configuration.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 subprocess
  21. import json
  22. import logging
  23. from lib_stov import stov_exceptions
  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. try:
  88. configfile = open(str(os.environ['HOME']) +
  89. "/.stov/stov.json", "w")
  90. except IOError:
  91. raise stov_exceptions.ConfigFileWriteErrorException()
  92. else:
  93. json.dump(self.values, configfile, indent=0)
  94. configfile.close()
  95. def initialize(self):
  96. """Creates the necessary directory for the stov configuration and
  97. calls the internal methods to create the database and the
  98. configuration file.
  99. """
  100. try:
  101. os.mkdir(str(os.environ['HOME']) + "/.stov", 0o750)
  102. except os.error:
  103. raise stov_exceptions.DirectoryCreationFailedException()
  104. else:
  105. process = subprocess.Popen(["which", "youtube-dl"],
  106. stdout=subprocess.PIPE)
  107. self.values["youtube-dl"] = \
  108. process.communicate()[0].strip().decode("utf-8")
  109. self.write_config()
  110. def read_old_config(self):
  111. """Reads the existing plain text configuration file and places the
  112. values in the dictionary. Existing values (such as default values)
  113. are overwritten.
  114. """
  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. try:
  132. configfile = open(str(os.environ['HOME']) + "/.stov/stov.json",
  133. "r")
  134. except IOError:
  135. raise stov_exceptions.ConfigFileReadErrorException()
  136. else:
  137. self.values.update(json.load(configfile))
  138. configfile.close()
  139. def check_config(self):
  140. """Checks if the configuration is up-to-date with the running
  141. stov version.
  142. """
  143. try:
  144. currentversion = int(self.values["config_version"])
  145. except ValueError:
  146. raise stov_exceptions.InvalidConfigurationVersionException()
  147. self.values["config_version"] = "0"
  148. self.read_config()
  149. if self.values["config_version"] == "0" \
  150. or int(self.values["config_version"]) < currentversion:
  151. self.values["config_version"] = str(currentversion)
  152. return False
  153. else:
  154. self.values["config_version"] = currentversion
  155. return True
  156. def update_config(self):
  157. """Update the configuration to the latest version"""
  158. versionbuffer = self.values["config_version"]
  159. self.read_config()
  160. self.values["config_version"] = versionbuffer
  161. self.write_config()
  162. def check_db(self):
  163. """Checks the database if it is up-to-date"""
  164. currentdbversion = int(self.values["db_version"])
  165. self.values["db_version"] = "0"
  166. self.read_config()
  167. if self.values["db_version"] == "0" or \
  168. int(self.values["db_version"]) <\
  169. int(currentdbversion):
  170. self.values["db_version"] = str(currentdbversion)
  171. return False
  172. else:
  173. self.values["db_version"] = str(currentdbversion)
  174. return True
  175. def get_youtube_parameter(self):
  176. """Determines which itag value results from codec and resolution
  177. settings and returns it
  178. """
  179. itag_value = 0
  180. if self.values["videocodec"] == "flv":
  181. if self.values["maxresolution"] == "240p":
  182. itag_value = 5
  183. elif self.values["maxresolution"] == "270p":
  184. itag_value = 6
  185. elif self.values["maxresolution"] == "360p":
  186. itag_value = 34
  187. elif self.values["maxresolution"] == "480p":
  188. itag_value = 35
  189. elif self.values["videocodec"] == "webm":
  190. if self.values["maxresolution"] == "360p":
  191. itag_value = 43
  192. elif self.values["maxresolution"] == "480p":
  193. itag_value = 44
  194. elif self.values["maxresolution"] == "720p":
  195. itag_value = 45
  196. elif self.values["maxresolution"] == "1080p":
  197. itag_value = 46
  198. elif self.values["videocodec"] == "mp4":
  199. if self.values["maxresolution"] == "360p":
  200. itag_value = 18
  201. elif self.values["maxresolution"] == "720p":
  202. itag_value = 22
  203. elif self.values["maxresolution"] == "1080p":
  204. itag_value = 37
  205. elif self.values["maxresolution"] == "3072p":
  206. itag_value = 38
  207. return itag_value
  208. def assist(self):
  209. """ Ask the user to set all required configuration parameters """
  210. print(_("This assistant will help you to perform the initial "
  211. "configuration of stov. \nThe default value will be "
  212. "displayed in brackets.\n"
  213. "Please specify now :\n"))
  214. for value in self.__explanations:
  215. print(self.__explanations[value] + " [" + self.values[value] +
  216. "]:" +
  217. " ")
  218. user_input = input()
  219. if user_input != "":
  220. self.values[value] = user_input
  221. self.dbpath = str(os.environ['HOME']) + "/.stov/" + \
  222. self.values["database"]
  223. def migrate_config(self):
  224. """Migrates the configuration from the old plain text config to
  225. the new and shiny json configuration file.
  226. """
  227. try:
  228. self.read_old_config()
  229. self.write_config()
  230. except stov_exceptions.ConfigFileReadErrorException:
  231. raise stov_exceptions.ConfigurationMigrationFailed()
  232. except stov_exceptions.ConfigFileWriteErrorException:
  233. raise stov_exceptions.ConfigurationMigrationFailed
  234. else:
  235. os.remove(str(os.environ['HOME']) + "/.stov/stov.config")
  236. def configure_logging(self, verbose=False, quiet=False):
  237. """
  238. Sets up logging for stov and returns a logger object
  239. :param verbose: whether to use verbose mode
  240. :type verbose: bool
  241. :param quiet: whether to use quiet mode
  242. :type quiet: bool
  243. :return: logger object
  244. :rtype: logging.Logger
  245. """
  246. logger = logging.getLogger("stov")
  247. # verbose takes precedence
  248. if verbose:
  249. logger.setLevel(logging.DEBUG)
  250. self.outputlevel = "verbose"
  251. elif quiet:
  252. logger.setLevel(logging.ERROR)
  253. self.outputlevel = "quiet"
  254. else:
  255. logger.setLevel(logging.INFO)
  256. console_handler = logging.StreamHandler()
  257. logger.addHandler(console_handler)
  258. return logger