configuration.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. # This file is part of stov, written by Helmut Pozimski 2012-2017.
  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 json
  21. import logging
  22. from lib_stov import stov_exceptions
  23. LOGGER = logging.getLogger("stov")
  24. class Conf(object):
  25. """This class is used to create the object which is responsible for all
  26. configuration operations.
  27. """
  28. def __init__(self):
  29. """Constructor
  30. Constructs the conf object with some reasonable default values which
  31. should work on most systems, existence of a local mail server is
  32. assumed.
  33. """
  34. self.values = {
  35. "database": "stov.sqlite",
  36. "downloaddir": str(os.environ['HOME']) + "/stov",
  37. "maxvideos": "25",
  38. "mailhost": "localhost",
  39. "mailto": "root",
  40. "mailfrom": "stov@localhost",
  41. "smtpport": "25",
  42. "auth_needed": "no",
  43. "user_name": "",
  44. "password": "",
  45. "youtube-dl": "",
  46. "notify": "yes",
  47. "config_version": "9",
  48. "db_version": "6",
  49. "videocodec": "mp4",
  50. "maxresolution": "1080p",
  51. "maxfails": 50,
  52. "check_title": "no"
  53. }
  54. self.__explanations = {
  55. "database": _("the name of your database file"),
  56. "downloaddir": _("the directory where downloaded videos are "
  57. "saved"),
  58. "maxvideos": _("the maximum number of videos to retrieve for each "
  59. "subscription"),
  60. "mailhost": _("the host name of your mail server"),
  61. "mailto": _("the address used for notifications"),
  62. "mailfrom": _("the sender address of notification e-mails"),
  63. "smtpport": _("the port to use on your mail server"),
  64. "auth_needed": _("if your mail server requires authentication"),
  65. "user_name": _("the user name used to authenticate to your mail "
  66. "server"),
  67. "password": _("the password used to authenticate to your mail "
  68. "server"),
  69. "youtube-dl": _("the path to your youtube-dl installation"),
  70. "notify": _("if you want to be notified via e-mail about new "
  71. "videos"),
  72. "videocodec": _("which video codec you prefer (h264, webm or "
  73. "flv)"),
  74. "maxresolution": _("which resolution you prefer (360p, 480p, 720p "
  75. "or 1080p)"),
  76. "check_title": _("if you want to compare the title of a video "
  77. "with the subscription search string")
  78. }
  79. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  80. self.values["database"]
  81. self.outputlevel = "default"
  82. def write_config(self):
  83. """Writes the configuration from the dictionary into the configuration
  84. file for stov. The configuration is written into the home directory of
  85. the user by default.
  86. """
  87. LOGGER.debug(_("Writing configuration file."))
  88. try:
  89. configfile = open(str(os.environ['HOME']) +
  90. "/.stov/stov.json", "w")
  91. except IOError:
  92. raise stov_exceptions.ConfigFileWriteErrorException()
  93. else:
  94. json.dump(self.values, configfile, indent=0)
  95. configfile.close()
  96. def initialize(self):
  97. """Creates the necessary directory for the stov configuration and
  98. calls the internal methods to create the database and the
  99. configuration file.
  100. """
  101. LOGGER.debug(_("Creating stov configuration directory"))
  102. try:
  103. os.mkdir(str(os.environ['HOME']) + "/.stov", 0o750)
  104. except os.error:
  105. raise stov_exceptions.DirectoryCreationFailedException()
  106. else:
  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. LOGGER.debug(_("Opening old configuration file to convert it to "
  114. "json"))
  115. try:
  116. configfile = open(str(os.environ['HOME']) +
  117. "/.stov/stov.config", "r")
  118. except IOError:
  119. raise stov_exceptions.ConfigFileReadErrorException()
  120. for lines in configfile:
  121. tmpline = lines.strip()
  122. tmplist = tmpline.split("=")
  123. self.values[tmplist[0].lower()] = tmplist[1]
  124. configfile.close()
  125. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  126. self.values["database"]
  127. def read_config(self):
  128. """Reads the existing json configuration files and loads the values in
  129. the dictionary.
  130. """
  131. LOGGER.debug(_("Opening configuration file"))
  132. try:
  133. configfile = open(str(os.environ['HOME']) + "/.stov/stov.json",
  134. "r")
  135. except IOError:
  136. raise stov_exceptions.ConfigFileReadErrorException()
  137. else:
  138. self.values.update(json.load(configfile))
  139. configfile.close()
  140. def check_config(self):
  141. """Checks if the configuration is up-to-date with the running
  142. stov version.
  143. """
  144. try:
  145. current_version = int(self.values["config_version"])
  146. except ValueError:
  147. raise stov_exceptions.InvalidConfigurationVersionException()
  148. self.values["config_version"] = "0"
  149. self.read_config()
  150. if self.values["config_version"] == "0" \
  151. or int(self.values["config_version"]) < current_version:
  152. self.values["config_version"] = str(current_version)
  153. return False
  154. else:
  155. self.values["config_version"] = current_version
  156. return True
  157. def update_config(self):
  158. """Update the configuration to the latest version"""
  159. version_buffer = self.values["config_version"]
  160. self.read_config()
  161. self.values["config_version"] = version_buffer
  162. self.write_config()
  163. def check_db(self):
  164. """Checks the database if it is up-to-date"""
  165. currentdbversion = int(self.values["db_version"])
  166. self.values["db_version"] = "0"
  167. self.read_config()
  168. if self.values["db_version"] == "0" or \
  169. int(self.values["db_version"]) <\
  170. int(currentdbversion):
  171. self.values["db_version"] = str(currentdbversion)
  172. return False
  173. else:
  174. self.values["db_version"] = str(currentdbversion)
  175. return True
  176. def get_youtube_parameter(self):
  177. """Determines which itag value results from codec and resolution
  178. settings and returns it
  179. """
  180. itag_value = 0
  181. if self.values["videocodec"] == "flv":
  182. if self.values["maxresolution"] == "240p":
  183. itag_value = 5
  184. elif self.values["maxresolution"] == "270p":
  185. itag_value = 6
  186. elif self.values["maxresolution"] == "360p":
  187. itag_value = 34
  188. elif self.values["maxresolution"] == "480p":
  189. itag_value = 35
  190. elif self.values["videocodec"] == "webm":
  191. if self.values["maxresolution"] == "360p":
  192. itag_value = 43
  193. elif self.values["maxresolution"] == "480p":
  194. itag_value = 44
  195. elif self.values["maxresolution"] == "720p":
  196. itag_value = 45
  197. elif self.values["maxresolution"] == "1080p":
  198. itag_value = 46
  199. elif self.values["videocodec"] == "mp4":
  200. if self.values["maxresolution"] == "360p":
  201. itag_value = 18
  202. elif self.values["maxresolution"] == "720p":
  203. itag_value = 22
  204. elif self.values["maxresolution"] == "1080p":
  205. itag_value = 37
  206. elif self.values["maxresolution"] == "3072p":
  207. itag_value = 38
  208. if itag_value:
  209. return itag_value
  210. else:
  211. LOGGER.debug(_("Could not determine an itag value "
  212. "from the configuration"))
  213. return 38
  214. def assist(self):
  215. """ Ask the user to set all required configuration parameters """
  216. print(_("This assistant will help you to perform the initial "
  217. "configuration of stov. \nThe default value will be "
  218. "displayed in brackets.\n"
  219. "Please specify now :\n"))
  220. for value in self.__explanations:
  221. print(self.__explanations[value] + " [" + self.values[value] +
  222. "]:" +
  223. " ")
  224. user_input = input()
  225. if user_input != "":
  226. self.values[value] = user_input
  227. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  228. self.values["database"]
  229. def migrate_config(self):
  230. """Migrates the configuration from the old plain text config to
  231. the new and shiny json configuration file.
  232. """
  233. try:
  234. self.read_old_config()
  235. self.write_config()
  236. except stov_exceptions.ConfigFileReadErrorException:
  237. raise stov_exceptions.ConfigurationMigrationFailed()
  238. except stov_exceptions.ConfigFileWriteErrorException:
  239. raise stov_exceptions.ConfigurationMigrationFailed
  240. else:
  241. os.remove(str(os.environ['HOME']) + "/.stov/stov.config")
  242. def configure_logging(self, verbose=False, quiet=False):
  243. """
  244. Sets up logging for stov and returns a logger object
  245. :param verbose: whether to use verbose mode
  246. :type verbose: bool
  247. :param quiet: whether to use quiet mode
  248. :type quiet: bool
  249. :return: logger object
  250. :rtype: logging.Logger
  251. """
  252. logger = logging.getLogger("stov")
  253. # verbose takes precedence
  254. if verbose:
  255. logger.setLevel(logging.DEBUG)
  256. self.outputlevel = "verbose"
  257. elif quiet:
  258. logger.setLevel(logging.ERROR)
  259. self.outputlevel = "quiet"
  260. else:
  261. logger.setLevel(logging.INFO)
  262. console_handler = logging.StreamHandler()
  263. logger.addHandler(console_handler)
  264. return logger