configuration.py 9.7 KB

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