program.py 20 KB

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