configuration.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. # This file is part of stov, written by Helmut Pozimski 2012-2014.
  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. from __future__ import print_function
  17. import os
  18. import subprocess
  19. import sys
  20. import json
  21. from lib_stov import stov_exceptions
  22. class conf(object):
  23. def __init__(self):
  24. """Constructor
  25. Constructs the conf object with some reasonable default values which
  26. should work on most systems, existence of a local mail server is
  27. assumed.
  28. """
  29. self.values = {
  30. "database": "stov.sqlite",
  31. "downloaddir": str(os.environ['HOME']) + "/stov",
  32. "maxvideos": "25",
  33. "mailhost": "localhost",
  34. "mailto": "root",
  35. "mailfrom": "stov@localhost",
  36. "smtpport": "25",
  37. "auth_needed": "no",
  38. "user_name": "",
  39. "password": "",
  40. "youtube-dl": "",
  41. "notify": "yes",
  42. "config_version": "8",
  43. "db_version": "3",
  44. "videocodec": "h264",
  45. "maxresolution": "1080p",
  46. "maxfails": 50,
  47. "check_title": "no",
  48. "use_api": True
  49. }
  50. self.__explanations = {
  51. "database": _("the name of your database file"),
  52. "downloaddir": _("the directory where downloaded videos are "
  53. "saved"),
  54. "maxvideos": _("the maximum number of videos to retrieve for each "
  55. "subscription"),
  56. "mailhost": _("the host name of your mail server"),
  57. "mailto": _("the address used for notifications"),
  58. "mailfrom": _("the sender address of notification e-mails"),
  59. "smtpport": _("the port to use on your mail server"),
  60. "auth_needed": _("if your mail server requires authentication"),
  61. "user_name": _("the user name used to authenticate to your mail "
  62. "server"),
  63. "password": _("the password used to authenticate to your mail "
  64. "server"),
  65. "youtube-dl": _("the path to your youtube-dl installation"),
  66. "notify": _("if you want to be notified via e-mail about new "
  67. "videos"),
  68. "videocodec": _("which video codec you prefer (h264, webm or "
  69. "flv)"),
  70. "maxresolution": _("which resolution you prefer (360p, 480p, 720p "
  71. "or 1080p)"),
  72. "check_title": _("if you want to compare the title of a video "
  73. "with the subscription search string"),
  74. "use_api": _("if you want to use the youtube API")
  75. }
  76. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  77. self.values["database"]
  78. self.outputlevel = "default"
  79. def WriteConfig(self):
  80. """Writes the configuration from the dictionary into the configuration
  81. file for stov. The configuration is written into the home directory of
  82. the user by default.
  83. """
  84. try:
  85. configfile = open(str(os.environ['HOME']) +
  86. "/.stov/stov.json", "w")
  87. except IOError:
  88. raise stov_exceptions.ConfigFileWriteErrorException()
  89. else:
  90. json.dump(self.values, configfile, indent=0)
  91. configfile.close()
  92. def Initialize(self):
  93. """Creates the necessary directory for the stov configuration and
  94. calls the internal methods to create the database and the
  95. configuration file.
  96. """
  97. try:
  98. os.mkdir(str(os.environ['HOME']) + "/.stov", 0o750)
  99. except os.error:
  100. raise stov_exceptions.DirectoryCreationFailedException()
  101. else:
  102. process = subprocess.Popen(["which", "youtube-dl"],
  103. stdout=subprocess.PIPE)
  104. self.values["youtube-dl"] = process.communicate()[0].strip()
  105. self.WriteConfig()
  106. def ReadOldConfig(self):
  107. """Reads the existing plain text configuration file and places the
  108. values in the dictionary. Existing values (such as default values)
  109. are overwritten.
  110. """
  111. try:
  112. configfile = open(str(os.environ['HOME']) +
  113. "/.stov/stov.config", "r")
  114. except IOError:
  115. raise stov_exceptions.ConfigFileReadErrorException()
  116. for lines in configfile:
  117. tmpline = lines.strip()
  118. tmplist = tmpline.split("=")
  119. self.values[tmplist[0].lower()] = tmplist[1]
  120. configfile.close()
  121. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  122. self.values["database"]
  123. def ReadConfig(self):
  124. """Reads the existing json configuration files and loads the values in
  125. the dictionary.
  126. """
  127. try:
  128. configfile = open(str(os.environ['HOME']) + "/.stov/stov.json",
  129. "r")
  130. except IOError:
  131. raise stov_exceptions.ConfigFileReadErrorException()
  132. else:
  133. self.values.update(json.load(configfile))
  134. configfile.close()
  135. def CheckConfig(self):
  136. """Checks if the configuration is up-to-date with the running
  137. stov version.
  138. """
  139. try:
  140. currentversion = int(self.values["config_version"])
  141. except ValueError:
  142. raise stov_exceptions.InvalidConfigurationVersionException()
  143. self.values["config_version"] = "0"
  144. self.ReadConfig()
  145. if self.values["config_version"] == "0" \
  146. or int(self.values["config_version"]) < currentversion:
  147. self.values["config_version"] = str(currentversion)
  148. return False
  149. else:
  150. self.values["config_version"] = currentversion
  151. return True
  152. def UpdateConfig(self):
  153. """Update the configuration to the latest version"""
  154. versionbuffer = self.values["config_version"]
  155. self.ReadConfig()
  156. self.values["config_version"] = versionbuffer
  157. self.WriteConfig()
  158. def CheckDB(self):
  159. """Checks the database if it is up-to-date"""
  160. currentdbversion = int(self.values["db_version"])
  161. self.values["db_version"] = "0"
  162. self.ReadConfig()
  163. if self.values["db_version"] == "0" or \
  164. int(self.values["db_version"]) <\
  165. int(currentdbversion):
  166. self.values["db_version"] = str(currentdbversion)
  167. return False
  168. else:
  169. self.values["db_version"] = str(currentdbversion)
  170. return True
  171. def GetYoutubeParameter(self):
  172. """Determines which itag value results from codec and resolution
  173. settings and returns it
  174. """
  175. itag_value = 0
  176. if self.values["videocodec"] == "flv":
  177. if self.values["maxresolution"] == "240p":
  178. itag_value = 5
  179. elif self.values["maxresolution"] == "270p":
  180. itag_value = 6
  181. elif self.values["maxresolution"] == "360p":
  182. itag_value = 34
  183. elif self.values["maxresolution"] == "480p":
  184. itag_value = 35
  185. elif self.values["videocodec"] == "webm":
  186. if self.values["maxresolution"] == "360p":
  187. itag_value = 43
  188. elif self.values["maxresolution"] == "480p":
  189. itag_value = 44
  190. elif self.values["maxresolution"] == "720p":
  191. itag_value = 45
  192. elif self.values["maxresolution"] == "1080p":
  193. itag_value = 46
  194. elif self.values["videocodec"] == "h264":
  195. if self.values["maxresolution"] == "360p":
  196. itag_value = 18
  197. elif self.values["maxresolution"] == "720p":
  198. itag_value = 22
  199. elif self.values["maxresolution"] == "1080p":
  200. itag_value = 37
  201. elif self.values["maxresolution"] == "3072p":
  202. itag_value = 38
  203. return itag_value
  204. def assist(self):
  205. """ Ask the user to set all required configuration parameters """
  206. print(_("This assistant will help you to perform the initial "
  207. "configuration of stov. \nThe default value will be "
  208. "displayed in brackets.\n"
  209. "Please specify now :\n"))
  210. for value in self.__explanations:
  211. print(self.__explanations[value] + " [" + self.values[value] +
  212. "]:" +
  213. " ")
  214. if sys.version_info >= (3, 0):
  215. user_input = input()
  216. else:
  217. user_input = raw_input()
  218. if user_input != "":
  219. self.values[value] = user_input
  220. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  221. self.values["database"]
  222. def migrate_config(self):
  223. """Migrates the configuration from the old plain text config to
  224. the new and shiny json configuration file.
  225. """
  226. try:
  227. self.ReadOldConfig()
  228. self.WriteConfig()
  229. except stov_exceptions.ConfigFileReadErrorException:
  230. raise stov_exceptions.ConfigurationMigrationFailed()
  231. except stov_exceptions.ConfigFileWriteErrorException:
  232. raise stov_exceptions.ConfigurationMigrationFailed
  233. else:
  234. os.remove(str(os.environ['HOME']) + "/.stov/stov.config")