program.py 21 KB

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