stov 26 KB

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