stov 30 KB

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