1
0

configuration.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. # This file is part of stov, written by Helmut Pozimski in 2012.
  2. #
  3. # stov is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, version 2 of the License.
  6. #
  7. # stov is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License
  13. # along with stov. If not, see <http://www.gnu.org/licenses/>.
  14. # -*- coding: utf8 -*-
  15. from __future__ import unicode_literals
  16. import os
  17. import gettext
  18. import sys
  19. import sqlite3
  20. import subprocess
  21. from outputhelper import printf
  22. class conf(object):
  23. def __init__(self):
  24. """Constructor
  25. Constructs the conf object with some reasonable default values which should
  26. work on most systems, existence of a local mail server is assumed.
  27. """
  28. self.values = {
  29. "database": "stov.sqlite",
  30. "downloaddir": str(os.environ['HOME']) + "/stov",
  31. "maxvideos": "25",
  32. "mailhost": "localhost",
  33. "mailto": "root",
  34. "mailfrom": "stov@localhost",
  35. "smtpport": "25",
  36. "auth_needed": "no",
  37. "user_name": "",
  38. "password": "",
  39. "youtube-dl": "",
  40. "notify": "yes",
  41. "config_version": "7",
  42. "db_version": "2",
  43. "videocodec": "h264",
  44. "maxresolution": "1080p",
  45. "maxfails": "50",
  46. "check_title": "no"
  47. }
  48. self.__explanations = {
  49. "database": _("the name of your database file"),
  50. "downloaddir": _("the directory where downloaded videos are saved"),
  51. "maxvideos": _("the maximum number of videos to retrieve for each "
  52. "subscription"),
  53. "mailhost": _("the host of your mail server"),
  54. "mailto": _("the address used for notifications"),
  55. "mailfrom": _("the sender address of notification e-mails"),
  56. "smtpport": _("the port to use on your mail server"),
  57. "auth_needed": _("if your mail server requires authentication"),
  58. "user_name": _("the user name used to authenticate to your mail server"),
  59. "password": _("the password used to authenticate to your mail server"),
  60. "youtube-dl": _("the path to your youtube-dl installation"),
  61. "notify": _("if you want to be notified via e-mail about new videos"),
  62. "videocodec": _("which video codec you prefer (h264, webm or flv)"),
  63. "maxresolution": _("which resolution you prefer (360p, 480p, 720p "
  64. "or 1080p)"),
  65. "check_title": _("if you want to compare the title of a video with the "
  66. "subscription search string")
  67. }
  68. self.dbpath = str(os.environ['HOME']) + "/.stov/" + self.values["database"]
  69. self.outputlevel = "default"
  70. def WriteConfig(self):
  71. """Writes the configuration from the dictionary into the configuration file
  72. for stov. The configuration is written into the home directory of the user
  73. by default.
  74. """
  75. try:
  76. printf(_("Opening configuration file"),
  77. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  78. self.configfile = open(str(os.environ['HOME']) + "/.stov/stov.config", "w")
  79. except IOError:
  80. printf(_("Configuration could not be written, please"
  81. " check that the configuration directory exists and is writable"),
  82. outputlevel="default", level=self.outputlevel, descriptor="stderr")
  83. else:
  84. for key in self.values.iterkeys():
  85. printf(_("Writing value for %s") % key.upper(),
  86. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  87. self.configfile.write(key.upper() + "=" + self.values[key] + "\n")
  88. self.configfile.close()
  89. def CreateDB(self):
  90. """Creates the database structure if it doesn't exist already."""
  91. try:
  92. self.__database = sqlite3.connect(self.dbpath)
  93. except sqlite3.OperationalError:
  94. printf(_("The database could not be created, please "
  95. "check that the configuration directory exists and is writable"),
  96. outputlevel="default", level=self.outputlevel, descriptor="stderr")
  97. else:
  98. self.__dbcursor = self.__database.cursor()
  99. printf(_("Creating table subscriptions"),
  100. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  101. self.__dbcursor.execute("""CREATE TABLE subscriptions (
  102. id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  103. title TEXT,
  104. name TEXT,
  105. type TEXT,
  106. searchstring TEXT,
  107. directory TEXT
  108. );""")
  109. printf(_("Creating table videos"),
  110. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  111. self.__dbcursor.execute("""CREATE TABLE videos (
  112. id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  113. title TEXT,
  114. description TEXT,
  115. ytid TEXT,
  116. subscription_id INTEGER,
  117. downloaded INT,
  118. failcnt INT DEFAULT 0
  119. );""")
  120. self.__database.commit()
  121. self.__database.close()
  122. def Initialize(self):
  123. """Creates the necessary directory for the stov configuration and calls the
  124. internal methods to create the database and the configuration file.
  125. """
  126. try:
  127. printf(_("Creating hidden directory in home for configuration and "
  128. "database"),
  129. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  130. os.mkdir(str(os.environ['HOME']) + "/.stov", 0o750)
  131. except os.error:
  132. printf(_("Configuration directory could not be created, "
  133. "please check that your home directory exists and is writable"),
  134. outputlevel="default", level=self.outputlevel, descriptor="stderr")
  135. else:
  136. printf(_("Looking for youtube-dl file"),
  137. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  138. self.values["youtube-dl"] = subprocess.Popen(["which", "youtube-dl"],
  139. stdout=subprocess.PIPE).communicate()[0].strip()
  140. self.WriteConfig()
  141. self.CreateDB()
  142. def ReadConfig(self):
  143. """Reads the existing configuration file and places the values in the
  144. dictionary. Existing values (such as default values) are overwritten.
  145. """
  146. try:
  147. printf(_("Opening config file for reading"),
  148. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  149. self.configfile = open(str(os.environ['HOME']) + "/.stov/stov.config", "r")
  150. except IOError:
  151. printf(_("Configuration could not be "
  152. "read, please check that the configuration file exists and is readable"),
  153. outputlevel="default", level=self.outputlevel, descriptor="stderr")
  154. for lines in self.configfile:
  155. printf(_("Reading line %s") % lines.strip(),
  156. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  157. self.tmpline = lines.strip()
  158. self.tmplist = self.tmpline.split("=")
  159. self.values[self.tmplist[0].lower()] = self.tmplist[1]
  160. self.configfile.close()
  161. self.dbpath = str(os.environ['HOME']) + "/.stov/" + self.values["database"]
  162. def CheckConfig(self):
  163. """Checks if the configuration is up-to-date with the running
  164. stov version.
  165. """
  166. printf(_("Checking current and running configuration version"),
  167. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  168. try:
  169. self.__currentversion = int(self.values["config_version"])
  170. except ValueError:
  171. printf(_("Invalid config version read"), outputlevel="default",
  172. level=self.outputlevel, descriptor="stderr")
  173. self.values["config_version"] = "0"
  174. self.__currentdbversion = self.values["db_version"]
  175. self.ReadConfig()
  176. printf(_("Found running version: ") + self.values["config_version"] + "\n" +
  177. _("Current version: ") + str(self.__currentversion),
  178. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  179. if self.values["config_version"] == "0" \
  180. or int(self.values["config_version"]) < self.__currentversion:
  181. self.values["config_version"] = str(self.__currentversion)
  182. return False
  183. else:
  184. self.values["config_version"] = str(self.__currentversion)
  185. return True
  186. def UpdateConfig(self):
  187. """Update the configuration to the latest version"""
  188. self.__versionbuffer = self.values["config_version"]
  189. self.ReadConfig()
  190. self.values["config_version"] = self.__versionbuffer
  191. self.WriteConfig()
  192. def CheckDB(self):
  193. """Checks the database if it is up-to-date"""
  194. printf(_("Checking current and running database version."),
  195. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  196. self.values["db_version"] = "0"
  197. self.ReadConfig()
  198. printf(_("Found running database version: ") + self.values["db_version"] +
  199. "\n" + _("Current version: ") + str(self.__currentversion),
  200. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  201. if self.values["db_version"] == "0" or \
  202. int(self.values["db_version"]) < int(self.__currentdbversion):
  203. self.values["db_version"] = str(self.__currentversion)
  204. return False
  205. else:
  206. self.values["db_version"] = str(self.__currentversion)
  207. return True
  208. def UpdateDB(self):
  209. """Performs database changes that need to be done"""
  210. self.ReadConfig()
  211. if int(self.values["db_version"]) == 1:
  212. try:
  213. self.__database = sqlite3.connect(self.dbpath)
  214. except sqlite3.OperationalError:
  215. printf(_("The database could not be updated, please "
  216. "check that the configuration directory exists and is writable"),
  217. outputlevel="default", level=self.outputlevel, descriptor="stderr")
  218. else:
  219. self.__dbcursor = self.__database.cursor()
  220. self.__dbcursor.execute("ALTER TABLE videos add column failcnt int \
  221. DEFAULT 0;")
  222. self.__database.commit()
  223. self.__database.close()
  224. self.ReadConfig()
  225. self.values["db_version"] = "2"
  226. self.WriteConfig()
  227. else:
  228. pass
  229. def GetYoutubeParameter(self):
  230. """Determines which itag value results from codec and resolution settings
  231. and returns it
  232. """
  233. printf(_("Trying to determine the itag value for youtube-dl from your"
  234. " quality and codec settings"),
  235. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  236. itag_value = 0
  237. if self.values["videocodec"] == "flv":
  238. if self.values["maxresolution"] == "240p":
  239. itag_value = 5
  240. elif self.values["maxresolution"] == "270p":
  241. itag_value = 6
  242. elif self.values["maxresolution"] == "360p":
  243. itag_value = 34
  244. elif self.values["maxresolution"] == "480p":
  245. itag_value = 35
  246. elif self.values["videocodec"] == "webm":
  247. if self.values["maxresolution"] == "360p":
  248. itag_value = 43
  249. elif self.values["maxresolution"] == "480p":
  250. itag_value = 44
  251. elif self.values["maxresolution"] == "720p":
  252. itag_value = 45
  253. elif self.values["maxresolution"] == "1080p":
  254. itag_value = 46
  255. elif self.values["videocodec"] == "h264":
  256. if self.values["maxresolution"] == "360p":
  257. itag_value = 18
  258. elif self.values["maxresolution"] == "720p":
  259. itag_value = 22
  260. elif self.values["maxresolution"] == "1080p":
  261. itag_value = 37
  262. elif self.values["maxresolution"] == "3072p":
  263. itag_value = 38
  264. printf(_("Found value: %s") % itag_value,
  265. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  266. return itag_value
  267. def assist(self):
  268. """ Ask the user to set all required configuration parameters """
  269. printf(_("This assistant will help you to perform the initial configuration"
  270. " of stov. \nThe default value will be displayed in brackets.\n"
  271. "Please specify now :\n"), outputlevel="default", level=self.outputlevel,
  272. descriptor="stdout")
  273. for value in self.__explanations:
  274. printf(self.__explanations[value] + " [" + self.values[value] + "]: ",
  275. outputlevel="default", level=self.outputlevel,
  276. descriptor="stdout")
  277. self.__user_input = raw_input()
  278. if self.__user_input != "":
  279. self.values[value] = self.__user_input
  280. self.dbpath = str(os.environ['HOME']) + "/.stov/" + self.values["database"]
  281. self.Initialize()
  282. printf(_("Writing initial configuration according to your input, have fun!"),
  283. outputlevel="default", level=self.outputlevel, descriptor="stdout")