program.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. # This file is part of stov, written by Helmut Pozimski 2012-2017.
  2. #
  3. # stov is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, version 2 of the License.
  6. #
  7. # stov is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License
  13. # along with stov. If not, see <http://www.gnu.org/licenses/>.
  14. # -*- coding: utf8 -*-
  15. """ This module contains the functions that make up the core of the
  16. application.
  17. """
  18. import logging
  19. import sys
  20. import smtplib
  21. import socket
  22. from email.mime.text import MIMEText
  23. from email.mime.multipart import MIMEMultipart
  24. from lib_stov import subscription
  25. from lib_stov import stov_exceptions
  26. from lib_stov.database import Db
  27. from lib_stov.configuration import Conf
  28. LOGGER = logging.getLogger("stov")
  29. DATABASE = Db.get_instance()
  30. CONFIGURATION = Conf.get_instance()
  31. def add_subscription(channel="", search="", playlist="", site="youtube"):
  32. """
  33. Takes care of adding a new subscription to the database.
  34. :param site: site the subscription is about to be created for
  35. :type site: str
  36. :param channel: optional channel name
  37. :type channel: str
  38. :param search: optional search string
  39. :type search: str
  40. :param playlist: optional playlist ID
  41. :type playlist: str
  42. """
  43. LOGGER.debug(_("Creating new subscription with the following "
  44. "parameters:\nChannel: %s\nSearch: %s\nPlaylist: %s"),
  45. channel, search, playlist)
  46. try:
  47. if channel and not search:
  48. new_subscription = subscription.Sub(subscription_type="user",
  49. name=channel, site=site)
  50. elif channel and search:
  51. new_subscription = subscription.Sub(subscription_type="user",
  52. name=channel, site=site,
  53. search=search)
  54. elif not channel and search:
  55. new_subscription = subscription.Sub(subscription_type="search",
  56. name=_("Search_"), site=site,
  57. search=search)
  58. elif playlist:
  59. if search:
  60. LOGGER.error(_("Playlists do not support searching, the "
  61. "search option will be ignored!"))
  62. new_subscription = subscription.Sub(subscription_type="playlist",
  63. name=playlist, site=site)
  64. else:
  65. LOGGER.error(_("None or invalid subscription type given, please "
  66. "check the type option and try again."))
  67. sys.exit(1)
  68. except stov_exceptions.TypeNotSupported as error:
  69. LOGGER.error(error)
  70. sys.exit(1)
  71. try:
  72. subscription_data = new_subscription.add_sub()
  73. site_id = DATABASE.get_site_id(subscription_data[6])
  74. new_sub_data = (subscription_data[0], subscription_data[1],
  75. subscription_data[2], subscription_data[3],
  76. subscription_data[4], subscription_data[5],
  77. site_id)
  78. subscription_id = DATABASE.insert_subscription(new_sub_data)
  79. new_subscription.set_id(subscription_id)
  80. except stov_exceptions.DBWriteAccessFailedException as error:
  81. LOGGER.error(error)
  82. sys.exit(1)
  83. except stov_exceptions.ChannelNotFound as error:
  84. LOGGER.error(error)
  85. sys.exit(1)
  86. else:
  87. LOGGER.debug(_("Subscription sucessfully inserted into database."))
  88. try:
  89. new_subscription.update_data()
  90. except stov_exceptions.YoutubeAPITimeoutException as error:
  91. LOGGER.error(error)
  92. except stov_exceptions.NoDataFromYoutubeAPIException as error:
  93. LOGGER.error(error)
  94. for video in new_subscription.parsed_response.videos:
  95. if not DATABASE.video_in_database(video.video_id):
  96. if new_subscription.check_string_match(video):
  97. try:
  98. DATABASE.insert_video(video, new_subscription.get_id())
  99. except stov_exceptions.DBWriteAccessFailedException as error:
  100. LOGGER.error(error)
  101. sys.exit(1)
  102. else:
  103. LOGGER.debug(_("Video %s successfully inserted into "
  104. "database."), video.title)
  105. LOGGER.info(_("New subscription ") + new_subscription.get_title() +
  106. _(" successfully added"))
  107. def list_subscriptions():
  108. """
  109. Prints a list of subscriptions from the database.
  110. """
  111. subscriptions_list = DATABASE.get_subscriptions(CONFIGURATION)
  112. sub_state = None
  113. if subscriptions_list:
  114. LOGGER.info(_("ID Title Site"))
  115. for sub in subscriptions_list:
  116. if not sub.disabled:
  117. sub_state = _("enabled")
  118. elif sub.disabled:
  119. sub_state = _("disabled")
  120. LOGGER.info(str(sub.get_id()) + " " + sub.get_title() +
  121. " " + sub.site + " " + "(%s)" % sub_state)
  122. else:
  123. LOGGER.info(_("No subscriptions added yet, add one!"))
  124. def delete_subscription(sub_id):
  125. """
  126. Deletes a specified subscription from the database
  127. :param sub_id: ID of the subscription to be deleted
  128. :type sub_id: int
  129. """
  130. try:
  131. DATABASE.delete_subscription(sub_id)
  132. except stov_exceptions.SubscriptionNotFoundException as error:
  133. LOGGER.error(error)
  134. sys.exit(1)
  135. except stov_exceptions.DBWriteAccessFailedException as error:
  136. LOGGER.error(error)
  137. sys.exit(1)
  138. else:
  139. LOGGER.info(_("Subscription deleted successfully!"))
  140. def update_subscriptions(subscriptions=None):
  141. """
  142. Updates data about videos in a subscription.
  143. :param subscriptions: list of subscriptions to update
  144. :type subscriptions: list
  145. """
  146. subscriptions_list = get_subscriptions(subscriptions)
  147. for element in subscriptions_list:
  148. LOGGER.debug(_("Updating subscription %s"), element.get_title())
  149. videos = DATABASE.get_videos(element.get_id(), CONFIGURATION)
  150. element.gather_videos(videos)
  151. try:
  152. element.update_data()
  153. except stov_exceptions.YoutubeAPITimeoutException as error:
  154. LOGGER.error(error)
  155. except stov_exceptions.NoDataFromYoutubeAPIException as error:
  156. LOGGER.error(error)
  157. for video in element.parsed_response.videos:
  158. if not DATABASE.video_in_database(video.video_id):
  159. if element.check_string_match(video):
  160. try:
  161. DATABASE.insert_video(video, element.get_id())
  162. except stov_exceptions.DBWriteAccessFailedException as \
  163. error:
  164. LOGGER.error(error)
  165. sys.exit(1)
  166. else:
  167. LOGGER.debug(_("Video %s successfully inserted into "
  168. "database."), video.title)
  169. def download_videos(subscriptions=None):
  170. """
  171. Downloads videos that haven't been previously downloaded.
  172. :param subscriptions: list of subscriptions to consider for downloading
  173. :type subscriptions: list
  174. :return: tuple containing (in that order) downloaded videos, failed \
  175. videos and a list of the videos downloaded
  176. :rtype: tuple
  177. """
  178. video_titles = []
  179. subscriptions_list = get_subscriptions(subscriptions)
  180. videos_downloaded = 0
  181. videos_failed = 0
  182. for sub in subscriptions_list:
  183. videos = DATABASE.get_videos(sub.get_id(), CONFIGURATION)
  184. sub.gather_videos(videos)
  185. try:
  186. sub.download_videos()
  187. except stov_exceptions.SubscriptionDisabledException as error:
  188. LOGGER.debug(error)
  189. for entry in sub.downloaded_videos:
  190. DATABASE.update_video_download_status(entry.get_id(), 1)
  191. video_titles.append(entry.title)
  192. videos_downloaded = len(video_titles)
  193. videos_failed = videos_failed + sub.failed_videos_count
  194. for video in sub.failed_videos:
  195. try:
  196. DATABASE.update_video_fail_count(video.failcnt, video.get_id())
  197. if video.failcnt >= int(CONFIGURATION.values["maxfails"]):
  198. DATABASE.disable_failed_video(video.get_id())
  199. except stov_exceptions.DBWriteAccessFailedException as error:
  200. LOGGER.error(error)
  201. sys.exit(1)
  202. return (videos_downloaded, videos_failed, video_titles)
  203. def compose_email(downloaded_videos, video_titles):
  204. """
  205. Composes an e-mail that can be send out to the user.
  206. :param downloaded_videos: number of downloaded videos
  207. :type downloaded_videos: int
  208. :param video_titles: titles of the downloaded videos
  209. :type video_titles: list
  210. :return: e-mail contents
  211. :rtype: MIMEMultipart
  212. """
  213. mail_text = ""
  214. msg = MIMEMultipart()
  215. if downloaded_videos == 1:
  216. msg["Subject"] = _("Downloaded %i new video") % downloaded_videos
  217. mail_text = _("The following episode has been downloaded by stov: "
  218. "\n\n")
  219. else:
  220. msg["Subject"] = _("Downloaded %i new videos") % downloaded_videos
  221. mail_text = _("The following episodes have been downloaded by "
  222. "stov: \n\n")
  223. msg["From"] = "stov <%s>" % CONFIGURATION.values["mailfrom"]
  224. msg["To"] = "<%s>" % CONFIGURATION.values["mailto"]
  225. for line in video_titles:
  226. mail_text += line + "\n"
  227. msg_text = MIMEText(mail_text.encode("utf8"), _charset="utf8")
  228. msg.attach(msg_text)
  229. return msg
  230. def send_email(msg):
  231. """
  232. Sends an e-mail to the user.
  233. :param msg: message to be sent
  234. :type msg: MIMEMultipart
  235. """
  236. server_connection = smtplib.SMTP(CONFIGURATION.values["mailhost"],
  237. CONFIGURATION.values["smtpport"])
  238. try:
  239. server_connection.connect()
  240. except (smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected,
  241. socket.error):
  242. LOGGER.error(_("Could not connect to the smtp server, please check"
  243. " your settings!"))
  244. else:
  245. try:
  246. server_connection.starttls()
  247. except smtplib.SMTPException:
  248. LOGGER.debug(_("TLS not available, proceeding unencrypted."))
  249. if CONFIGURATION.values["auth_needed"] == "yes":
  250. try:
  251. server_connection.login(CONFIGURATION.values["user_name"],
  252. CONFIGURATION.values["password"])
  253. except smtplib.SMTPAuthenticationError:
  254. LOGGER.error(_("Authentication failed, please check user "
  255. "name and password!"))
  256. except smtplib.SMTPException:
  257. LOGGER.error(_("Could not authenticate, server probably "
  258. "does not support authentication!"))
  259. try:
  260. server_connection.sendmail(CONFIGURATION.values["mailfrom"],
  261. CONFIGURATION.values["mailto"],
  262. msg.as_string())
  263. except smtplib.SMTPRecipientsRefused:
  264. LOGGER.error(_("The server refused the recipient address, "
  265. "please check your settings."))
  266. except smtplib.SMTPSenderRefused:
  267. LOGGER.error(_("The server refused the sender address, "
  268. "please check your settings."))
  269. server_connection.quit()
  270. def list_videos(sub_id):
  271. """
  272. Lists all videos in a specified subscription
  273. :param sub_id: ID of the subscription
  274. :type sub_id: int
  275. """
  276. try:
  277. data = DATABASE.get_subscription(sub_id)
  278. except stov_exceptions.DBWriteAccessFailedException as error:
  279. LOGGER.error(error)
  280. sys.exit(1)
  281. else:
  282. if data:
  283. sub = subscription.Sub(subscription_type=data[0][2],
  284. name=data[0][3], site=data[0][7],
  285. search=data[0][4],
  286. subscription_id=data[0][0],
  287. title=data[0][1], directory=data[0][5],
  288. disabled=data[0][6])
  289. videos = DATABASE.get_videos(sub.get_id(), CONFIGURATION)
  290. sub.gather_videos(videos)
  291. videos_list = sub.print_videos()
  292. for video in videos_list:
  293. LOGGER.info(video)
  294. else:
  295. LOGGER.error(_("Invalid subscription, please check the list and "
  296. "try again."))
  297. def catchup(sub_id):
  298. """
  299. Marks all videos in a subscription as downloaded
  300. :param sub_id: ID of the subscription
  301. :type sub_id: int
  302. """
  303. try:
  304. sub_data = DATABASE.get_subscription_title(sub_id)
  305. except stov_exceptions.DBWriteAccessFailedException as error:
  306. LOGGER.error(error)
  307. sys.exit(1)
  308. else:
  309. if sub_data:
  310. try:
  311. DATABASE.mark_video_downloaded(sub_id)
  312. except stov_exceptions.DBWriteAccessFailedException as error:
  313. LOGGER.error(error)
  314. else:
  315. LOGGER.error(_("The subscription could not be updated, "
  316. "please check if the ID given is correct."))
  317. def clean_database():
  318. """
  319. Initiates a database cleanup, deleting all videos that are no longer
  320. in the scope of the query and vacuuming the database to free up space.
  321. """
  322. subscription_list = DATABASE.get_subscriptions(CONFIGURATION)
  323. for element in subscription_list:
  324. videos = DATABASE.get_videos(element.get_id(), CONFIGURATION)
  325. element.check_and_delete(videos)
  326. for delete_video in element.to_delete:
  327. LOGGER.debug(_("Deleting video %s from "
  328. "database"), delete_video.title)
  329. try:
  330. DATABASE.delete_video(delete_video.get_id())
  331. except stov_exceptions.DBWriteAccessFailedException as error:
  332. LOGGER.error(error)
  333. sys.exit(1)
  334. try:
  335. DATABASE.vacuum()
  336. except stov_exceptions.DBWriteAccessFailedException as error:
  337. LOGGER.error(error)
  338. sys.exit(1)
  339. def change_subscription_state(sub_id, enable=False):
  340. """
  341. Enables or disables a subscription.
  342. :param sub_id: ID of the subscription
  343. :type sub_id: int
  344. :param enable: whether to enable or disable the subscription
  345. :type enable: bool
  346. """
  347. subscription_state = DATABASE.get_subscription(sub_id)
  348. try:
  349. if enable:
  350. if int(subscription_state[0][6]) == 0:
  351. LOGGER.error(_("The subscription ID %s is already enabled."),
  352. sub_id)
  353. elif int(subscription_state[0][6]) == 1:
  354. try:
  355. DATABASE.change_subscription_state(sub_id, 0)
  356. except stov_exceptions.DBWriteAccessFailedException as error:
  357. LOGGER.error(error)
  358. sys.exit(1)
  359. else:
  360. LOGGER.info(_("Enabled subscription ID %s."), sub_id)
  361. else:
  362. if int(subscription_state[0][6]) == 1:
  363. LOGGER.error(_("Subscription ID %s is already disabled."),
  364. sub_id)
  365. elif int(subscription_state[0][6]) == 0:
  366. try:
  367. DATABASE.change_subscription_state(sub_id, 1)
  368. except stov_exceptions.DBWriteAccessFailedException as error:
  369. LOGGER.error(error)
  370. sys.exit(1)
  371. else:
  372. LOGGER.info(_("Disabled subscription ID %s."),
  373. sub_id)
  374. except IndexError:
  375. LOGGER.error(_("Could not find the subscription with ID %s, "
  376. "please check and try again."), sub_id)
  377. def print_license():
  378. """
  379. Prints the license of the application.
  380. """
  381. LOGGER.info("""
  382. stov is free software: you can redistribute it and/or modify
  383. it under the terms of the GNU General Public License as published by
  384. the Free Software Foundation, version 2 of the License.
  385. stov is distributed in the hope that it will be useful,
  386. but WITHOUT ANY WARRANTY; without even the implied warranty of
  387. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  388. GNU General Public License for more details.
  389. You should have received a copy of the GNU General Public License
  390. along with stov. If not, see <http://www.gnu.org/licenses/>.""")
  391. def download_notify(subscriptions=None):
  392. """
  393. starts an update of not yet downloaded videos and notifies the user
  394. :param subscriptions: list of subscriptions to consider for downloading
  395. :type subscriptions: list
  396. """
  397. videos_downloaded, videos_failed, video_titles = \
  398. download_videos(subscriptions)
  399. if videos_downloaded > 0 and CONFIGURATION.values["notify"] == "yes":
  400. msg = compose_email(videos_downloaded, video_titles)
  401. send_email(msg)
  402. elif videos_downloaded == 0 and videos_failed == 0:
  403. if CONFIGURATION.values["notify"] == "no":
  404. LOGGER.info(_("There are no videos to be downloaded."))
  405. elif CONFIGURATION.values["notify"] == "no":
  406. if videos_failed == 0:
  407. LOGGER.info(_("The following videos have been downloaded:\n"))
  408. for i in video_titles:
  409. LOGGER.info(i)
  410. else:
  411. if CONFIGURATION.values["notify"] != "yes":
  412. LOGGER.error(_("Could not determine how you want to be informed "
  413. "about new videos, please check the notify "
  414. "parameter in your configuration."))
  415. def initialize_sites():
  416. """
  417. Adds sites to the database if they are not in there yet.
  418. """
  419. supported_sites = ["youtube", "zdf_mediathek", "twitch"]
  420. sites = DATABASE.get_sites()
  421. for site in supported_sites:
  422. site_found = False
  423. for result in sites:
  424. if site in result:
  425. site_found = True
  426. if not site_found:
  427. DATABASE.add_site(site)
  428. for site in sites:
  429. if site[1] not in supported_sites:
  430. DATABASE.remove_site(site[1])
  431. def list_sites():
  432. """
  433. Lists the currently supported sites.
  434. """
  435. sites = DATABASE.get_sites()
  436. LOGGER.info(_("Sites currently supported by stov:"))
  437. for entry in sites:
  438. LOGGER.info(entry[1])
  439. def get_subscriptions(subscriptions=None):
  440. """
  441. Retrieves all or only specific subscriptions from the database and
  442. returns them as a list of subscription objects.
  443. :param subscriptions: list of subscriptions to retrieve
  444. :type subscriptions: list
  445. :return: list of subscription objects
  446. :rtype: list
  447. """
  448. if subscriptions:
  449. subscriptions_list = []
  450. for element in subscriptions:
  451. data = DATABASE.get_subscription(element)
  452. if data:
  453. sub = subscription.Sub(subscription_type=data[0][2],
  454. name=data[0][3], site=data[0][7],
  455. search=data[0][4],
  456. subscription_id=data[0][0],
  457. title=data[0][1], directory=data[0][5],
  458. disabled=data[0][6])
  459. subscriptions_list.append(sub)
  460. else:
  461. LOGGER.error(
  462. _("Invalid subscription, please check the list and "
  463. "try again."))
  464. else:
  465. subscriptions_list = DATABASE.get_subscriptions(CONFIGURATION)
  466. return subscriptions_list