configuration.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. import os
  16. import gettext
  17. import sys
  18. import sqlite3
  19. import subprocess
  20. from outputhelper import printf
  21. class conf(object):
  22. def __init__(self):
  23. """Constructor
  24. Constructs the conf object with some reasonable default values which should
  25. work on most systems, existence of a local mail server is assumed.
  26. """
  27. self.values = {
  28. "database": "stov.sqlite",
  29. "downloaddir": str(os.environ['HOME']) + "/stov",
  30. "maxvideos": "25",
  31. "mailhost": "localhost",
  32. "mailto": "root",
  33. "mailfrom": "stov@localhost",
  34. "smtpport": "25",
  35. "auth_needed": "no",
  36. "user_name": "",
  37. "password": "",
  38. "youtube-dl": "",
  39. "notify": "yes",
  40. "config_version": "6",
  41. "db_version": "2",
  42. "videocodec": "h264",
  43. "maxresolution": "1080p",
  44. "maxfails": "50"
  45. }
  46. self.dbpath = str(os.environ['HOME']) + "/.stov/" + self.values["database"]
  47. self.outputlevel = "default"
  48. def WriteConfig(self):
  49. """Writes the configuration from the dictionary into the configuration file
  50. for stov. The configuration is written into the home directory of the user
  51. by default.
  52. """
  53. try:
  54. printf(_("Opening configuration file"),
  55. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  56. self.configfile = open(str(os.environ['HOME']) + "/.stov/stov.config", "w")
  57. except IOError, os.error:
  58. printf(_("Configuration could not be written, please"
  59. " check that the configuration directory exists and is writable"),
  60. outputlevel="default", level=self.outputlevel, descriptor="stderr")
  61. else:
  62. for key in self.values.iterkeys():
  63. printf(_("Writing value for %s" % key.upper()),
  64. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  65. self.configfile.write(key.upper() + "=" + self.values[key] + "\n")
  66. self.configfile.close()
  67. def CreateDB(self):
  68. """Creates the database structure if it doesn't exist already."""
  69. try:
  70. self.__database = sqlite3.connect(self.dbpath)
  71. except sqlite3.OperationalError:
  72. printf(_("The database could not be created, please "
  73. "check that the configuration directory exists and is writable"),
  74. outputlevel = "default", level=self.outputlevel, descriptor="stderr")
  75. else:
  76. self.__dbcursor = self.__database.cursor()
  77. printf(_("Creating table subscriptions"),
  78. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  79. self.__dbcursor.execute("""CREATE TABLE subscriptions (
  80. id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  81. title TEXT,
  82. name TEXT,
  83. type TEXT,
  84. searchstring TEXT,
  85. directory TEXT
  86. );""")
  87. printf(_("Creating table videos"),
  88. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  89. self.__dbcursor.execute("""CREATE TABLE videos (
  90. id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  91. title TEXT,
  92. description TEXT,
  93. ytid TEXT,
  94. subscription_id INTEGER,
  95. downloaded INT,
  96. failcnt INT DEFAULT 0
  97. );""")
  98. self.__database.commit()
  99. self.__database.close()
  100. def Initialize(self):
  101. """Creates the necessary directory for the stov configuration and calls the
  102. internal methods to create the database and the configuration file.
  103. """
  104. try:
  105. printf(_("Creating hidden directory in home for configuration and database"),
  106. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  107. os.mkdir(str(os.environ['HOME']) + "/.stov", 0750)
  108. except os.error:
  109. printf(_("Configuration directory could not be created, "
  110. "please check that your home directory exists and is writable"),
  111. outputlevel="default", level=self.outputlevel, descriptor="stderr")
  112. else:
  113. printf(_("Looking for youtube-dl file"),
  114. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  115. self.values["youtube-dl"] = subprocess.Popen(["which", "youtube-dl"],
  116. stdout=subprocess.PIPE).communicate()[0].strip()
  117. self.WriteConfig()
  118. self.CreateDB()
  119. def ReadConfig(self):
  120. """Reads the existing configuration file and places the values in the
  121. dictionary. Existing values (such as default values) are overwritten.
  122. """
  123. try:
  124. printf(_("Opening config file for reading"),
  125. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  126. self.configfile = open(str(os.environ['HOME']) + "/.stov/stov.config", "r")
  127. except IOError:
  128. printf(_("Configuration could not be "
  129. "read, please check that the configuration file exists and is readable"),
  130. outputlevel="default", level=self.outputlevel, descriptor="stderr")
  131. for lines in self.configfile:
  132. printf(_("Reading line %s" % lines.strip()),
  133. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  134. self.tmpline = lines.strip()
  135. self.tmplist = self.tmpline.split("=")
  136. self.values[self.tmplist[0].lower()] = self.tmplist[1]
  137. self.configfile.close()
  138. self.dbpath = str(os.environ['HOME']) + "/.stov/" + self.values["database"]
  139. def CheckConfig(self):
  140. """Checks if the configuration is up-to-date with the running
  141. stov version.
  142. """
  143. printf(_("Checking current and running configuration version"),
  144. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  145. try:
  146. self.__currentversion = int(self.values["config_version"])
  147. except ValueError:
  148. printf(_("Invalid config version read"), outputlevel="default",
  149. level=self.outputlevel, descriptor="stderr")
  150. self.values["config_version"] = "0"
  151. self.__currentdbversion = self.values["db_version"]
  152. self.ReadConfig()
  153. printf(_("Found running version: " + self.values["config_version"] + "\n" +
  154. "Current version: " + str(self.__currentversion)),
  155. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  156. if self.values["config_version"] == "0" \
  157. or int(self.values["config_version"]) < self.__currentversion:
  158. self.values["config_version"] = str(self.__currentversion)
  159. return False
  160. else:
  161. self.values["config_version"] = str(self.__currentversion)
  162. return True
  163. def UpdateConfig(self):
  164. """Update the configuration to the latest version"""
  165. self.__versionbuffer = self.values["config_version"]
  166. self.ReadConfig()
  167. self.values["config_version"] = self.__versionbuffer
  168. self.WriteConfig()
  169. def CheckDB(self):
  170. """Checks the database if it is up-to-date"""
  171. printf(_("Checking current and running database version."),
  172. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  173. self.values["db_version"] = "0"
  174. self.ReadConfig()
  175. printf(_("Found running database version: " + self.values["db_version"] +
  176. "\n" + "Current version: " + str(self.__currentversion)),
  177. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  178. if self.values["db_version"] == "0" or \
  179. int(self.values["db_version"]) < int(self.__currentdbversion):
  180. self.values["db_version"] = str(self.__currentversion)
  181. return False
  182. else:
  183. self.values["db_version"] = str(self.__currentversion)
  184. return True
  185. def UpdateDB(self):
  186. """Performs database changes that need to be done"""
  187. self.ReadConfig()
  188. if int(self.values["db_version"]) == 1:
  189. try:
  190. self.__database = sqlite3.connect(self.dbpath)
  191. except sqlite3.OperationalError:
  192. printf(_("The database could not be updated, please "
  193. "check that the configuration directory exists and is writable"),
  194. outputlevel = "default", level=self.outputlevel, descriptor="stderr")
  195. else:
  196. self.__dbcursor = self.__database.cursor()
  197. self.__dbcursor.execute("ALTER TABLE videos add column failcnt int DEFAULT 0;")
  198. self.__database.commit()
  199. self.__database.close()
  200. self.ReadConfig()
  201. self.values["db_version"] = "2"
  202. self.WriteConfig()
  203. else:
  204. pass
  205. def GetYoutubeParameter(self):
  206. """Determines which itag value results from codec and resolution settings
  207. and returns it
  208. """
  209. printf(_("Trying to determine the itag value for youtube-dl from your"
  210. " quality and codec settings"),
  211. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  212. itag_value = 0
  213. if self.values["videocodec"] == "flv":
  214. if self.values["maxresolution"] == "240p":
  215. itag_value = 5
  216. elif self.values["maxresolution"] == "270p":
  217. itag_value = 6
  218. elif self.values["maxresolution"] == "360p":
  219. itag_value = 34
  220. elif self.values["maxresolution"] == "480p":
  221. itag_value = 35
  222. elif self.values["videocodec"] == "webm":
  223. if self.values["maxresolution"] == "360p":
  224. itag_value = 43
  225. elif self.values["maxresolution"] == "480p":
  226. itag_value = 44
  227. elif self.values["maxresolution"] == "720p":
  228. itag_value = 45
  229. elif self.values["maxresolution"] == "1080p":
  230. itag_value = 46
  231. elif self.values["videocodec"] == "h264":
  232. if self.values["maxresolution"] == "360p":
  233. itag_value = 18
  234. elif self.values["maxresolution"] == "720p":
  235. itag_value = 22
  236. elif self.values["maxresolution"] == "1080p":
  237. itag_value = 37
  238. elif self.values["maxresolution"] == "3072p":
  239. itag_value = 38
  240. printf(_("Found value: %s" % itag_value),
  241. outputlevel="verbose", level=self.outputlevel, descriptor="stderr")
  242. return itag_value