configuration.py 9.7 KB

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