1
0

configuration.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 assist(self):
  177. """ Ask the user to set all required configuration parameters """
  178. print(_("This assistant will help you to perform the initial "
  179. "configuration of stov. \nThe default value will be "
  180. "displayed in brackets.\n"
  181. "Please specify now :\n"))
  182. for value in self.__explanations:
  183. print(self.__explanations[value] + " [" + self.values[value] +
  184. "]:" +
  185. " ")
  186. user_input = input()
  187. if user_input != "":
  188. self.values[value] = user_input
  189. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  190. self.values["database"]
  191. def migrate_config(self):
  192. """Migrates the configuration from the old plain text config to
  193. the new and shiny json configuration file.
  194. """
  195. try:
  196. self.read_old_config()
  197. self.write_config()
  198. except stov_exceptions.ConfigFileReadErrorException:
  199. raise stov_exceptions.ConfigurationMigrationFailed()
  200. except stov_exceptions.ConfigFileWriteErrorException:
  201. raise stov_exceptions.ConfigurationMigrationFailed
  202. else:
  203. os.remove(str(os.environ['HOME']) + "/.stov/stov.config")
  204. def configure_logging(self, verbose=False, quiet=False):
  205. """
  206. Sets up logging for stov and returns a logger object
  207. :param verbose: whether to use verbose mode
  208. :type verbose: bool
  209. :param quiet: whether to use quiet mode
  210. :type quiet: bool
  211. :return: logger object
  212. :rtype: logging.Logger
  213. """
  214. logger = logging.getLogger("stov")
  215. # verbose takes precedence
  216. if verbose:
  217. logger.setLevel(logging.DEBUG)
  218. self.outputlevel = "verbose"
  219. elif quiet:
  220. logger.setLevel(logging.ERROR)
  221. self.outputlevel = "quiet"
  222. else:
  223. logger.setLevel(logging.INFO)
  224. console_handler = logging.StreamHandler()
  225. logger.addHandler(console_handler)
  226. return logger