Răsfoiți Sursa

coding style adjustments based on pylint complaints, mainly variable, method and class renaming

Helmut Pozimski 9 ani în urmă
părinte
comite
b5f8cbfdd9
6 a modificat fișierele cu 231 adăugiri și 187 ștergeri
  1. 24 16
      lib_stov/configuration.py
  2. 52 48
      lib_stov/database.py
  3. 17 8
      lib_stov/noapi.py
  4. 15 0
      lib_stov/stov_exceptions.py
  5. 62 54
      lib_stov/subscription.py
  6. 61 61
      stov

+ 24 - 16
lib_stov/configuration.py

@@ -15,6 +15,11 @@
 
 # -*- coding: utf8 -*-
 
+"""This file takes care of reading, storing and updating the configuration of
+stov, the configuration file is expected to be in json format and reside in
+~/.stov/stov.json.
+"""
+
 import os
 import subprocess
 import json
@@ -22,7 +27,10 @@ import json
 from lib_stov import stov_exceptions
 
 
-class conf(object):
+class Conf(object):
+    """This class is used to create the object which is responsible for all
+    configuration operations.
+    """
     def __init__(self):
         """Constructor
 
@@ -81,7 +89,7 @@ class conf(object):
             self.values["database"]
         self.outputlevel = "default"
 
-    def WriteConfig(self):
+    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
         the user by default.
@@ -96,7 +104,7 @@ class conf(object):
             json.dump(self.values, configfile, indent=0)
             configfile.close()
 
-    def Initialize(self):
+    def initialize(self):
         """Creates the necessary directory for the stov configuration and
         calls the internal methods to create the database and the
         configuration file.
@@ -110,9 +118,9 @@ class conf(object):
             process = subprocess.Popen(["which", "youtube-dl"],
                                        stdout=subprocess.PIPE)
             self.values["youtube-dl"] = process.communicate()[0].strip()
-            self.WriteConfig()
+            self.write_config()
 
-    def ReadOldConfig(self):
+    def read_old_config(self):
         """Reads the existing plain text configuration file and places the
         values in the dictionary. Existing values (such as default values)
         are overwritten.
@@ -131,7 +139,7 @@ class conf(object):
         self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
             self.values["database"]
 
-    def ReadConfig(self):
+    def read_config(self):
         """Reads the existing json configuration files and loads the values in
         the dictionary.
         """
@@ -144,7 +152,7 @@ class conf(object):
             self.values.update(json.load(configfile))
             configfile.close()
 
-    def CheckConfig(self):
+    def check_config(self):
         """Checks if the configuration is up-to-date with the running
         stov version.
 
@@ -154,7 +162,7 @@ class conf(object):
         except ValueError:
             raise stov_exceptions.InvalidConfigurationVersionException()
         self.values["config_version"] = "0"
-        self.ReadConfig()
+        self.read_config()
         if self.values["config_version"] == "0" \
                 or int(self.values["config_version"]) < currentversion:
             self.values["config_version"] = str(currentversion)
@@ -163,18 +171,18 @@ class conf(object):
             self.values["config_version"] = currentversion
             return True
 
-    def UpdateConfig(self):
+    def update_config(self):
         """Update the configuration to the latest version"""
         versionbuffer = self.values["config_version"]
-        self.ReadConfig()
+        self.read_config()
         self.values["config_version"] = versionbuffer
-        self.WriteConfig()
+        self.write_config()
 
-    def CheckDB(self):
+    def check_db(self):
         """Checks the database if it is up-to-date"""
         currentdbversion = int(self.values["db_version"])
         self.values["db_version"] = "0"
-        self.ReadConfig()
+        self.read_config()
         if self.values["db_version"] == "0" or \
                 int(self.values["db_version"]) <\
                 int(currentdbversion):
@@ -184,7 +192,7 @@ class conf(object):
             self.values["db_version"] = str(currentdbversion)
             return True
 
-    def GetYoutubeParameter(self):
+    def get_youtube_parameter(self):
         """Determines which itag value results from codec and resolution
         settings and returns it
 
@@ -242,8 +250,8 @@ class conf(object):
         the new and shiny json configuration file.
         """
         try:
-            self.ReadOldConfig()
-            self.WriteConfig()
+            self.read_old_config()
+            self.write_config()
         except stov_exceptions.ConfigFileReadErrorException:
             raise stov_exceptions.ConfigurationMigrationFailed()
         except stov_exceptions.ConfigFileWriteErrorException:

+ 52 - 48
lib_stov/database.py

@@ -15,7 +15,7 @@
 
 # -*- coding: utf8 -*-
 
-from __future__ import unicode_literals
+"""This module is responsible for all database related operations."""
 
 import sqlite3
 
@@ -24,7 +24,11 @@ from lib_stov import youtube
 from lib_stov import subscription
 
 
-class db(object):
+class Db(object):
+    """This class is used to cosntruct the module which will take care of all
+    database related operations like opening the database, reading from and
+    writing to it.
+    """
     def __init__(self, path, version):
         """Constructor of the db class, populates the object with the relevant
         attributes, connects to the database and creates it if asked to.
@@ -45,7 +49,7 @@ class db(object):
 
         self.__connection.close()
 
-    def __ExecuteStatement(self, statement, argument=None):
+    def _execute_statement(self, statement, argument=None):
         """Executes a statement, works as a wrapper around cursor execute."""
 
         try:
@@ -59,10 +63,10 @@ class db(object):
             self.__connection.commit()
             return result
 
-    def Populate(self):
+    def populate(self):
         """Populates the database with the initial structure."""
 
-        self.__ExecuteStatement("""CREATE TABLE subscriptions (
+        self._execute_statement("""CREATE TABLE subscriptions (
             id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
             title TEXT,
             name TEXT,
@@ -71,7 +75,7 @@ class db(object):
             directory TEXT,
             disabled INTEGER DEFAULT 0
             );""")
-        self.__ExecuteStatement("""CREATE TABLE videos (
+        self._execute_statement("""CREATE TABLE videos (
             id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
             title TEXT,
             description TEXT,
@@ -81,43 +85,43 @@ class db(object):
             failcnt INTEGER DEFAULT 0
             );""")
 
-    def Update(self):
+    def update(self):
         """Updates the database structure to match the current version"""
 
         if int(self.__version) == 1:
-            """Changes between version 1 and 2"""
-            self.__ExecuteStatement("ALTER TABLE videos ADD COLUMN failcnt \
+            # Changes between version 1 and 2
+            self._execute_statement("ALTER TABLE videos ADD COLUMN failcnt \
             INTEGER DEFAULT 0;")
             self.__version = 2
         if int(self.__version) == 2:
-            """Changes between version 2 and 3"""
-            self.__ExecuteStatement("ALTER TABLE subscriptions ADD COLUMN"
+            # Changes between version 2 and 3
+            self._execute_statement("ALTER TABLE subscriptions ADD COLUMN"
                                     " disabled INTEGER DEFAULT 0;")
-            self.__ExecuteStatement("UPDATE subscriptions SET disabled=0;")
+            self._execute_statement("UPDATE subscriptions SET disabled=0;")
             self.__version = 3
 
-    def GetVersion(self):
+    def get_version(self):
         """Simple getter method, returns the DB version"""
 
         return self.__version
 
-    def DeleteSubscription(self, sub_id):
+    def delete_subscription(self, sub_id):
         """Deletes a subscription and all associated videos from the
         database
 
         """
 
         checkquery = "SELECT * FROM subscriptions WHERE id=?"
-        checkresult = self.__ExecuteStatement(checkquery, (sub_id,))
+        checkresult = self._execute_statement(checkquery, (sub_id,))
         if not checkresult.fetchall():
             raise stov_exceptions.SubscriptionNotFoundException()
         else:
             deletevideos = "DELETE FROM videos WHERE subscription_id=?"
-            self.__ExecuteStatement(deletevideos, (sub_id,))
+            self._execute_statement(deletevideos, (sub_id,))
             deletesubscription = "DELETE FROM subscriptions WHERE id=?"
-            self.__ExecuteStatement(deletesubscription, (sub_id,))
+            self._execute_statement(deletesubscription, (sub_id,))
 
-    def GetVideos(self, subscription_id, conf):
+    def get_videos(self, subscription_id, conf):
         """Gets all videos of a given subscription id from the database and
         returns them
 
@@ -125,7 +129,7 @@ class db(object):
         videos_list = []
         video_query = "SELECT id, title, description, ytid, downloaded, " \
                       "failcnt FROM videos WHERE subscription_id=?"
-        cursor = self.__ExecuteStatement(video_query, (subscription_id,))
+        cursor = self._execute_statement(video_query, (subscription_id,))
         result = cursor.fetchall()
         for video in result:
             videos_list.append(youtube.video(id=video[0], title=video[1],
@@ -136,93 +140,93 @@ class db(object):
                                              conf=conf))
         return videos_list
 
-    def VideoInDatabase(self, ytid):
+    def video_in_database(self, ytid):
         """Checks if the video with a given youtube id already exists in the
         database
 
         """
         video_query = "SELECT id FROM videos WHERE ytid=?"
-        cursor = self.__ExecuteStatement(video_query, (ytid,))
+        cursor = self._execute_statement(video_query, (ytid,))
         result = cursor.fetchall()
         if not result:
             return False
         else:
             return True
 
-    def InsertVideo(self, video, subscription_id):
+    def insert_video(self, video, subscription_id):
         """Inserts a video with the given data into the database"""
         video_insert = "INSERT INTO videos (title, description, ytid, \
                             subscription_id, downloaded) VALUES \
                             (?, ?, ?, ?, ?)"
         insert_data = (video.title, video.description, video.ytid,
                        subscription_id, 0)
-        self.__ExecuteStatement(video_insert, insert_data)
+        self._execute_statement(video_insert, insert_data)
 
-    def InsertSubscription(self, data):
+    def insert_subscription(self, data):
         """Inserts a subscription with the given data into the database"""
         subscription_insert = "INSERT INTO subscriptions (title, type, " \
                               "searchstring, directory, name, disabled) " \
                               "VALUES (?, ?, ?, ?, ?, ?)"
-        self.__ExecuteStatement(subscription_insert, data)
+        self._execute_statement(subscription_insert, data)
         subscription_getid = "SELECT id from subscriptions where title=?"
-        query_cursor = self.__ExecuteStatement(subscription_getid, (data[0],))
+        query_cursor = self._execute_statement(subscription_getid, (data[0],))
         subscription_id = query_cursor.fetchone()[0]
         return subscription_id
 
-    def UpdateVideoDownloadStatus(self, video_id, status):
+    def update_video_download_status(self, video_id, status):
         """Updates the download status of a video in the database"""
         update_statement = "UPDATE videos SET downloaded = ? WHERE id = ?"
-        self.__ExecuteStatement(update_statement, (status, video_id))
+        self._execute_statement(update_statement, (status, video_id))
 
-    def DisableFailedVideo(self, video_id):
+    def disable_failed_video(self, video_id):
         """Disables a video in the database"""
         update_statement = "UPDATE videos SET downloaded = -1 WHERE id = ?"
-        self.__ExecuteStatement(update_statement, (video_id,))
+        self._execute_statement(update_statement, (video_id,))
 
-    def UpdateVideoFailCount(self, count, video_id):
+    def update_video_fail_count(self, count, video_id):
         """Updates the fail count of a video in the database"""
         update_statement = "UPDATE videos SET failcnt = ? WHERE id = ?"
-        self.__ExecuteStatement(update_statement, (count, video_id))
+        self._execute_statement(update_statement, (count, video_id))
 
-    def DeleteVideo(self, video_id):
+    def delete_video(self, video_id):
         """Deletes a video from the database"""
         delete_statement = "DELETE FROM videos where id = ?"
-        self.__ExecuteStatement(delete_statement, (video_id,))
+        self._execute_statement(delete_statement, (video_id,))
 
-    def GetSubscription(self, sub_id):
+    def get_subscription(self, sub_id):
         """Retrieves a specific subscription from the database"""
         sub_query = "SELECT id,title,type,name,searchstring, directory," \
                     "disabled FROM subscriptions where id=?"
-        result_cursor = self.__ExecuteStatement(sub_query, (sub_id,))
+        result_cursor = self._execute_statement(sub_query, (sub_id,))
         result = result_cursor.fetchall()
         return result
 
-    def GetSubscriptionTitle(self, sub_id):
+    def get_subscription_title(self, sub_id):
         """Retrieves only the title of a specified subscription from the
         database
 
         """
         title_query = "SELECT title from subscriptions where id=?"
-        result_cursor = self.__ExecuteStatement(title_query, (sub_id,))
+        result_cursor = self._execute_statement(title_query, (sub_id,))
         result = result_cursor.fetchall()
         return result
 
-    def MarkVideosDownloaded(self, video_id):
+    def mark_video_downloaded(self, video_id):
         """ Marks all videos in a specified subscription as downloaded"""
         update_statement = "UPDATE videos SET downloaded = 1 " \
                            "WHERE subscription_id =?"
-        self.__ExecuteStatement(update_statement, (video_id,))
+        self._execute_statement(update_statement, (video_id,))
 
-    def GetSubscriptions(self, conf):
+    def get_subscriptions(self, conf):
         """Retrieves all subscriptions from the database"""
         subscriptions_list = []
         subscriptions_query = "SELECT id,title,type,name,searchstring," \
                               "directory,disabled FROM subscriptions"
-        result_cursor = self.__ExecuteStatement(subscriptions_query)
+        result_cursor = self._execute_statement(subscriptions_query)
         result = result_cursor.fetchall()
         for sub in result:
-            subscriptions_list.append(subscription.sub(id=sub[0], title=sub[1],
-                                                       type=sub[2],
+            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],
@@ -230,14 +234,14 @@ class db(object):
                                                        conf=conf))
         return subscriptions_list
 
-    def Vacuum(self):
+    def vacuum(self):
         """Vacuums the database, shrinking it in size"""
-        self.__ExecuteStatement("VACUUM")
+        self._execute_statement("VACUUM")
 
-    def ChangeSubscriptionState(self, sub_id, state):
+    def change_subscription_state(self, sub_id, state):
         """Enables or disables a subscription depending on the parameter
         state
 
         """
         update_statement = "UPDATE subscriptions SET disabled=? WHERE id=?"
-        self.__ExecuteStatement(update_statement, (state, sub_id))
+        self._execute_statement(update_statement, (state, sub_id))

+ 17 - 8
lib_stov/noapi.py

@@ -16,6 +16,9 @@
 
 # -*- coding: utf8 -*-
 
+"""This module provides all classes and methods that were provided by the
+youtubeAPI module earlier."""
+
 import subprocess
 import sys
 import lxml.html
@@ -26,12 +29,14 @@ from lib_stov import stov_exceptions
 
 
 class YtChannel(object):
+    """Stores the relevant attributes of a youtube channel."""
     def __init__(self):
         self.title = ""
         self.videos = []
 
 
 class YtVideo(object):
+    """Stores the relevant attributes of a single youtube video."""
     def __init__(self, title, description, ytid):
         self.title = title
         self.description = description
@@ -42,9 +47,9 @@ class Connector(object):
     """This class will retrieve all the necessary data from youtube using
     youtube-dl, thus bypassing the API.
     """
-    def __init__(self, type, name, conf, search=""):
+    def __init__(self, subscription_type, name, conf, search=""):
         """Populates the object with all necessary data."""
-        self._type = type
+        self._type = subscription_type
         self._name = name
         self._search = search
         self._conf = conf
@@ -53,6 +58,9 @@ class Connector(object):
         self._construct_url()
 
     def _construct_url(self):
+        """Constructs the URL to request from youtube-dl according to the
+        subscription type and the given parameters.
+        """
         if self._type == "channel":
             self._url = "https://www.youtube.com/user/%s" \
                         % urllib.parse.quote(self._name)
@@ -94,16 +102,16 @@ class Connector(object):
                     self._search,
                     "--get-id",
                     self._url], stderr=stderr).strip()
-            except subprocess.CalledProcessError as e:
-                video_ids = e.output.strip()
+            except subprocess.CalledProcessError as error_message:
+                video_ids = error_message.output.strip()
         else:
             try:
                 video_ids = subprocess.check_output([
                     self._conf.values["youtube-dl"], "--max-downloads",
                     self._conf.values["maxvideos"], "--get-id",
                     self._url], stderr=stderr).strip()
-            except subprocess.CalledProcessError as e:
-                video_ids = e.output.strip()
+            except subprocess.CalledProcessError as error_message:
+                video_ids = error_message.output.strip()
         if len(video_ids) >= 1:
             for video_id in video_ids.split("\n"):
                 video_exists = False
@@ -119,7 +127,8 @@ class Connector(object):
                             "https://www.youtube.com/watch?v=%s"
                             % video_id], stderr=stderr).strip()
                         video_description = subprocess.check_output([
-                            self._conf.values["youtube-dl"], "--get-description",
+                            self._conf.values["youtube-dl"],
+                            "--get-description",
                             "https://www.youtube.com/watch?v=%s"
                             % video_id], stderr=stderr).strip()
                     except subprocess.CalledProcessError:
@@ -131,7 +140,7 @@ class Connector(object):
                             video_id))
         return videos_list
 
-    def ParseAPIData(self, existing_videos):
+    def parse_api_data(self, existing_videos):
         """This method calls all necessary methods to retrieve the data
                 and assembles them into a Channel object. The naming of this
                 method was set according to the method in youtubeAPI to be

+ 15 - 0
lib_stov/stov_exceptions.py

@@ -15,6 +15,8 @@
 
 # -*- coding: utf8 -*-
 
+"""This module contains all custome exceptions used by stov."""
+
 
 class DBConnectionFailedException(Exception):
     """ This exception will be raised when the initial connetion attempt
@@ -23,6 +25,7 @@ class DBConnectionFailedException(Exception):
     """
 
     def __init__(self):
+        super(DBConnectionFailedException, self).__init__()
         self.__message = _("Could not access the database, please check path"
                            " and permissions and try again!")
 
@@ -37,6 +40,7 @@ class DBWriteAccessFailedException(Exception):
     """
 
     def __init__(self):
+        super(DBWriteAccessFailedException, self).__init__()
         self.__message = _("Write access to the database failed, please check "
                            "file permissions and the file system and try"
                            " again!")
@@ -52,6 +56,7 @@ class SubscriptionNotFoundException(Exception):
     """
 
     def __init__(self):
+        super(SubscriptionNotFoundException, self).__init__()
         self.__message = _("The subscription you requested could not be "
                            "found in the database, requested action aborted.")
 
@@ -66,6 +71,7 @@ class NoDataFromYoutubeAPIException(Exception):
     """
 
     def __init__(self):
+        super(NoDataFromYoutubeAPIException, self).__init__()
         self.__message = _("The connection to the youtube API failed or "
                            "no data was returned.")
 
@@ -77,6 +83,7 @@ class YoutubeAPITimeoutException(Exception):
     """This exception will be raised when an API request times out"""
 
     def __init__(self, title):
+        super(YoutubeAPITimeoutException, self).__init__()
         self.__message = _("The API Request timed out for subscription %s,"
                            "please try again later.") % title
 
@@ -90,6 +97,7 @@ class ConfigFileWriteErrorException(Exception):
 
     """
     def __init__(self):
+        super(ConfigFileWriteErrorException, self).__init__()
         self.__message = _("The configuration could not be written, please"
                            " check that the configuration direcroty exists"
                            " and is writable.")
@@ -103,6 +111,7 @@ class DirectoryCreationFailedException(Exception):
 
     """
     def __init__(self):
+        super(DirectoryCreationFailedException, self).__init__()
         self.__message = _("The directory could not be created, "
                            "please check that the parent directory "
                            "exists and is writable")
@@ -117,6 +126,7 @@ class ConfigFileReadErrorException(Exception):
 
     """
     def __init__(self):
+        super(ConfigFileReadErrorException, self).__init__()
         self.__message = _("The configuration could not be read, please check "
                            "that the configuration file exists and is "
                            "readable.")
@@ -131,6 +141,7 @@ class InvalidConfigurationVersionException(Exception):
 
     """
     def __init__(self):
+        super(InvalidConfigurationVersionException, self).__init__()
         self.__message = _("Invalid config version read.")
 
     def __str__(self):
@@ -143,6 +154,7 @@ class SubscriptionDisabledException(Exception):
 
     """
     def __init__(self, subscription):
+        super(SubscriptionDisabledException, self).__init__()
         self.__message = _("The subscription %s is disabled, videos will"
                            " not be downloaded.") % subscription
 
@@ -156,6 +168,7 @@ class DownloadDirectoryCreationFailedException(Exception):
 
     """
     def __init__(self):
+        super(DownloadDirectoryCreationFailedException, self).__init__()
         self.__message = _("The download directory does not exist and can't "
                            "be created. Please check your configuration and "
                            "try again.")
@@ -169,6 +182,7 @@ class ConfigurationMigrationFailed(Exception):
     to the json format fails.
     """
     def __init__(self):
+        super(ConfigurationMigrationFailed, self).__init__()
         self._message = _("The migration of the configuration to the json "
                           "format failed.")
 
@@ -181,6 +195,7 @@ class YoutubeDlCallFailed(Exception):
         of an error returned by youtube-dl.
     """
     def __init__(self):
+        super(YoutubeDlCallFailed, self).__init__()
         self._message = _("Execution of youtube-dl failed.")
 
     def __str__(self):

+ 62 - 54
lib_stov/subscription.py

@@ -16,26 +16,31 @@
 
 # -*- coding: utf8 -*-
 
+"""This module takes care of managing subscriptions."""
+
 from lib_stov import stov_exceptions
 from lib_stov import noapi
 
 
-class sub(object):
-    def __init__(self, type, name, conf, search="", id=0, title="",
-                 directory="", disabled=0):
-        self.__ID = id
-        self.__title = title
-        self.__type = type
-        self.__name = name
-        self.__search = search
-        self.__directory = directory
-        self.__conf = conf
-        self.DownloadedVideos = []
-        self.FailedVideosCount = 0
-        self.FailedVideos = []
-        self.ToDelete = []
-        self.__video_list = []
-        self.__id_list = []
+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, search="",
+                 subscription_id=0, title="", directory="", disabled=0):
+        self._id = subscription_id
+        self._title = title
+        self._type = subscription_type
+        self._name = name
+        self._search = search
+        self._directory = directory
+        self._conf = conf
+        self.downloaded_videos = []
+        self.failed_videos_count = 0
+        self.failed_videos = []
+        self.to_delete = []
+        self._video_list = []
+        self._id_list = []
         self.parsed_response = None
 
         if int(disabled) == 0:
@@ -43,65 +48,68 @@ class sub(object):
         elif int(disabled) == 1:
             self.disabled = True
 
-        self._connector = noapi.Connector(self.__type, self.__name,
-                                          self.__conf, self.__search)
+        self._connector = noapi.Connector(self._type, self._name,
+                                          self._conf, self._search)
 
-    def GetTitle(self):
-        return self.__title
+    def get_title(self):
+        """Returns the title attribute."""
+        return self._title
 
-    def GetId(self):
-        return self.__ID
+    def get_id(self):
+        """Returns the id attribute."""
+        return self._id
 
-    def SetID(self, id):
-        self.__ID = id
+    def set_id(self, subscription_id):
+        """Sets the ID attribute."""
+        self._id = subscription_id
 
-    def CheckStringMatch(self, video):
+    def check_string_match(self, video):
         """Checks if the subscription is enabled and the video matches the
         search string defined for the subscription"""
         if not self.disabled:
-            if self.__search != "" and self.__conf.values["check_title"]\
+            if self._search != "" and self._conf.values["check_title"]\
                     == "yes":
-                if self.__search in video.title:
+                if self._search in video.title:
                     return True
                 else:
                     return False
             else:
                 return True
         else:
-                return False
+            return False
 
-    def GatherVideos(self, video_list):
+    def gather_videos(self, video_list):
         """Gathers all videos in the subscription and saves
         them in an the internal list so they can be accessed by the object
 
         """
-        self.__video_list = video_list
+        self._video_list = video_list
 
-    def DownloadVideos(self, itag_value):
+    def download_videos(self, itag_value):
         """Uses the DownloadVideo method of the video object to download all
         videos contained in the subscription and adds them to the list of
         downloaded videos if the download succeeds.
 
         """
         if not self.disabled:
-            for video in self.__video_list:
+            for video in self._video_list:
                 if video.downloaded == 0:
-                    if video.DownloadVideo(self.__directory, itag_value,
-                                           self.__conf.values["videocodec"]):
-                        self.DownloadedVideos.append(video)
+                    if video.DownloadVideo(self._directory, itag_value,
+                                           self._conf.values["videocodec"]):
+                        self.downloaded_videos.append(video)
                     else:
-                        self.FailedVideosCount += 1
-                        self.FailedVideos.append(video)
+                        self.failed_videos_count += 1
+                        self.failed_videos.append(video)
         else:
-            raise stov_exceptions.SubscriptionDisabledException(self.__title)
+            raise stov_exceptions.SubscriptionDisabledException(self._title)
 
-    def PrintVideos(self):
+    def print_videos(self):
         """Prepares a human readable list of all videos contained
         in the subscription.
 
         """
         video_list = []
-        for i in self.__video_list:
+        for i in self._video_list:
             if i.downloaded == 0:
                 video_list.append(i.title + _("   (pending)"))
             elif i.downloaded == 1:
@@ -110,28 +118,28 @@ class sub(object):
                 video_list.append(i.title + _("   (failed)"))
         return video_list
 
-    def AddSub(self):
+    def add_sub(self):
         """Adds a new subscription to the database"""
-        parsed_response = self._connector.ParseAPIData([])
-        self.__title = parsed_response.title
-        self.__directory = self.__name + "_" + self.__search.replace(" ", "_")
-        data = (self.__title, self.__type, self.__search, self.__directory,
-                self.__name, 0)
+        parsed_response = self._connector.parse_api_data([])
+        self._title = parsed_response.title
+        self._directory = self._name + "_" + self._search.replace(" ", "_")
+        data = (self._title, self._type, self._search, self._directory,
+                self._name, 0)
         return data
 
-    def CheckAndDelete(self, videos):
+    def check_and_delete(self, videos):
         """Checks if a video still exists in the current API response and
         deletes it if it doesn't
 
         """
-        parsed_response = self._connector.ParseAPIData([])
-        self.GatherVideos(videos)
+        parsed_response = self._connector.parse_api_data([])
+        self.gather_videos(videos)
         for entry in parsed_response.videos:
-            self.__id_list.append(entry.ytid)
-        for item in self.__video_list:
-            if item.ytid not in self.__id_list:
-                self.ToDelete.append(item)
+            self._id_list.append(entry.ytid)
+        for item in self._video_list:
+            if item.ytid not in self._id_list:
+                self.to_delete.append(item)
 
     def update_data(self):
         """Updates the data from the API."""
-        self.parsed_response = self._connector.ParseAPIData(self.__video_list)
+        self.parsed_response = self._connector.parse_api_data(self._video_list)

+ 61 - 61
stov

@@ -257,7 +257,7 @@ doesnt, create it using the configuration class.
 if os.access(os.environ['HOME'] + "/.stov", os.F_OK & os.W_OK) is not True:
     logger.info(_("This seems to be the first time you run the programm, do "
                   "you want to run the interactive assistant? (yes/no)"))
-    conf = configuration.conf()
+    conf = configuration.Conf()
     if sys.version_info >= (3, 0):
         temp_input = input()
     else:
@@ -266,7 +266,7 @@ if os.access(os.environ['HOME'] + "/.stov", os.F_OK & os.W_OK) is not True:
     if temp_input == "yes":
         conf.assist()
         try:
-            conf.Initialize()
+            conf.initialize()
         except stov_exceptions.ConfigFileWriteErrorException as e:
             logger.error(e)
         else:
@@ -278,19 +278,19 @@ if os.access(os.environ['HOME'] + "/.stov", os.F_OK & os.W_OK) is not True:
         logger.debug(_("Creating hidden directory in home for configuration"
                        " and database."))
         try:
-            conf.Initialize()
+            conf.initialize()
         except stov_exceptions.DirectoryCreationFailedException as e:
             logger.error(e)
         except stov_exceptions.ConfigFileWriteErrorException as e:
             logger.error(e)
 else:
-    conf = configuration.conf()
+    conf = configuration.Conf()
     if os.access(str(os.environ['HOME']) + "/.stov/stov.config", os.F_OK):
         logger.debug(_("Migrating configuration from plain text to json."))
         conf.migrate_config()
     try:
         logger.debug(_("Comparing current and running configuration version."))
-        check_result = conf.CheckConfig()
+        check_result = conf.check_config()
     except stov_exceptions.ConfigFileReadErrorException as e:
         logger.error(e)
         sys.exit(1)
@@ -302,7 +302,7 @@ else:
             logger.info(_("Your configuration needs to be updated, performing"
                           " update now."))
             try:
-                conf.UpdateConfig()
+                conf.update_config()
             except stov_exceptions.ConfigFileReadErrorException as e:
                 logger.error(e)
                 sys.exit(1)
@@ -315,19 +315,19 @@ else:
 
 if os.access(conf.dbpath, os.F_OK):
     try:
-        db = database.db(path=conf.dbpath, version=conf.values["db_version"])
+        db = database.Db(path=conf.dbpath, version=conf.values["db_version"])
     except stov_exceptions.DBConnectionFailedException as e:
         logger.error(e)
         sys.exit(1)
 else:
     try:
-        db = database.db(path=conf.dbpath, version=conf.values["db_version"])
+        db = database.Db(path=conf.dbpath, version=conf.values["db_version"])
     except stov_exceptions.DBConnectionFailedException as e:
         logger.error(e)
         sys.exit(1)
     else:
         try:
-            db.Populate()
+            db.populate()
         except stov_exceptions.DBWriteAccessFailedException as e:
             logger.error(e)
             sys.exit(1)
@@ -336,14 +336,14 @@ else:
 
 try:
     logger.debug(_("Comparing current and running database version."))
-    if conf.CheckDB() is not True:
+    if conf.check_db() is not True:
                 logger.info(_("Your database needs to be updated, performing"
                               " update now."))
-                db.Update()
-                conf.values["db_version"] = db.GetVersion()
+                db.update()
+                conf.values["db_version"] = db.get_version()
                 logger.debug("Opening configuration file.")
                 try:
-                    conf.WriteConfig()
+                    conf.write_config()
                 except stov_exceptions.ConfigFileWriteErrorException as e:
                     logger.error(e)
 except stov_exceptions.DBWriteAccessFailedException as e:
@@ -371,7 +371,7 @@ if conf.values["youtube-dl"] == "":
                       "configuration file."))
         logger.debug("Opening configuration file.")
         try:
-            conf.WriteConfig()
+            conf.write_config()
         except stov_exceptions.ConfigFileWriteErrorException as e:
             logger.error(e)
             sys.exit(1)
@@ -393,15 +393,15 @@ run the corresponding code
 """
 if options.add is True:
     if options.channel is not None and options.searchparameter is None:
-        NewSubscription = subscription.sub(type="channel",
+        NewSubscription = subscription.Sub(subscription_type="channel",
                                            name=options.channel, conf=conf)
     elif options.channel is not None and options.searchparameter is not None:
-        NewSubscription = subscription.sub(type="channel",
+        NewSubscription = subscription.Sub(subscription_type="channel",
                                            name=options.channel,
                                            search=options.searchparameter,
                                            conf=conf)
     elif options.channel is None and options.searchparameter is not None:
-        NewSubscription = subscription.sub(type="search",
+        NewSubscription = subscription.Sub(subscription_type="search",
                                            name=_("Search_"),
                                            search=options.searchparameter,
                                            conf=conf)
@@ -409,7 +409,7 @@ if options.add is True:
         if options.searchparameter is not None:
             logger.error(_("Playlists do not support searching, the search "
                            "option will be ignored!"))
-        NewSubscription = subscription.sub(type="playlist",
+        NewSubscription = subscription.Sub(subscription_type="playlist",
                                            name=options.playlist,
                                            conf=conf)
     else:
@@ -417,8 +417,8 @@ if options.add is True:
                        "the type option and try again."))
         sys.exit(1)
     try:
-        id = db.InsertSubscription(NewSubscription.AddSub())
-        NewSubscription.SetID(id)
+        id = db.insert_subscription(NewSubscription.add_sub())
+        NewSubscription.set_id(id)
     except stov_exceptions.DBWriteAccessFailedException as e:
         logger.error(e)
         sys.exit(1)
@@ -431,21 +431,21 @@ if options.add is True:
     except stov_exceptions.NoDataFromYoutubeAPIException as e:
         logger.error(e)
     for video in NewSubscription.parsed_response.videos:
-        if not db.VideoInDatabase(video.ytid):
-            if NewSubscription.CheckStringMatch(video):
+        if not db.video_in_database(video.ytid):
+            if NewSubscription.check_string_match(video):
                 try:
-                    db.InsertVideo(video, NewSubscription.GetId())
+                    db.insert_video(video, NewSubscription.get_id())
                 except stov_exceptions.DBWriteAccessFailedException as e:
                     logger.error(e)
                     sys.exit(1)
                 else:
                     logger.debug(_("Video %s successfully inserted into "
                                    "database.") % video.title)
-    logger.info(_("New subscription ") + NewSubscription.GetTitle()
+    logger.info(_("New subscription ") + NewSubscription.get_title()
                 + _(" successfully added"))
 
 elif options.list is True:
-    Listofsubscriptions = db.GetSubscriptions(conf)
+    Listofsubscriptions = db.get_subscriptions(conf)
     sub_state = None
     if len(Listofsubscriptions) != 0:
         logger.info(_("ID Title"))
@@ -454,7 +454,7 @@ elif options.list is True:
                 sub_state = _("enabled")
             elif sub.disabled:
                 sub_state = _("disabled")
-            logger.info(str(sub.GetId()) + " " + sub.GetTitle()
+            logger.info(str(sub.get_id()) + " " + sub.get_title()
                         + " (%s)" % sub_state)
     else:
         logger.info(_("No subscriptions added yet, add one!"))
@@ -467,7 +467,7 @@ elif options.deleteid is not None:
                        "option."))
     else:
         try:
-            db.DeleteSubscription(DeleteID)
+            db.delete_subscription(DeleteID)
         except stov_exceptions.SubscriptionNotFoundException as e:
             logger.error(e)
             sys.exit(1)
@@ -477,10 +477,10 @@ elif options.deleteid is not None:
         else:
             logger.info(_("Subscription deleted successfully!"))
 elif options.update is True:
-    listofsubscriptions = db.GetSubscriptions(conf)
+    listofsubscriptions = db.get_subscriptions(conf)
     for element in listofsubscriptions:
-        videos = db.GetVideos(element.GetId(), conf)
-        element.GatherVideos(videos)
+        videos = db.get_videos(element.get_id(), conf)
+        element.gather_videos(videos)
         try:
             element.update_data()
         except stov_exceptions.YoutubeAPITimeoutException as e:
@@ -488,10 +488,10 @@ elif options.update is True:
         except stov_exceptions.NoDataFromYoutubeAPIException as e:
             logger.error(e)
         for video in element.parsed_response.videos:
-            if not db.VideoInDatabase(video.ytid):
-                if element.CheckStringMatch(video):
+            if not db.video_in_database(video.ytid):
+                if element.check_string_match(video):
                     try:
-                        db.InsertVideo(video, element.GetId())
+                        db.insert_video(video, element.get_id())
                     except stov_exceptions.DBWriteAccessFailedException as e:
                         logger.error(e)
                         sys.exit(1)
@@ -500,10 +500,10 @@ elif options.update is True:
                                        "database.") % video.title)
 
 elif options.download is True:
-    listofsubscriptions = db.GetSubscriptions(conf)
+    listofsubscriptions = db.get_subscriptions(conf)
     logger.debug(_("Trying to determine the itag value for youtube-dl from"
                    " your quality and codec settings."))
-    itag_value = conf.GetYoutubeParameter()
+    itag_value = conf.get_youtube_parameter()
     logger.debug(_("Found value: %s.") % itag_value)
     if itag_value == 0:
         logger.debug(_("Codec and resolution could not be determined, using "
@@ -512,22 +512,22 @@ elif options.download is True:
     videosdownloaded = 0
     videosfailed = 0
     for element in listofsubscriptions:
-        videos = db.GetVideos(element.GetId(), conf)
-        element.GatherVideos(videos)
+        videos = db.get_videos(element.get_id(), conf)
+        element.gather_videos(videos)
         try:
-            element.DownloadVideos(itag_value)
+            element.download_videos(itag_value)
         except stov_exceptions.SubscriptionDisabledException as e:
             logger.debug(e)
-        for entry in element.DownloadedVideos:
-            db.UpdateVideoDownloadStatus(entry.GetID(), 1)
+        for entry in element.downloaded_videos:
+            db.update_video_download_status(entry.GetID(), 1)
             mailcontent.append(entry.title)
         videosdownloaded = len(mailcontent)
-        videosfailed = videosfailed + element.FailedVideosCount
-        for video in element.FailedVideos:
+        videosfailed = videosfailed + element.failed_videos_count
+        for video in element.failed_videos:
             try:
-                db.UpdateVideoFailCount(video.failcnt, video.GetID())
+                db.update_video_fail_count(video.failcnt, video.GetID())
                 if video.failcnt >= int(conf.values["maxfails"]):
-                    db.DisableFailedVideo(video.GetID())
+                    db.disable_failed_video(video.GetID())
             except stov_exceptions.DBWriteAccessFailedException as e:
                 logger.error(e)
                 sys.exit(1)
@@ -603,20 +603,20 @@ elif options.download is True:
 
 elif options.subscriptionid is not None:
     try:
-        Data = db.GetSubscription(options.subscriptionid)
+        Data = db.get_subscription(options.subscriptionid)
     except stov_exceptions.DBWriteAccessFailedException as e:
         logger.error(e)
         sys.exit(1)
     else:
         if Data:
-            Subscription = subscription.sub(id=Data[0][0], title=Data[0][1],
-                                            type=Data[0][2], name=Data[0][3],
+            Subscription = subscription.Sub(subscription_id=Data[0][0], title=Data[0][1],
+                                            subscription_type=Data[0][2], name=Data[0][3],
                                             search=Data[0][4],
                                             directory=Data[0][5],
                                             disabled=Data[0][6], conf=conf)
-            videos = db.GetVideos(Subscription.GetId(), conf)
-            Subscription.GatherVideos(videos)
-            video_list = Subscription.PrintVideos()
+            videos = db.get_videos(Subscription.get_id(), conf)
+            Subscription.gather_videos(videos)
+            video_list = Subscription.print_videos()
             for video in video_list:
                 logger.info(video)
         else:
@@ -624,14 +624,14 @@ elif options.subscriptionid is not None:
                            "try again."))
 elif options.catchup is not None:
     try:
-        sub_data = db.GetSubscriptionTitle(options.catchup)
+        sub_data = db.get_subscription_title(options.catchup)
     except stov_exceptions.DBWriteAccessFailedException as e:
         logger.error(e)
         sys.exit(1)
     else:
         if sub_data != []:
             try:
-                db.MarkVideosDownloaded(options.catchup)
+                db.mark_video_downloaded(options.catchup)
             except stov_exceptions.DBWriteAccessFailedException as e:
                 logger.error(e)
         else:
@@ -640,32 +640,32 @@ elif options.catchup is not None:
 
 
 elif options.cleanup is True:
-    subscriptions_list = db.GetSubscriptions(conf)
+    subscriptions_list = db.get_subscriptions(conf)
     for element in subscriptions_list:
-        videos = db.GetVideos(element.GetId(), conf)
-        element.CheckAndDelete(videos)
+        videos = db.get_videos(element.get_id(), conf)
+        element.check_and_delete(videos)
         for delete_video in element.ToDelete:
             logger.debug(_("Deleting video %s from "
                            "database") % delete_video.title)
             try:
-                db.DeleteVideo(delete_video.GetID())
+                db.delete_video(delete_video.GetID())
             except stov_exceptions.DBWriteAccessFailedException as e:
                 logger.error(e)
                 sys.exit(1)
     try:
-        db.Vacuum()
+        db.vacuum()
     except stov_exceptions.DBWriteAccessFailedException as e:
         logger.error(e)
         sys.exit(1)
 elif options.enableid is not None:
-        subscription_state = db.GetSubscription(options.enableid)
+        subscription_state = db.get_subscription(options.enableid)
         try:
             if int(subscription_state[0][6]) == 0:
                 logger.error(_("The subscription ID %s is already enabled.")
                              % options.enableid)
             elif int(subscription_state[0][6]) == 1:
                 try:
-                    db.ChangeSubscriptionState(options.enableid, 0)
+                    db.change_subscription_state(options.enableid, 0)
                 except stov_exceptions.DBWriteAccessFailedException as e:
                     logger.error(e)
                     sys.exit(1)
@@ -676,14 +676,14 @@ elif options.enableid is not None:
             logger.error(_("Could not find the subscription with ID %s, "
                            "please check and try again.") % options.enableid)
 elif options.disableid is not None:
-        subscription_state = db.GetSubscription(options.disableid)
+        subscription_state = db.get_subscription(options.disableid)
         try:
             if int(subscription_state[0][6]) == 1:
                 logger.error(_("Subscription ID %s is already disabled.")
                              % options.disableid)
             elif int(subscription_state[0][6]) == 0:
                 try:
-                    db.ChangeSubscriptionState(options.disableid, 1)
+                    db.change_subscription_state(options.disableid, 1)
                 except stov_exceptions.DBWriteAccessFailedException as e:
                     logger.error(e)
                     sys.exit(1)