Browse Source

convert the Conf class to singleton to avoid passing to all functions that need the object

Helmut Pozimski 6 years ago
parent
commit
92036f3a06

+ 17 - 0
lib_stov/configuration.py

@@ -33,6 +33,8 @@ class Conf(object):
     """This class is used to create the object which is responsible for all
     configuration operations.
     """
+    _instance = None
+
     def __init__(self):
         """Constructor
 
@@ -91,6 +93,21 @@ class Conf(object):
             self.values["database"]
         self.outputlevel = "default"
 
+    def __new__(cls, *args, **kwargs):
+        if not Conf._instance:
+            Conf._instance = super(Conf, cls).__new__(cls)
+        return Conf._instance
+
+    @staticmethod
+    def get_instance():
+        """
+        Returns the singleton instance of the object
+
+        :return: Conf object
+        :rtype: lib_stov.configuration.Conf
+        """
+        return Conf._instance
+
     def write_config(self):
         """Writes the configuration from the dictionary into the configuration
         file for stov. The configuration is written into the home directory of

+ 10 - 10
lib_stov/database.py

@@ -80,9 +80,7 @@ class Db(object):
     @staticmethod
     def get_instance():
         """ Return the singleton instance of Db"""
-        if Db._instance:
-            return Db._instance
-        return None
+        return Db._instance
 
     def populate(self):
         """Populates the database with the initial structure."""
@@ -205,9 +203,10 @@ class Db(object):
         cursor = self._execute_statement(video_query, (subscription_id,))
         result = cursor.fetchall()
         for video in result:
-            videos_list.append(generic_video.Video(
-                video_id=video[0], title=video[1], site_id=video[2],
-                downloaded=video[3], failcount=video[4], conf=conf))
+            videos_list.append(
+                generic_video.Video(title=video[1], site_id=video[2],
+                                    downloaded=video[3], failcount=video[4],
+                                    video_id=video[0]))
         return videos_list
 
     def video_in_database(self, ytid):
@@ -297,10 +296,11 @@ class Db(object):
         result_cursor = self._execute_statement(subscriptions_query)
         result = result_cursor.fetchall()
         for sub in result:
-            subscriptions_list.append(subscription.Sub(
-                subscription_id=sub[0], title=sub[1], subscription_type=sub[2],
-                name=sub[3], search=sub[4], directory=sub[5], disabled=sub[6],
-                site=sub[7], conf=conf))
+            subscriptions_list.append(
+                subscription.Sub(subscription_type=sub[2], name=sub[3],
+                                 site=sub[7], search=sub[4],
+                                 subscription_id=sub[0], title=sub[1],
+                                 directory=sub[5], disabled=sub[6]))
         return subscriptions_list
 
     def vacuum(self):

+ 5 - 5
lib_stov/generic_video.py

@@ -23,6 +23,7 @@ import logging
 
 from lib_stov import stov_exceptions
 from lib_stov import youtubedl_wrapper
+from lib_stov import configuration
 
 LOGGER = logging.getLogger("stov")
 
@@ -31,12 +32,11 @@ class Video(object):
     """This class stores all the attributes of a single video and is
     also able to download it using youtube-dl.
     """
-    def __init__(self, title, site_id, conf, downloaded, failcount=0,
-                 video_id=0):
+    def __init__(self, title, site_id, downloaded, failcount=0, video_id=0):
         self._id = video_id
         self.title = title
         self.site_id = site_id
-        self._conf = conf
+        self._conf = configuration.Conf.get_instance()
         self.downloaded = downloaded
         self.failcnt = int(failcount)
 
@@ -66,14 +66,14 @@ class Video(object):
         os.chdir(targetdir)
         if self.downloaded == 0:
             try:
-                youtubedl_wrapper.download_video(self._conf, url,
-                                                 itag_value)
+                youtubedl_wrapper.download_video(url, itag_value)
             except stov_exceptions.YoutubeDlCallFailed:
                 self.failcnt = int(self.failcnt) + 1
                 return False
             else:
                 self.downloaded = 1
                 return True
+        return False
 
     def get_id(self):
         """Resturns the id attribute assigned to the object."""

+ 4 - 6
lib_stov/helpers.py

@@ -264,15 +264,14 @@ def setup_configuration(args):
     return conf
 
 
-def setup_database(conf):
+def setup_database():
     """ Sets up the database and provides a DB object to talk to the database
     in the application.
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :return: database object
     :rtype: lib_stov.database.Db
     """
+    conf = configuration.Conf.get_instance()
     LOGGER.debug(_("Connecting to stov database"))
     if os.access(conf.dbpath, os.F_OK):
         try:
@@ -317,12 +316,11 @@ def setup_database(conf):
     return db
 
 
-def find_youtubedl(conf):
+def find_youtubedl():
     """
     Tries to find youtube-dl and writes it's path to the configuration file
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     """
+    conf = configuration.Conf.get_instance()
     if conf.values["youtube-dl"] == "":
         youtubedl_path = find_executable("youtube-dl")
         conf.values["youtube-dl"] = youtubedl_path

+ 10 - 10
lib_stov/main.py

@@ -32,36 +32,36 @@ def main():
     parser = helpers.parse_arguments()
     arguments = parser.parse_args()
     helpers.create_lock()
-    conf = helpers.setup_configuration(arguments)
+    helpers.setup_configuration(arguments)
     logger = logging.getLogger("stov")
-    helpers.setup_database(conf)
-    helpers.find_youtubedl(conf)
+    helpers.setup_database()
+    helpers.find_youtubedl()
     program.initialize_sites()
     if arguments.add:
         if arguments.site:
-            program.add_subscription(conf, arguments.channel,
+            program.add_subscription(arguments.channel,
                                      arguments.searchparameter,
                                      arguments.playlist, arguments.site)
         else:
-            program.add_subscription(conf, arguments.channel,
+            program.add_subscription(arguments.channel,
                                      arguments.searchparameter,
                                      arguments.playlist)
     elif arguments.lssites:
         program.list_sites()
     elif arguments.list:
-        program.list_subscriptions(conf)
+        program.list_subscriptions()
     elif arguments.deleteid:
         program.delete_subscription(arguments.deleteid)
     elif arguments.update is not None:
-        program.update_subscriptions(conf, arguments.update)
+        program.update_subscriptions(arguments.update)
     elif arguments.download is not None:
-        program.download_notify(conf, arguments.download)
+        program.download_notify(arguments.download)
     elif arguments.subscriptionid:
-        program.list_videos(conf, arguments.subscriptionid)
+        program.list_videos(arguments.subscriptionid)
     elif arguments.catchup:
         program.catchup(arguments.catchup)
     elif arguments.cleanup:
-        program.clean_database(conf)
+        program.clean_database()
     elif arguments.enableid:
         program.change_subscription_state(arguments.enableid, True)
     elif arguments.disableid:

+ 54 - 80
lib_stov/program.py

@@ -30,17 +30,17 @@ from email.mime.multipart import MIMEMultipart
 from lib_stov import subscription
 from lib_stov import stov_exceptions
 from lib_stov.database import Db
+from lib_stov.configuration import Conf
 
 LOGGER = logging.getLogger("stov")
 DATABASE = Db.get_instance()
+CONFIGURATION = Conf.get_instance()
 
 
-def add_subscription(conf, channel="", search="", playlist="", site="youtube"):
+def add_subscription(channel="", search="", playlist="", site="youtube"):
     """
     Takes care of adding a new subscription to the database.
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param site: site the subscription is about to be created for
     :type site: str
     :param channel: optional channel name
@@ -56,25 +56,21 @@ def add_subscription(conf, channel="", search="", playlist="", site="youtube"):
     try:
         if channel and not search:
             new_subscription = subscription.Sub(subscription_type="user",
-                                                name=channel, conf=conf,
-                                                site=site)
+                                                name=channel, site=site)
         elif channel and search:
             new_subscription = subscription.Sub(subscription_type="user",
-                                                name=channel,
-                                                search=search,
-                                                conf=conf, site=site)
+                                                name=channel, site=site,
+                                                search=search)
         elif not channel and search:
             new_subscription = subscription.Sub(subscription_type="search",
-                                                name=_("Search_"),
-                                                search=search,
-                                                conf=conf, site=site)
+                                                name=_("Search_"), site=site,
+                                                search=search)
         elif playlist:
             if search:
                 LOGGER.error(_("Playlists do not support searching, the "
                                "search option will be ignored!"))
             new_subscription = subscription.Sub(subscription_type="playlist",
-                                                name=playlist,
-                                                conf=conf, site=site)
+                                                name=playlist, site=site)
         else:
             LOGGER.error(_("None or invalid subscription type given, please "
                            "check the type option and try again."))
@@ -120,14 +116,12 @@ def add_subscription(conf, channel="", search="", playlist="", site="youtube"):
                 _(" successfully added"))
 
 
-def list_subscriptions(conf):
+def list_subscriptions():
     """
     Prints a list of subscriptions from the database.
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     """
-    subscriptions_list = DATABASE.get_subscriptions(conf)
+    subscriptions_list = DATABASE.get_subscriptions(CONFIGURATION)
     sub_state = None
     if subscriptions_list:
         LOGGER.info(_("ID Title Site"))
@@ -161,19 +155,17 @@ def delete_subscription(sub_id):
         LOGGER.info(_("Subscription deleted successfully!"))
 
 
-def update_subscriptions(conf, subscriptions=None):
+def update_subscriptions(subscriptions=None):
     """
     Updates data about videos in a subscription.
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param subscriptions: list of subscriptions to update
     :type subscriptions: list
     """
-    subscriptions_list = get_subscriptions(conf, subscriptions)
+    subscriptions_list = get_subscriptions(subscriptions)
     for element in subscriptions_list:
         LOGGER.debug(_("Updating subscription %s"), element.get_title())
-        videos = DATABASE.get_videos(element.get_id(), conf)
+        videos = DATABASE.get_videos(element.get_id(), CONFIGURATION)
         element.gather_videos(videos)
         try:
             element.update_data()
@@ -195,12 +187,10 @@ def update_subscriptions(conf, subscriptions=None):
                                        "database."), video.title)
 
 
-def download_videos(conf, subscriptions=None):
+def download_videos(subscriptions=None):
     """
     Downloads videos that haven't been previously downloaded.
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param subscriptions: list of subscriptions to consider for downloading
     :type subscriptions: list
     :return: tuple containing (in that order) downloaded videos, failed \
@@ -208,11 +198,11 @@ def download_videos(conf, subscriptions=None):
     :rtype: tuple
     """
     video_titles = []
-    subscriptions_list = get_subscriptions(conf, subscriptions)
+    subscriptions_list = get_subscriptions(subscriptions)
     videos_downloaded = 0
     videos_failed = 0
     for sub in subscriptions_list:
-        videos = DATABASE.get_videos(sub.get_id(), conf)
+        videos = DATABASE.get_videos(sub.get_id(), CONFIGURATION)
         sub.gather_videos(videos)
         try:
             sub.download_videos()
@@ -226,7 +216,7 @@ def download_videos(conf, subscriptions=None):
         for video in sub.failed_videos:
             try:
                 DATABASE.update_video_fail_count(video.failcnt, video.get_id())
-                if video.failcnt >= int(conf.values["maxfails"]):
+                if video.failcnt >= int(CONFIGURATION.values["maxfails"]):
                     DATABASE.disable_failed_video(video.get_id())
             except stov_exceptions.DBWriteAccessFailedException as error:
                 LOGGER.error(error)
@@ -234,12 +224,10 @@ def download_videos(conf, subscriptions=None):
     return (videos_downloaded, videos_failed, video_titles)
 
 
-def compose_email(conf, downloaded_videos, video_titles):
+def compose_email(downloaded_videos, video_titles):
     """
     Composes an e-mail that can be send out to the user.
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param downloaded_videos: number of downloaded videos
     :type downloaded_videos: int
     :param video_titles: titles of the downloaded videos
@@ -257,8 +245,8 @@ def compose_email(conf, downloaded_videos, video_titles):
         msg["Subject"] = _("Downloaded %i new videos") % downloaded_videos
         mail_text = _("The following episodes have been downloaded by "
                       "stov: \n\n")
-    msg["From"] = "stov <%s>" % conf.values["mailfrom"]
-    msg["To"] = "<%s>" % conf.values["mailto"]
+    msg["From"] = "stov <%s>" % CONFIGURATION.values["mailfrom"]
+    msg["To"] = "<%s>" % CONFIGURATION.values["mailto"]
     for line in video_titles:
         mail_text += line + "\n"
     msg_text = MIMEText(mail_text.encode("utf8"), _charset="utf8")
@@ -266,17 +254,15 @@ def compose_email(conf, downloaded_videos, video_titles):
     return msg
 
 
-def send_email(conf, msg):
+def send_email(msg):
     """
     Sends an e-mail to the user.
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param msg: message to be sent
     :type msg: MIMEMultipart
     """
-    server_connection = smtplib.SMTP(conf.values["mailhost"],
-                                     conf.values["smtpport"])
+    server_connection = smtplib.SMTP(CONFIGURATION.values["mailhost"],
+                                     CONFIGURATION.values["smtpport"])
     try:
         server_connection.connect()
     except (smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected,
@@ -288,10 +274,10 @@ def send_email(conf, msg):
             server_connection.starttls()
         except smtplib.SMTPException:
             LOGGER.debug(_("TLS not available, proceeding unencrypted."))
-        if conf.values["auth_needed"] == "yes":
+        if CONFIGURATION.values["auth_needed"] == "yes":
             try:
-                server_connection.login(conf.values["user_name"],
-                                        conf.values["password"])
+                server_connection.login(CONFIGURATION.values["user_name"],
+                                        CONFIGURATION.values["password"])
             except smtplib.SMTPAuthenticationError:
                 LOGGER.error(_("Authentication failed, please check user "
                                "name and password!"))
@@ -299,8 +285,8 @@ def send_email(conf, msg):
                 LOGGER.error(_("Could not authenticate, server probably "
                                "does not support authentication!"))
         try:
-            server_connection.sendmail(conf.values["mailfrom"],
-                                       conf.values["mailto"],
+            server_connection.sendmail(CONFIGURATION.values["mailfrom"],
+                                       CONFIGURATION.values["mailto"],
                                        msg.as_string())
         except smtplib.SMTPRecipientsRefused:
             LOGGER.error(_("The server refused the recipient address, "
@@ -311,12 +297,10 @@ def send_email(conf, msg):
         server_connection.quit()
 
 
-def list_videos(conf, sub_id):
+def list_videos(sub_id):
     """
     Lists all videos in a specified subscription
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param sub_id: ID of the subscription
     :type sub_id: int
     """
@@ -327,15 +311,13 @@ def list_videos(conf, sub_id):
         sys.exit(1)
     else:
         if data:
-            sub = subscription.Sub(subscription_id=data[0][0],
-                                   title=data[0][1],
-                                   subscription_type=data[0][2],
-                                   name=data[0][3],
+            sub = subscription.Sub(subscription_type=data[0][2],
+                                   name=data[0][3], site=data[0][7],
                                    search=data[0][4],
-                                   directory=data[0][5],
-                                   disabled=data[0][6],
-                                   site=data[0][7], conf=conf)
-            videos = DATABASE.get_videos(sub.get_id(), conf)
+                                   subscription_id=data[0][0],
+                                   title=data[0][1], directory=data[0][5],
+                                   disabled=data[0][6])
+            videos = DATABASE.get_videos(sub.get_id(), CONFIGURATION)
             sub.gather_videos(videos)
             videos_list = sub.print_videos()
             for video in videos_list:
@@ -368,17 +350,15 @@ def catchup(sub_id):
                            "please check if the ID given is correct."))
 
 
-def clean_database(conf):
+def clean_database():
     """
     Initiates a database cleanup, deleting all videos that are no longer
     in the scope of the query and vacuuming the database to free up space.
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     """
-    subscription_list = DATABASE.get_subscriptions(conf)
+    subscription_list = DATABASE.get_subscriptions(CONFIGURATION)
     for element in subscription_list:
-        videos = DATABASE.get_videos(element.get_id(), conf)
+        videos = DATABASE.get_videos(element.get_id(), CONFIGURATION)
         element.check_and_delete(videos)
         for delete_video in element.to_delete:
             LOGGER.debug(_("Deleting video %s from "
@@ -454,30 +434,28 @@ def print_license():
         along with stov.  If not, see <http://www.gnu.org/licenses/>.""")
 
 
-def download_notify(conf, subscriptions=None):
+def download_notify(subscriptions=None):
     """
     starts an update of not yet downloaded videos and notifies the user
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param subscriptions: list of subscriptions to consider for downloading
     :type subscriptions: list
     """
     videos_downloaded, videos_failed, video_titles = \
-        download_videos(conf, subscriptions)
-    if videos_downloaded > 0 and conf.values["notify"] == "yes":
-        msg = compose_email(conf, videos_downloaded, video_titles)
-        send_email(conf, msg)
+        download_videos(subscriptions)
+    if videos_downloaded > 0 and CONFIGURATION.values["notify"] == "yes":
+        msg = compose_email(videos_downloaded, video_titles)
+        send_email(msg)
     elif videos_downloaded == 0 and videos_failed == 0:
-        if conf.values["notify"] == "no":
+        if CONFIGURATION.values["notify"] == "no":
             LOGGER.info(_("There are no videos to be downloaded."))
-    elif conf.values["notify"] == "no":
+    elif CONFIGURATION.values["notify"] == "no":
         if videos_failed == 0:
             LOGGER.info(_("The following videos have been downloaded:\n"))
             for i in video_titles:
                 LOGGER.info(i)
     else:
-        if conf.values["notify"] != "yes":
+        if CONFIGURATION.values["notify"] != "yes":
             LOGGER.error(_("Could not determine how you want to be informed "
                            "about new videos, please check the notify "
                            "parameter in your configuration."))
@@ -513,13 +491,11 @@ def list_sites():
         LOGGER.info(entry[1])
 
 
-def get_subscriptions(conf, subscriptions=None):
+def get_subscriptions(subscriptions=None):
     """
     Retrieves all or only specific subscriptions from the database and
     returns them as a list of subscription objects.
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param subscriptions: list of subscriptions to retrieve
     :type subscriptions: list
     :return: list of subscription objects
@@ -530,19 +506,17 @@ def get_subscriptions(conf, subscriptions=None):
         for element in subscriptions:
             data = DATABASE.get_subscription(element)
             if data:
-                sub = subscription.Sub(subscription_id=data[0][0],
-                                       title=data[0][1],
-                                       subscription_type=data[0][2],
-                                       name=data[0][3],
+                sub = subscription.Sub(subscription_type=data[0][2],
+                                       name=data[0][3], site=data[0][7],
                                        search=data[0][4],
-                                       directory=data[0][5],
-                                       disabled=data[0][6],
-                                       site=data[0][7], conf=conf)
+                                       subscription_id=data[0][0],
+                                       title=data[0][1], directory=data[0][5],
+                                       disabled=data[0][6])
                 subscriptions_list.append(sub)
             else:
                 LOGGER.error(
                     _("Invalid subscription, please check the list and "
                       "try again."))
     else:
-        subscriptions_list = DATABASE.get_subscriptions(conf)
+        subscriptions_list = DATABASE.get_subscriptions(CONFIGURATION)
     return subscriptions_list

+ 6 - 6
lib_stov/subscription.py

@@ -24,7 +24,7 @@ from lib_stov import stov_exceptions
 from lib_stov import yt_noapi
 from lib_stov import zdf_mediathek
 from lib_stov import twitch
-
+from lib_stov import configuration
 
 LOGGER = logging.getLogger("stov")
 
@@ -33,7 +33,7 @@ class Sub(object):
     """This class constructs a object that stores all the attributes that define
     a subscription and performs the necessary operations on it.
     """
-    def __init__(self, subscription_type, name, conf, site, search="",
+    def __init__(self, subscription_type, name, site, search="",
                  subscription_id=0, title="", directory="", disabled=0):
         self._id = subscription_id
         self._title = title
@@ -41,7 +41,7 @@ class Sub(object):
         self._name = name
         self._search = search
         self._directory = directory
-        self._conf = conf
+        self._conf = configuration.Conf.get_instance()
         self.site = site
         self.downloaded_videos = []
         self.failed_videos_count = 0
@@ -58,13 +58,13 @@ class Sub(object):
 
         if site == "youtube":
             self._connector = yt_noapi.Connector(self._type, self._name,
-                                                 self._conf, self._search)
+                                                 self._search)
         elif site == "zdf_mediathek":
             self._connector = zdf_mediathek.Connector(self._type, self._name,
-                                                      self._conf, self._search)
+                                                      self._search)
         elif site == "twitch":
             self._connector = twitch.Connector(self._type, self._name,
-                                               self._conf, self._search)
+                                               self._search)
         else:
             raise stov_exceptions.SiteUnsupported()
 

+ 5 - 7
lib_stov/twitch.py

@@ -33,10 +33,9 @@ class Connector(yt_noapi.Connector):
     """ Connector class, performing calls to youtube-dl to retrieve
         information about videos from twitch.tv
     """
-    def __init__(self, subscription_type, name, conf, search=""):
+    def __init__(self, subscription_type, name, search=""):
         """Populates the object with all necessary data."""
-        yt_noapi.Connector.__init__(self, subscription_type, name,
-                                    conf, search)
+        yt_noapi.Connector.__init__(self, subscription_type, name, search)
 
     def _construct_url(self):
         """ Constructs the URL for the subscription to retrieve
@@ -96,7 +95,6 @@ class Connector(yt_noapi.Connector):
         if quality_value:
             LOGGER.debug(_("Found value: %s."), quality_value)
             return quality_value + "/" + config.values["videocodec"]
-        else:
-            LOGGER.debug(_("Could not determine an itag value "
-                           "from the configuration"))
-            return "1080p" + "/" + config.values["videocodec"]
+        LOGGER.debug(_("Could not determine an itag value "
+                       "from the configuration"))
+        return "1080p" + "/" + config.values["videocodec"]

+ 24 - 28
lib_stov/youtubedl_wrapper.py

@@ -23,15 +23,15 @@ import sys
 import logging
 
 from lib_stov import stov_exceptions
+from lib_stov import configuration
 
 LOGGER = logging.getLogger("stov")
+CONFIGURATION = configuration.Conf.get_instance()
 
 
-def get_ids(conf, url, reverse=False):
+def get_ids(url, reverse=False):
     """
     Retrieves the IDs
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param url: URL to pass to youtube-dl
     :type url: str
     :param reverse: look up a playlist in reverse order to get \
@@ -41,24 +41,24 @@ def get_ids(conf, url, reverse=False):
     :rtype: list
     """
     videos_list = []
-    if conf.outputlevel == "verbose":
+    if CONFIGURATION.outputlevel == "verbose":
         stderr = sys.stderr
     else:
         stderr = open("/dev/null", "w")
     LOGGER.debug(_("Executing command: %s %s %s %s %s %s"),
-                 conf.values["youtube-dl"], "--max-downloads",
-                 conf.values["maxvideos"], "-i", "--get-id", url)
+                 CONFIGURATION.values["youtube-dl"], "--max-downloads",
+                 CONFIGURATION.values["maxvideos"], "-i", "--get-id", url)
     try:
         if reverse:
             video_ids = subprocess.check_output(
-                [conf.values["youtube-dl"], "--max-downloads",
-                 conf.values["maxvideos"], "-i", "--playlist-reverse",
+                [CONFIGURATION.values["youtube-dl"], "--max-downloads",
+                 CONFIGURATION.values["maxvideos"], "-i", "--playlist-reverse",
                  "--get-id", url], stderr=stderr)
         else:
             video_ids = subprocess.check_output(
-                [conf.values["youtube-dl"], "--max-downloads",
-                conf.values["maxvideos"],
-                "-i", "--get-id", url], stderr=stderr)
+                [CONFIGURATION.values["youtube-dl"], "--max-downloads",
+                 CONFIGURATION.values["maxvideos"],
+                 "-i", "--get-id", url], stderr=stderr)
     except subprocess.CalledProcessError as error_message:
         video_ids = error_message.output
     video_ids = video_ids.decode(sys.stdout.encoding).strip()
@@ -68,33 +68,29 @@ def get_ids(conf, url, reverse=False):
     return videos_list
 
 
-def get_title(conf, url):
+def get_title(url):
     """
     Retrieves the title of a specified video
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param url: URL to pass to youtube-dl
     :type url: str
     """
-    if conf.outputlevel == "verbose":
+    if CONFIGURATION.outputlevel == "verbose":
         stderr = sys.stderr
     else:
         stderr = open("/dev/null", "w")
     LOGGER.debug(_("Executing command: %s %s %s"),
-                 conf.values["youtube-dl"], "--get-title", url)
+                 CONFIGURATION.values["youtube-dl"], "--get-title", url)
     video_title = subprocess.check_output([
-        conf.values["youtube-dl"], "--get-title", url], stderr=stderr)
+        CONFIGURATION.values["youtube-dl"], "--get-title", url], stderr=stderr)
     video_title = video_title.decode(sys.stdout.encoding)
     return video_title
 
 
-def download_video(conf, url, itag_value):
+def download_video(url, itag_value):
     """
     Downloads a video from a specified url using youtube-dl.
 
-    :param conf: configuration object
-    :type conf: lib_stov.configuration.Conf
     :param itag_value: video and audio parameter
     :type itag_value: str
     :param url: URL to pass to youtube-dl
@@ -102,21 +98,21 @@ def download_video(conf, url, itag_value):
     """
     try:
         LOGGER.debug(_("Executing command: %s -f %s %s"),
-                     conf.values["youtube-dl"], itag_value, url)
-        if conf.outputlevel == "default":
-            subprocess.check_call([conf.values["youtube-dl"], "-f %s"
+                     CONFIGURATION.values["youtube-dl"], itag_value, url)
+        if CONFIGURATION.outputlevel == "default":
+            subprocess.check_call([CONFIGURATION.values["youtube-dl"], "-f %s"
                                    % itag_value,
                                    "-o", "%(title)s-%(id)s.%(ext)s", url],
                                   stderr=sys.stderr,
                                   stdout=open("/dev/null", "w"))
-        elif conf.outputlevel == "verbose":
-            subprocess.check_call([conf.values["youtube-dl"], "-f %s"
+        elif CONFIGURATION.outputlevel == "verbose":
+            subprocess.check_call([CONFIGURATION.values["youtube-dl"], "-f %s"
                                    % itag_value,
                                    "-o", "%(title)s-%(id)s.%(ext)s", url],
                                   stderr=sys.stderr, stdout=sys.stdout)
-        elif conf.outputlevel == "quiet":
-            subprocess.check_call([conf.values["youtube-dl"], "-f %s/%s"
-                                   % itag_value,
+        elif CONFIGURATION.outputlevel == "quiet":
+            subprocess.check_call([CONFIGURATION.values["youtube-dl"],
+                                   "-f %s/%s" % itag_value,
                                    "-o", "%(title)s-%(id)s.%(ext)s", url],
                                   stderr=open("/dev/null", "w"),
                                   stdout=open("/dev/null", "w"))

+ 10 - 11
lib_stov/yt_noapi.py

@@ -28,6 +28,7 @@ import logging
 import lxml.html
 from lib_stov import stov_exceptions
 from lib_stov import youtubedl_wrapper
+from lib_stov import configuration
 
 LOGGER = logging.getLogger("stov")
 
@@ -53,12 +54,12 @@ class Connector(object):
     """This class will retrieve all the necessary data from youtube using
     youtube-dl, thus bypassing the API.
     """
-    def __init__(self, subscription_type, name, conf, search=""):
+    def __init__(self, subscription_type, name, search=""):
         """Populates the object with all necessary data."""
         self._type = subscription_type
         self._name = name
         self._search = search
-        self._conf = conf
+        self._conf = configuration.Conf.get_instance()
         self._title = ""
         self._url = ""
         self._construct_url()
@@ -121,12 +122,11 @@ class Connector(object):
         """Retrieves all the relevant videos in a subscription."""
         videos_list = []
         if self._type == "user" and self._search:
-            video_ids = youtubedl_wrapper.get_ids(self._conf, self._url)
+            video_ids = youtubedl_wrapper.get_ids(self._url)
         elif self._type == "playlist":
-            video_ids = youtubedl_wrapper.get_ids(self._conf, self._url,
-                                                  reverse=True)
+            video_ids = youtubedl_wrapper.get_ids(self._url, reverse=True)
         else:
-            video_ids = youtubedl_wrapper.get_ids(self._conf, self._url)
+            video_ids = youtubedl_wrapper.get_ids(self._url)
         LOGGER.debug("Got video IDs: %s", video_ids)
         if video_ids:
             for video_id in video_ids:
@@ -139,7 +139,7 @@ class Connector(object):
                 if not video_exists:
                     try:
                         video_title = youtubedl_wrapper.get_title(
-                            self._conf, self.construct_video_url(video_id))
+                            self.construct_video_url(video_id))
                     except subprocess.CalledProcessError:
                         raise stov_exceptions.YoutubeDlCallFailed()
                     else:
@@ -215,7 +215,6 @@ class Connector(object):
         if itag_value:
             LOGGER.debug(_("Found value: %s."), itag_value)
             return str(itag_value) + "/" + config.values["videocodec"]
-        else:
-            LOGGER.debug(_("Could not determine an itag value "
-                           "from the configuration"))
-            return "38"
+        LOGGER.debug(_("Could not determine an itag value "
+                       "from the configuration"))
+        return "38"

+ 6 - 6
lib_stov/zdf_mediathek.py

@@ -24,6 +24,7 @@ import urllib.request
 from datetime import datetime, timedelta
 
 from lib_stov import stov_exceptions
+from lib_stov import configuration
 
 LOGGER = logging.getLogger("stov")
 
@@ -49,13 +50,13 @@ class ZDFVideo(object):
 
 class Connector(object):
     """Connector class performing operations against the API"""
-    def __init__(self, subscription_type, name, conf, search=""):
+    def __init__(self, subscription_type, name, search=""):
         if subscription_type == "user":
             self._type = "channel"
         else:
             self._type = subscription_type
         self._name = name
-        self._conf = conf
+        self._conf = configuration.Conf.get_instance()
         self._search = search
         if self._type != "channel":
             raise stov_exceptions.TypeNotSupported()
@@ -154,7 +155,6 @@ class Connector(object):
         if quality_value:
             LOGGER.debug(_("Found value: %s."), quality_value)
             return quality_value + "/" + config.values["videocodec"]
-        else:
-            LOGGER.debug(_("Could not determine an itag value "
-                           "from the configuration"))
-            return "hls-3286" + "/" + config.values["videocodec"]
+        LOGGER.debug(_("Could not determine an itag value "
+                       "from the configuration"))
+        return "hls-3286" + "/" + config.values["videocodec"]