program.py 20 KB

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