stov 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. #! /usr/bin/env python
  2. # -*- coding: utf8 -*-
  3. #stov - a program to subscribe to channels and users from youtube
  4. # and download the videos automatically
  5. #
  6. # written by Helmut Pozimski 2012-2014
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; version 2
  11. # of the License.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. # Boston, MA 02110-1301, USA.
  22. from __future__ import unicode_literals
  23. from __future__ import print_function
  24. import sys
  25. import gettext
  26. import os
  27. import smtplib
  28. import subprocess
  29. import signal
  30. import socket
  31. import logging
  32. from email.mime.multipart import MIMEMultipart
  33. from email.mime.text import MIMEText
  34. from optparse import OptionParser
  35. from lib_stov import subscription
  36. from lib_stov import configuration
  37. from lib_stov import stov_exceptions
  38. from lib_stov import database
  39. """Setup the logger to log messages to stdout and stderr"""
  40. logger = logging.getLogger("stov")
  41. logger.setLevel(logging.DEBUG)
  42. console_handler = logging.StreamHandler()
  43. logger.addHandler(console_handler)
  44. """Determine the path where the stov files are for localization"""
  45. locale_path = os.path.join(sys.path[0] + "/locale")
  46. if gettext.find("stov", locale_path) is None:
  47. base_path = os.path.split(sys.path[0])[0]
  48. if "share" in base_path:
  49. locale_path = os.path.join(base_path, "locale")
  50. else:
  51. locale_path = os.path.join(base_path, "share/locale")
  52. """Initialize gettext to support translation of the program"""
  53. try:
  54. trans = gettext.translation("stov", locale_path)
  55. except IOError:
  56. gettext.install("stov")
  57. if os.environ["LANG"] != "C" and os.environ["LANGUAGE"] != "C":
  58. print(_("The translation files could not be found, localization "
  59. "won't be available"), file=sys.stderr)
  60. else:
  61. if sys.version_info >= (3, 0):
  62. trans.install()
  63. else:
  64. trans.install(unicode=True)
  65. """Define a handler for signals sent to the program"""
  66. def sighandler(signum, frame):
  67. if signum == 2:
  68. print(_("STRG+C has been pressed, quitting..."), file=sys.stderr)
  69. elif signum == 15:
  70. print(_("Received SIGTERM, quitting..."), file=sys.stderr)
  71. os.killpg(os.getpid(), 1)
  72. os.remove("/tmp/stov.lock")
  73. sys.exit(0)
  74. signal.signal(signal.SIGTERM, sighandler)
  75. signal.signal(signal.SIGINT, sighandler)
  76. """Overwrite the default OptionParser class so error messages
  77. can be localized
  78. """
  79. class MyOptionParser(OptionParser):
  80. def error(self, parser_msg):
  81. if "invalid integer" in parser_msg:
  82. print(_("option %s requires an integer value")
  83. % parser_msg.split()[1], file=sys.stderr)
  84. self.exit()
  85. elif "an argument" in parser_msg:
  86. print(_("option %s requires an argument") % parser_msg.split()[0],
  87. file=sys.stderr)
  88. self.exit()
  89. elif "no such" in parser_msg:
  90. print(_("invalid option %s") % parser_msg.split()[3],
  91. file=sys.stderr)
  92. self.exit()
  93. else:
  94. print(parser_msg, file=sys.stderr)
  95. self.exit()
  96. """Process the given options and parameters,
  97. add: Add a new subscription (which can be a search, channel or
  98. playlist)
  99. channel: with add, specify the name of the channel or user
  100. lssubs: List the currently available subscriptions
  101. remove: remove a subscription
  102. update: update the information about the available videos
  103. download: download all available videos which haven't already been
  104. downloaded
  105. search: optionally add a search string to a new subscription or
  106. create a search subscription with add
  107. playlist: with add, subscribe to a youtube playlist
  108. catchup: Mark all videos in a subscription as downloaded
  109. version: Print version number
  110. quiet: Suppress all output
  111. verbose: Print normal output + diagnostical messages
  112. clean-database: Clean the database of old entries, meaning videos that
  113. are no longer present in the current API response of youtube
  114. enable: enables a previously disabled subscription
  115. disable: disables a previously enabled subscription
  116. """
  117. parser = MyOptionParser(usage=_("Usage: %prog [options]"), prog="stov",
  118. add_help_option=True, conflict_handler="resolve")
  119. parser.add_option("-h", "--help", action="store_true", dest="help",
  120. help=_("show this help message and exit"))
  121. parser.add_option("-a", "--add", dest="add", action="store_true",
  122. help=_("Add a new subscription (requires either \
  123. --search, --channel or --playlist)"))
  124. parser.add_option("-p", "--playlist", dest="playlist",
  125. help=_("Add a new Playlist subscription (requires add)"))
  126. parser.add_option("-l", "--lssubs", action="store_true", dest="list",
  127. help=_("List the currently available subscriptions"))
  128. parser.add_option("-r", "--remove", type="int", dest="deleteid",
  129. help=_("remove a subscription"))
  130. parser.add_option("-u", "--update", action="store_true", dest="update",
  131. help=_("update the information about the available videos"))
  132. parser.add_option("-d", "--download", action="store_true", dest="download",
  133. help=_("download all available videos which haven't already "
  134. "been downloaded"))
  135. parser.add_option("-s", "--search", dest="searchparameter",
  136. help=_("optionally add a search string to a new channel "
  137. "subscription or create a new search subscription "
  138. "(requires --add)"))
  139. parser.add_option("-l", "--lsvids", type="int", dest="subscriptionid",
  140. help=_("Print all videos from a subscription"))
  141. parser.add_option("-c", "--catchup", dest="catchup",
  142. help=_("Mark all videos from one channel as read \
  143. (requires subscription-id as argument)"))
  144. parser.add_option("-c", "--channel", dest="channel",
  145. help=_("specify a channel for a new subscription "
  146. "(requires --add)"))
  147. parser.add_option("-l", "--license", dest="license", action="store_true",
  148. help=_("show the license of the program"))
  149. parser.add_option("-v", "--version", dest="version", action="store_true",
  150. help=_("show the current running version number"))
  151. parser.add_option("-q", "--quiet", dest="quiet", action="store_true",
  152. help=_("Suppress all output"))
  153. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  154. help=_("Be verbose and print also diagnostical messages"))
  155. parser.add_option("-c", "--clean-database", dest="cleanup",
  156. action="store_true", help=_("Clean the database of entries "
  157. "no longer listed in the current"
  158. " API response"))
  159. parser.add_option("-e", "--enable", type="int", dest="enableid",
  160. help=_("enables the subscription with the provided ID"))
  161. parser.add_option("--disable", type="int", dest="disableid",
  162. help=_("disables the subscription with the provided ID"))
  163. (options, arguments) = parser.parse_args()
  164. """Check if stov is run directly from command line since it shouldn't be
  165. loaded as a module
  166. """
  167. if __name__ != "__main__":
  168. print("This file should not be imported as a module"
  169. "please run it directly from command line")
  170. sys.exit(1)
  171. """Variable to determine if the exit code should be success or not"""
  172. exit_status = True
  173. """Check which outputlevel is defined and save it to a temporary variable
  174. accordingly. Output generated before this will be printed to stdout regardless
  175. of the user defined setting
  176. """
  177. if options.verbose is True and options.quiet is True:
  178. print(_("--quiet and --verbose can't be defined at the same time, "
  179. "exiting."), file=sys.stderr)
  180. sys.exit(1)
  181. elif options.verbose is True:
  182. outputlevel = "verbose"
  183. logger.setLevel(logging.DEBUG)
  184. elif options.quiet is True:
  185. outputlevel = "quiet"
  186. logger.setLevel(logging.ERROR)
  187. else:
  188. outputlevel = "default"
  189. logger.setLevel(logging.INFO)
  190. """Create the lock file which is used to determine if another instance is
  191. already running by chance, the program shouldn't be run in this case since
  192. we want to prevent concurent access to the database.
  193. """
  194. if os.access("/tmp/stov.lock", os.F_OK):
  195. try:
  196. lockfile = open("/tmp/stov.lock", "r")
  197. except IOError:
  198. logger.error(_("The lock file could not be opened, please check that "
  199. "it exists and is readable, quitting now"))
  200. sys.exit(1)
  201. oldpid = lockfile.read().strip()
  202. if os.access("/proc/" + oldpid, os.F_OK):
  203. logger.error(_("The lock file already exists, probably another"
  204. "instance of this program is already running\n"
  205. "if you are sure this is not the case, delete it"
  206. " manually and try again!"))
  207. sys.exit(1)
  208. lockfile.close()
  209. if os.access("/proc/" + oldpid, os.F_OK) is not True:
  210. try:
  211. os.remove("/tmp/stov.lock")
  212. except os.error:
  213. logger.error(_("The old lock file could not be deleted!"))
  214. try:
  215. lockfile = open("/tmp/stov.lock", "w")
  216. lockfile.write(str(os.getpid()))
  217. lockfile.close()
  218. except IOError:
  219. logger.error(_("The lock file could not be created, please check that /tmp"
  220. " is writable and properly configured, quitting now."))
  221. sys.exit(1)
  222. """Check if the configuration directory exists and is writeable. If it
  223. doesnt, create it using the configuration class.
  224. """
  225. if os.access(os.environ['HOME'] + "/.stov", os.F_OK & os.W_OK) is not True:
  226. logger.info(_("This seems to be the first time you run the programm, do "
  227. "you want to run the interactive assistant? (yes/no)"))
  228. conf = configuration.conf()
  229. if sys.version_info >= (3, 0):
  230. temp_input = input()
  231. else:
  232. # noinspection PyCompatibility
  233. temp_input = raw_input()
  234. if temp_input == "yes":
  235. conf.assist()
  236. try:
  237. conf.Initialize()
  238. except stov_exceptions.ConfigFileWriteErrorException as e:
  239. logger.error(e)
  240. else:
  241. logger.info(_("Writing initial configuration according to your "
  242. "input, have fun!"))
  243. else:
  244. logger.info(_("Writing initial configuration according to default"
  245. "values."))
  246. logger.debug(_("Creating hidden directory in home for configuration"
  247. "and database."))
  248. try:
  249. conf.Initialize()
  250. except stov_exceptions.DirectoryCreationFailedException as e:
  251. logger.error(e)
  252. except stov_exceptions.ConfigFileWriteErrorException as e:
  253. logger.error(e)
  254. else:
  255. conf = configuration.conf()
  256. try:
  257. logger.debug(_("Comparing current and running configuration version."))
  258. check_result = conf.CheckConfig()
  259. except stov_exceptions.ConfigFileReadErrorException as e:
  260. logger.error(e)
  261. except stov_exceptions.InvalidConfigurationVersionException as e:
  262. logger.error(e)
  263. else:
  264. if check_result is not True:
  265. logger.info(_("Your configuration needs to be updated, performing"
  266. " update now."))
  267. try:
  268. conf.UpdateConfig()
  269. except stov_exceptions.ConfigFileReadErrorException as e:
  270. logger.error(e)
  271. except stov_exceptions.ConfigFileWriteErrorException as e:
  272. logger.error(e)
  273. """Create the initial connection to the database"""
  274. if os.access(conf.dbpath, os.F_OK):
  275. try:
  276. db = database.db(path=conf.dbpath, version=conf.values["db_version"])
  277. except stov_exceptions.DBConnectionFailedException as e:
  278. logger.error(e)
  279. sys.exit(1)
  280. else:
  281. try:
  282. db = database.db(path=conf.dbpath, version=conf.values["db_version"])
  283. except stov_exceptions.DBConnectionFailedException as e:
  284. logger.error(e)
  285. sys.exit(1)
  286. else:
  287. try:
  288. db.Populate()
  289. except stov_exceptions.DBWriteAccessFailedException as e:
  290. logger.error(e)
  291. sys.exit(1)
  292. try:
  293. logger.debug(_("Comparing current and running database version."))
  294. if conf.CheckDB() is not True:
  295. logger.info(_("Your database needs to be updated, performing"
  296. " update now."))
  297. db.Update()
  298. conf.values["db_version"] = db.GetVersion()
  299. logger.debug("Opening configuration file.")
  300. try:
  301. conf.WriteConfig()
  302. except stov_exceptions.ConfigFileWriteErrorException as e:
  303. logger.error(e)
  304. except stov_exceptions.DBWriteAccessFailedException as e:
  305. logger.error(e)
  306. """Check which outputlevel is defined and update the configuration object
  307. accordingly.
  308. """
  309. conf.outputlevel = outputlevel
  310. """youtube-dl is really a dependency but the program will run with limited
  311. functionality without it so we need to check that here
  312. """
  313. if conf.values["youtube-dl"] == "":
  314. youtube_dl_path = subprocess.Popen(["which", "youtube-dl"],
  315. stdout=subprocess.PIPE)\
  316. .communicate()[0]
  317. conf.values["youtube-dl"] = youtube_dl_path.strip()
  318. if os.access(conf.values["youtube-dl"], os.F_OK & os.R_OK & os.X_OK):
  319. logger.info(_("Found youtube-dl, writing it's path to the "
  320. "configuration file."))
  321. logger.debug("Opening configuration file.")
  322. try:
  323. conf.WriteConfig()
  324. except stov_exceptions.ConfigFileWriteErrorException as e:
  325. logger.error(e)
  326. else:
  327. logger.error(_("Could not find youtube-dl, it either does not exist, "
  328. "is not readable or not executable. Please note that "
  329. "youtube-dl is not needed for the program to run but "
  330. "is needed to use the download option which won't work "
  331. "otherwise. If youtube-dl isn't found automatically, "
  332. "you may also enter the path to it in the configuration"
  333. " file."))
  334. """Variable to save the text that is later sent as e-mail"""
  335. mailcontent = []
  336. """Check which options are given on the command line and
  337. run the corresponding code
  338. """
  339. if options.add is True:
  340. if options.channel is not None and options.searchparameter is None:
  341. NewSubscription = subscription.sub(type="channel",
  342. name=options.channel, conf=conf)
  343. elif options.channel is not None and options.searchparameter is not None:
  344. NewSubscription = subscription.sub(type="channel",
  345. name=options.channel,
  346. search=options.searchparameter,
  347. conf=conf)
  348. elif options.channel is None and options.searchparameter is not None:
  349. NewSubscription = subscription.sub(type="search",
  350. name=_("Search_"),
  351. search=options.searchparameter,
  352. conf=conf)
  353. elif options.playlist is not None:
  354. if options.searchparameter is not None:
  355. logger.error(_("Playlists do not support searching, the search "
  356. "option will be ignored!"))
  357. NewSubscription = subscription.sub(type="playlist",
  358. name=options.playlist,
  359. conf=conf)
  360. else:
  361. logger.error(_("None or invalid subscription type given, please check "
  362. "the type option and try again."))
  363. sys.exit(1)
  364. try:
  365. message, id = db.InsertSubscription(NewSubscription.AddSub())
  366. NewSubscription.SetID(id)
  367. except stov_exceptions.DBWriteAccessFailedException as e:
  368. logger.error(e)
  369. try:
  370. NewSubscription.ParseAPIData()
  371. except stov_exceptions.YoutubeAPITimeoutException as e:
  372. logger.error(e)
  373. except stov_exceptions.NoDataFromYoutubeAPIException as e:
  374. logger.error(e)
  375. for video in NewSubscription.parsed_response.videos:
  376. if not db.VideoInDatabase(video.ytid):
  377. if NewSubscription.CheckStringMatch(video):
  378. db.InsertVideo(video, NewSubscription.GetId())
  379. logger.info(_("New subscription ") + NewSubscription.GetTitle()
  380. + _(" successfully added"))
  381. elif options.list is True:
  382. Listofsubscriptions = db.GetSubscriptions()
  383. sub_state = None
  384. if len(Listofsubscriptions) != 0:
  385. logger.info(_("ID Title"))
  386. for sub in Listofsubscriptions:
  387. if int(sub[6]) == 0:
  388. sub_state = _("enabled")
  389. elif int(sub[6]) == 1:
  390. sub_state = _("disabled")
  391. if sub[0] is not None:
  392. logger.info(str(sub[0]) + " " + sub[1]
  393. + " (%s)" % sub_state)
  394. else:
  395. logger.info(_("No subscriptions added yet, add one!"))
  396. elif options.deleteid is not None:
  397. try:
  398. DeleteID = int(options.deleteid)
  399. except ValueError:
  400. logger.error(_("Invalid Option, please use the ID of the subscription "
  401. "you want to delete as parameter for the remove "
  402. "option"))
  403. else:
  404. try:
  405. deletemessage = db.DeleteSubscription(DeleteID)
  406. except stov_exceptions.SubscriptionNotFoundException as e:
  407. logger.error(e)
  408. except stov_exceptions.DBWriteAccessFailedException as e:
  409. logger.error(e)
  410. else:
  411. logger.info(deletemessage)
  412. elif options.update is True:
  413. listofsubscriptions = []
  414. subscriptions = db.GetSubscriptions()
  415. for element in subscriptions:
  416. listofsubscriptions.append(subscription.sub(id=element[0],
  417. title=element[1],
  418. type=element[2],
  419. name=element[3],
  420. search=element[4],
  421. directory=element[5],
  422. disabled=element[6],
  423. conf=conf))
  424. for element in listofsubscriptions:
  425. try:
  426. element.ParseAPIData()
  427. except stov_exceptions.YoutubeAPITimeoutException as e:
  428. logger.error(e)
  429. except stov_exceptions.NoDataFromYoutubeAPIException as e:
  430. logger.error(e)
  431. for video in element.parsed_response.videos:
  432. if not db.VideoInDatabase(video.ytid):
  433. if element.CheckStringMatch(video):
  434. db.InsertVideo(video, element.GetId())
  435. elif options.download is True:
  436. listofsubscriptions = []
  437. subscriptions = db.GetSubscriptions()
  438. logger.debug(_("Trying to determine the itag value for youtube-dl from"
  439. " your quality and codec settings"))
  440. itag_value = conf.GetYoutubeParameter()
  441. logger.debug(_("Found value: %s.") % itag_value)
  442. if itag_value == 0:
  443. logger.debug(_("Codec and resolution could not be determined, using "
  444. "maximum possible value"))
  445. itag_value = 38
  446. for element in subscriptions:
  447. listofsubscriptions.append(subscription.sub(id=element[0],
  448. title=element[1],
  449. type=element[2],
  450. name=element[3],
  451. search=element[4],
  452. directory=element[5],
  453. disabled=element[6],
  454. conf=conf))
  455. videosdownloaded = 0
  456. videosfailed = 0
  457. for element in listofsubscriptions:
  458. videos = db.GetVideos(element.GetId())
  459. element.GatherVideos(videos)
  460. try:
  461. element.DownloadVideos(itag_value)
  462. except stov_exceptions.SubscriptionDisabledException as e:
  463. logger.debug(e)
  464. for entry in element.DownloadedVideos:
  465. db.UpdateVideoDownloadStatus(entry.GetID(), 1)
  466. mailcontent.append(entry.title)
  467. videosdownloaded = len(mailcontent)
  468. videosfailed = videosfailed + element.FailedVideosCount
  469. for video in element.FailedVideos:
  470. try:
  471. db.UpdateVideoFailCount(video.failcnt, video.GetID())
  472. if video.failcnt >= int(conf.values["maxfails"]):
  473. db.DisableFailedVideo(video.GetID())
  474. except stov_exceptions.DBWriteAccessFailedException as e:
  475. logger.error(e)
  476. if videosdownloaded > 0 and conf.values["notify"] == "yes":
  477. MailText = ""
  478. msg = MIMEMultipart()
  479. if videosdownloaded == 1:
  480. msg["Subject"] = _("Downloaded %i new video") % videosdownloaded
  481. MailText = _("The following episode has been downloaded by stov: "
  482. "\n\n")
  483. else:
  484. msg["Subject"] = _("Downloaded %i new videos") % videosdownloaded
  485. MailText = _("The following episodes have been downloaded by stov:"
  486. " \n\n")
  487. msg["From"] = "stov <%s>" % conf.values["mailfrom"]
  488. msg["To"] = "<%s>" % conf.values["mailto"]
  489. for line in mailcontent:
  490. MailText += line + "\n"
  491. msgtext = MIMEText(MailText.encode("utf8"), _charset="utf8")
  492. msg.attach(msgtext)
  493. serverconnection = smtplib.SMTP()
  494. try:
  495. if sys.version_info >= (3, 0):
  496. serverconnection.connect(conf.values["mailhost"],
  497. conf.values["smtpport"])
  498. else:
  499. serverconnection.connect(str(conf.values["mailhost"]),
  500. str(conf.values["smtpport"]))
  501. except (smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected,
  502. socket.error):
  503. logger.error(_("Could not connect to the smtp server, please check"
  504. " your settings!"))
  505. logger.error(MailText)
  506. else:
  507. try:
  508. serverconnection.starttls()
  509. except smtplib.SMTPException:
  510. logger.debug(_("TLS not available, proceeding unencrypted."))
  511. if conf.values["auth_needed"] == "yes":
  512. try:
  513. serverconnection.login(conf.values["user_name"],
  514. conf.values["password"])
  515. except smtplib.SMTPAuthenticationError:
  516. logger.error(_("Authentication failed, please check user "
  517. "name and password!"))
  518. except smtplib.SMTPException:
  519. logger.error(_("Could not authenticate, server probably "
  520. "does not support authentication!"))
  521. try:
  522. serverconnection.sendmail(conf.values["mailfrom"],
  523. conf.values["mailto"],
  524. msg.as_string())
  525. except smtplib.SMTPRecipientsRefused:
  526. logger.error(_("The server refused the recipient address, "
  527. "please check your settings."))
  528. except smtplib.SMTPSenderRefused:
  529. logger.error(_("The server refused the sender address, "
  530. "please check your settings."))
  531. serverconnection.quit()
  532. elif videosdownloaded == 0 and videosfailed == 0:
  533. if conf.values["notify"] == "no":
  534. logger.info(_("There No videos to be downloaded."))
  535. elif conf.values["notify"] == "no":
  536. if videosfailed == 0:
  537. logger.info(_("The following videos have been downloaded:\n"))
  538. for i in mailcontent:
  539. logger.info(i)
  540. else:
  541. if conf.values["notify"] != "yes":
  542. logger.error(_("Could not determine how you want to be informed "
  543. "about new videos, please check the notify parameter "
  544. "in your configuration"))
  545. elif options.subscriptionid is not None:
  546. try:
  547. Data = db.GetSubscription(options.subscriptionid)
  548. except stov_exceptions.DBWriteAccessFailedException as e:
  549. logger.error(e)
  550. sys.exit(1)
  551. else:
  552. if Data:
  553. Subscription = subscription.sub(id=Data[0][0], title=Data[0][1],
  554. type=Data[0][2], name=Data[0][3],
  555. search=Data[0][4],
  556. directory=Data[0][5],
  557. disabled=Data[0][6], conf=conf)
  558. videos = db.GetVideos(Subscription.GetId())
  559. Subscription.GatherVideos(videos)
  560. video_list = Subscription.PrintVideos()
  561. for video in video_list:
  562. logger.info(video)
  563. else:
  564. logger.error(_("Invalid subscription, please check the list and "
  565. "try again"))
  566. elif options.catchup is not None:
  567. try:
  568. sub_data = db.GetSubscriptionTitle(options.catchup)
  569. except stov_exceptions.DBWriteAccessFailedException as e:
  570. logger.error(e)
  571. else:
  572. if sub_data != []:
  573. try:
  574. db.MarkVideosDownloaded(options.catchup)
  575. except stov_exceptions.DBWriteAccessFailedException as e:
  576. logger.error(e)
  577. else:
  578. logger.error(_("The subscription could not be updated, "
  579. "please check if the ID given is correct."))
  580. elif options.cleanup is True:
  581. subscriptions_list = []
  582. subscriptions = db.GetSubscriptions()
  583. for element in subscriptions:
  584. subscriptions_list.append(subscription.sub(id=element[0],
  585. title=element[1], type=element[2],
  586. name=element[3], search=element[4],
  587. directory=element[5], disabled=element[6],
  588. conf=conf))
  589. for element in subscriptions_list:
  590. videos = db.GetVideos(element.GetId())
  591. element.CheckAndDelete(videos)
  592. for delete_video in element.ToDelete:
  593. logger.debug(_("Deleting video %s from "
  594. "database") % delete_video.title)
  595. try:
  596. db.DeleteVideo(delete_video.GetID())
  597. except stov_exceptions.DBWriteAccessFailedException as e:
  598. logger.error(e)
  599. try:
  600. db.Vacuum()
  601. except stov_exceptions.DBWriteAccessFailedException as e:
  602. logger.error(e)
  603. elif options.enableid is not None:
  604. subscription_state = db.GetSubscription(options.enableid)
  605. try:
  606. if int(subscription_state[0][6]) == 0:
  607. logger.error(_("The subscription ID %s is already enabled")
  608. % options.enableid)
  609. elif int(subscription_state[0][6]) == 1:
  610. try:
  611. db.ChangeSubscriptionState(options.enableid, 0)
  612. except stov_exceptions.DBWriteAccessFailedException as e:
  613. logger.error(e)
  614. else:
  615. logger.info(_("Enabled subscription ID %s")
  616. % options.enableid)
  617. except IndexError:
  618. logger.error(_("Could not find the subscription with ID %s, "
  619. "please check and try again") % options.enableid)
  620. elif options.disableid is not None:
  621. subscription_state = db.GetSubscription(options.disableid)
  622. try:
  623. if int(subscription_state[0][6]) == 1:
  624. logger.error(_("Subscription ID %s is already disabled")
  625. % options.disableid)
  626. elif int(subscription_state[0][6]) == 0:
  627. try:
  628. db.ChangeSubscriptionState(options.disableid, 1)
  629. except stov_exceptions.DBWriteAccessFailedException as e:
  630. logger.error(e)
  631. else:
  632. logger.info(_("Disabled subscription ID %s")
  633. % options.disableid)
  634. except IndexError:
  635. logger.error(_("Could not find the subscription with ID %s, please"
  636. " check and try again") % options.disableid)
  637. elif options.license is True:
  638. logger.info("""
  639. stov is free software: you can redistribute it and/or modify
  640. it under the terms of the GNU General Public License as published by
  641. the Free Software Foundation, version 2 of the License.
  642. stov is distributed in the hope that it will be useful,
  643. but WITHOUT ANY WARRANTY; without even the implied warranty of
  644. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  645. GNU General Public License for more details.
  646. You should have received a copy of the GNU General Public License
  647. along with stov. If not, see <http://www.gnu.org/licenses/>.""")
  648. elif options.version is True:
  649. logger.info("0.8wip")
  650. else:
  651. parser.print_help()
  652. """Remove the lock file and end the program so it can be run again"""
  653. try:
  654. os.remove("/tmp/stov.lock")
  655. if exit_status is True:
  656. sys.exit(0)
  657. else:
  658. sys.exit(1)
  659. except os.error:
  660. logger.error(_("Could not delete the lock file. Please check what "
  661. "went wrong and clean up manually!"))