Browse Source

move downloading of videos and e-mail notification to program

Helmut Pozimski 6 years ago
parent
commit
7f50d6143e
2 changed files with 136 additions and 91 deletions
  1. 129 0
      lib_stov/program.py
  2. 7 91
      stov

+ 129 - 0
lib_stov/program.py

@@ -21,6 +21,11 @@ application.
 
 import logging
 import sys
+import smtplib
+import socket
+
+from email.mime.text import MIMEText
+from email.mime.multipart import MIMEMultipart
 
 from lib_stov import subscription
 from lib_stov import stov_exceptions
@@ -176,3 +181,127 @@ def update_subscriptions(database, conf):
                     else:
                         LOGGER.debug(_("Video %s successfully inserted into "
                                        "database."), video.title)
+
+
+def download_videos(database, conf):
+    """
+    Downloads videos that haven't been previously downloaded.
+
+    :param conf: configuration object
+    :type conf: lib_stov.configuration.Conf
+    :param database: database object
+    :type database: lib_stov.database.Db
+    :return: tuple containing (in that order) downloaded videos, failed \
+    videos and a list of the videos downloaded
+    :rtype: tuple
+    """
+    video_titles = []
+    subscriptions_list = database.get_subscriptions(conf)
+    LOGGER.debug(_("Trying to determine the itag value for youtube-dl from"
+                   " your quality and codec settings."))
+    itag = conf.get_youtube_parameter()
+    LOGGER.debug(_("Found value: %s."), itag)
+    if itag == 0:
+        LOGGER.debug(_("Codec and resolution could not be determined, using "
+                       "maximum possible value."))
+        itag = 38
+    videos_downloaded = 0
+    videos_failed = 0
+    for sub in subscriptions_list:
+        videos = database.get_videos(sub.get_id(), conf)
+        sub.gather_videos(videos)
+        try:
+            sub.download_videos(itag)
+        except stov_exceptions.SubscriptionDisabledException as error:
+            LOGGER.debug(error)
+        for entry in sub.downloaded_videos:
+            database.update_video_download_status(entry.get_id(), 1)
+            video_titles.append(entry.title)
+        videos_downloaded = len(video_titles)
+        videos_failed = videos_failed + sub.failed_videos_count
+        for video in sub.failed_videos:
+            try:
+                database.update_video_fail_count(video.failcnt, video.get_id())
+                if video.failcnt >= int(conf.values["maxfails"]):
+                    database.disable_failed_video(video.get_id())
+            except stov_exceptions.DBWriteAccessFailedException as error:
+                LOGGER.error(error)
+                sys.exit(1)
+    return (videos_downloaded, videos_failed, video_titles)
+
+
+def compose_email(conf, 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
+    :type video_titles: list
+    :return: e-mail contents
+    :rtype: MIMEMultipart
+    """
+    mail_text = ""
+    msg = MIMEMultipart()
+    if downloaded_videos == 1:
+        msg["Subject"] = _("Downloaded %i new video") % downloaded_videos
+        mail_text = _("The following episode has been downloaded by stov: "
+                      "\n\n")
+    else:
+        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"]
+    for line in video_titles:
+        mail_text += line + "\n"
+    msg_text = MIMEText(mail_text.encode("utf8"), _charset="utf8")
+    msg.attach(msg_text)
+    return msg
+
+
+def send_email(conf, 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"])
+    try:
+        server_connection.connect()
+    except (smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected,
+            socket.error):
+        LOGGER.error(_("Could not connect to the smtp server, please check"
+                       " your settings!"))
+    else:
+        try:
+            server_connection.starttls()
+        except smtplib.SMTPException:
+            LOGGER.debug(_("TLS not available, proceeding unencrypted."))
+        if conf.values["auth_needed"] == "yes":
+            try:
+                server_connection.login(conf.values["user_name"],
+                                        conf.values["password"])
+            except smtplib.SMTPAuthenticationError:
+                LOGGER.error(_("Authentication failed, please check user "
+                               "name and password!"))
+            except smtplib.SMTPException:
+                LOGGER.error(_("Could not authenticate, server probably "
+                               "does not support authentication!"))
+        try:
+            server_connection.sendmail(conf.values["mailfrom"],
+                                       conf.values["mailto"],
+                                       msg.as_string())
+        except smtplib.SMTPRecipientsRefused:
+            LOGGER.error(_("The server refused the recipient address, "
+                           "please check your settings."))
+        except smtplib.SMTPSenderRefused:
+            LOGGER.error(_("The server refused the sender address, "
+                           "please check your settings."))
+        server_connection.quit()

+ 7 - 91
stov

@@ -26,11 +26,7 @@ everything together, performing all the actions a user wants.
 """
 
 import sys
-import smtplib
-import socket
 import logging
-from email.mime.multipart import MIMEMultipart
-from email.mime.text import MIMEText
 
 from lib_stov import subscription
 from lib_stov import stov_exceptions
@@ -48,8 +44,6 @@ LOGGER = logging.getLogger("stov")
 DB = helpers.setup_database(CONF)
 helpers.find_youtubedl(CONF)
 
-# Variable to save the text that is later sent as e-mail
-MAIL_CONTENT = []
 
 """Check which ARGUMENTS are given on the command line and
 run the corresponding code
@@ -63,99 +57,21 @@ elif ARGUMENTS.list:
     program.list_subscriptions(CONF, DB)
 elif ARGUMENTS.deleteid:
     program.delete_subscription(DB, ARGUMENTS.deleteid)
-elif ARGUMENTS.update is True:
+elif ARGUMENTS.update:
     program.update_subscriptions(CONF, DB)
-elif ARGUMENTS.download is True:
-    SUBSCRIPTIONS_LIST = DB.get_subscriptions(CONF)
-    LOGGER.debug(_("Trying to determine the itag value for youtube-dl from"
-                   " your quality and codec settings."))
-    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 "
-                       "maximum possible value."))
-        ITAG_VALUE = 38
-    VIDEOS_DOWNLOADED = 0
-    VIDEOS_FAILED = 0
-    for element in SUBSCRIPTIONS_LIST:
-        VIDEOS = DB.get_videos(element.get_id(), CONF)
-        element.gather_videos(VIDEOS)
-        try:
-            element.download_videos(ITAG_VALUE)
-        except stov_exceptions.SubscriptionDisabledException as error:
-            LOGGER.debug(error)
-        for entry in element.downloaded_videos:
-            DB.update_video_download_status(entry.get_id(), 1)
-            MAIL_CONTENT.append(entry.title)
-        VIDEOS_DOWNLOADED = len(MAIL_CONTENT)
-        VIDEOS_FAILED = VIDEOS_FAILED + element.failed_videos_count
-        for video in element.failed_videos:
-            try:
-                DB.update_video_fail_count(video.failcnt, video.get_id())
-                if video.failcnt >= int(CONF.values["maxfails"]):
-                    DB.disable_failed_video(video.get_id())
-            except stov_exceptions.DBWriteAccessFailedException as error:
-                LOGGER.error(error)
-                sys.exit(1)
+elif ARGUMENTS.download:
+    VIDEOS_DOWNLOADED, VIDEOS_FAILED, VIDEO_TITLES = \
+        program.download_videos(DB, CONF)
     if VIDEOS_DOWNLOADED > 0 and CONF.values["notify"] == "yes":
-        MAIL_TEXT = ""
-        MSG = MIMEMultipart()
-        if VIDEOS_DOWNLOADED == 1:
-            MSG["Subject"] = _("Downloaded %i new video") % VIDEOS_DOWNLOADED
-            MAIL_TEXT = _("The following episode has been downloaded by stov: "
-                          "\n\n")
-        else:
-            MSG["Subject"] = _("Downloaded %i new videos") % VIDEOS_DOWNLOADED
-            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"]
-        for line in MAIL_CONTENT:
-            MAIL_TEXT += line + "\n"
-        MSG_TEXT = MIMEText(MAIL_TEXT.encode("utf8"), _charset="utf8")
-        MSG.attach(MSG_TEXT)
-        SERVER_CONNECTION = smtplib.SMTP(CONF.values["mailhost"],
-                                         CONF.values["smtpport"])
-        try:
-            SERVER_CONNECTION.connect()
-        except (smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected,
-                socket.error):
-            LOGGER.error(_("Could not connect to the smtp server, please check"
-                           " your settings!"))
-            LOGGER.error(MAIL_TEXT)
-        else:
-            try:
-                SERVER_CONNECTION.starttls()
-            except smtplib.SMTPException:
-                LOGGER.debug(_("TLS not available, proceeding unencrypted."))
-            if CONF.values["auth_needed"] == "yes":
-                try:
-                    SERVER_CONNECTION.login(CONF.values["user_name"],
-                                            CONF.values["password"])
-                except smtplib.SMTPAuthenticationError:
-                    LOGGER.error(_("Authentication failed, please check user "
-                                   "name and password!"))
-                except smtplib.SMTPException:
-                    LOGGER.error(_("Could not authenticate, server probably "
-                                   "does not support authentication!"))
-            try:
-                SERVER_CONNECTION.sendmail(CONF.values["mailfrom"],
-                                           CONF.values["mailto"],
-                                           MSG.as_string())
-            except smtplib.SMTPRecipientsRefused:
-                LOGGER.error(_("The server refused the recipient address, "
-                               "please check your settings."))
-            except smtplib.SMTPSenderRefused:
-                LOGGER.error(_("The server refused the sender address, "
-                               "please check your settings."))
-            SERVER_CONNECTION.quit()
+        MSG = program.compose_email(CONF, VIDEOS_DOWNLOADED, VIDEO_TITLES)
+        program.send_email(CONF, MSG)
     elif VIDEOS_DOWNLOADED == 0 and VIDEOS_FAILED == 0:
         if CONF.values["notify"] == "no":
             LOGGER.info(_("There are no videos to be downloaded."))
     elif CONF.values["notify"] == "no":
         if VIDEOS_FAILED == 0:
             LOGGER.info(_("The following videos have been downloaded:\n"))
-            for i in MAIL_CONTENT:
+            for i in VIDEO_TITLES:
                 LOGGER.info(i)
     else:
         if CONF.values["notify"] != "yes":