configuration.py 9.8 KB

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