configuration.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. }
  75. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  76. self.values["database"]
  77. self.outputlevel = "default"
  78. def WriteConfig(self):
  79. """Writes the configuration from the dictionary into the configuration
  80. file for stov. The configuration is written into the home directory of
  81. the user by default.
  82. """
  83. try:
  84. configfile = open(str(os.environ['HOME']) +
  85. "/.stov/stov.json", "w")
  86. except IOError:
  87. raise stov_exceptions.ConfigFileWriteErrorException()
  88. else:
  89. json.dump(self.values, configfile, indent=0)
  90. configfile.close()
  91. def Initialize(self):
  92. """Creates the necessary directory for the stov configuration and
  93. calls the internal methods to create the database and the
  94. configuration file.
  95. """
  96. try:
  97. os.mkdir(str(os.environ['HOME']) + "/.stov", 0o750)
  98. except os.error:
  99. raise stov_exceptions.DirectoryCreationFailedException()
  100. else:
  101. process = subprocess.Popen(["which", "youtube-dl"],
  102. stdout=subprocess.PIPE)
  103. self.values["youtube-dl"] = process.communicate()[0].strip()
  104. self.WriteConfig()
  105. def ReadOldConfig(self):
  106. """Reads the existing plain text configuration file and places the
  107. values in the dictionary. Existing values (such as default values)
  108. are overwritten.
  109. """
  110. try:
  111. configfile = open(str(os.environ['HOME']) +
  112. "/.stov/stov.config", "r")
  113. except IOError:
  114. raise stov_exceptions.ConfigFileReadErrorException()
  115. for lines in configfile:
  116. tmpline = lines.strip()
  117. tmplist = tmpline.split("=")
  118. self.values[tmplist[0].lower()] = tmplist[1]
  119. configfile.close()
  120. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  121. self.values["database"]
  122. def ReadConfig(self):
  123. """Reads the existing json configuration files and loads the values in
  124. the dictionary.
  125. """
  126. try:
  127. configfile = open(str(os.environ['HOME']) + "/.stov/stov.json",
  128. "r")
  129. except IOError:
  130. raise stov_exceptions.ConfigFileReadErrorException()
  131. else:
  132. self.values.update(json.load(configfile))
  133. configfile.close()
  134. def CheckConfig(self):
  135. """Checks if the configuration is up-to-date with the running
  136. stov version.
  137. """
  138. try:
  139. currentversion = int(self.values["config_version"])
  140. except ValueError:
  141. raise stov_exceptions.InvalidConfigurationVersionException()
  142. self.values["config_version"] = "0"
  143. self.ReadConfig()
  144. if self.values["config_version"] == "0" \
  145. or int(self.values["config_version"]) < currentversion:
  146. self.values["config_version"] = str(currentversion)
  147. return False
  148. else:
  149. self.values["config_version"] = currentversion
  150. return True
  151. def UpdateConfig(self):
  152. """Update the configuration to the latest version"""
  153. versionbuffer = self.values["config_version"]
  154. self.ReadConfig()
  155. self.values["config_version"] = versionbuffer
  156. self.WriteConfig()
  157. def CheckDB(self):
  158. """Checks the database if it is up-to-date"""
  159. currentdbversion = int(self.values["db_version"])
  160. self.values["db_version"] = "0"
  161. self.ReadConfig()
  162. if self.values["db_version"] == "0" or \
  163. int(self.values["db_version"]) <\
  164. int(currentdbversion):
  165. self.values["db_version"] = str(currentdbversion)
  166. return False
  167. else:
  168. self.values["db_version"] = str(currentdbversion)
  169. return True
  170. def GetYoutubeParameter(self):
  171. """Determines which itag value results from codec and resolution
  172. settings and returns it
  173. """
  174. itag_value = 0
  175. if self.values["videocodec"] == "flv":
  176. if self.values["maxresolution"] == "240p":
  177. itag_value = 5
  178. elif self.values["maxresolution"] == "270p":
  179. itag_value = 6
  180. elif self.values["maxresolution"] == "360p":
  181. itag_value = 34
  182. elif self.values["maxresolution"] == "480p":
  183. itag_value = 35
  184. elif self.values["videocodec"] == "webm":
  185. if self.values["maxresolution"] == "360p":
  186. itag_value = 43
  187. elif self.values["maxresolution"] == "480p":
  188. itag_value = 44
  189. elif self.values["maxresolution"] == "720p":
  190. itag_value = 45
  191. elif self.values["maxresolution"] == "1080p":
  192. itag_value = 46
  193. elif self.values["videocodec"] == "h264":
  194. if self.values["maxresolution"] == "360p":
  195. itag_value = 18
  196. elif self.values["maxresolution"] == "720p":
  197. itag_value = 22
  198. elif self.values["maxresolution"] == "1080p":
  199. itag_value = 37
  200. elif self.values["maxresolution"] == "3072p":
  201. itag_value = 38
  202. return itag_value
  203. def assist(self):
  204. """ Ask the user to set all required configuration parameters """
  205. print(_("This assistant will help you to perform the initial "
  206. "configuration of stov. \nThe default value will be "
  207. "displayed in brackets.\n"
  208. "Please specify now :\n"))
  209. for value in self.__explanations:
  210. print(self.__explanations[value] + " [" + self.values[value] +
  211. "]:" +
  212. " ")
  213. if sys.version_info >= (3, 0):
  214. user_input = input()
  215. else:
  216. user_input = raw_input()
  217. if user_input != "":
  218. self.values[value] = user_input
  219. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  220. self.values["database"]
  221. def migrate_config(self):
  222. """Migrates the configuration from the old plain text config to
  223. the new and shiny json configuration file.
  224. """
  225. try:
  226. self.ReadOldConfig()
  227. self.WriteConfig()
  228. except stov_exceptions.ConfigFileReadErrorException:
  229. raise stov_exceptions.ConfigurationMigrationFailed()
  230. except stov_exceptions.ConfigFileWriteErrorException:
  231. raise stov_exceptions.ConfigurationMigrationFailed
  232. else:
  233. os.remove(str(os.environ['HOME']) + "/.stov/stov.config")