You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

407 lines
15 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. """Youtubedlg module to handle settings. """
  4. from __future__ import unicode_literals
  5. import json
  6. import os.path
  7. from .utils import (
  8. os_path_expanduser,
  9. os_path_exists,
  10. encode_tuple,
  11. decode_tuple,
  12. check_path
  13. )
  14. from .formats import (
  15. OUTPUT_FORMATS,
  16. FORMATS
  17. )
  18. class OptionsManager(object):
  19. """Handles youtubedlg options.
  20. This class is responsible for storing and retrieving the options.
  21. Attributes:
  22. SETTINGS_FILENAME (string): Filename of the settings file.
  23. SENSITIVE_KEYS (tuple): Contains the keys that we don't want
  24. to store on the settings file. (SECURITY ISSUES).
  25. Args:
  26. config_path (string): Absolute path where OptionsManager
  27. should store the settings file.
  28. Note:
  29. See load_default() method for available options.
  30. Example:
  31. Access the options using the 'options' variable.
  32. opt_manager = OptionsManager('.')
  33. opt_manager.options['save_path'] = '~/Downloads'
  34. """
  35. SETTINGS_FILENAME = 'settings.json'
  36. SENSITIVE_KEYS = ('sudo_password', 'password', 'video_password')
  37. def __init__(self, config_path):
  38. self.config_path = config_path
  39. self.settings_file = os.path.join(config_path, self.SETTINGS_FILENAME)
  40. self.options = dict()
  41. self.load_default()
  42. self.load_from_file()
  43. def load_default(self):
  44. """Load the default options.
  45. Note:
  46. This method is automatically called by the constructor.
  47. Options Description:
  48. save_path (string): Path where youtube-dl should store the
  49. downloaded file. Default is $HOME.
  50. video_format (string): Video format to download.
  51. When this options is set to '0' youtube-dl will choose
  52. the best video format available for the given URL.
  53. second_video_format (string): Video format to mix with the first
  54. one (-f 18+17).
  55. to_audio (boolean): If True youtube-dl will post process the
  56. video file.
  57. keep_video (boolen): If True youtube-dl will keep the video file
  58. after post processing it.
  59. audio_format (string): Audio format of the post processed file.
  60. Available values are "mp3", "wav", "aac", "m4a", "vorbis",
  61. "opus" & "flac".
  62. audio_quality (string): Audio quality of the post processed file.
  63. Available values are "9", "5", "0". The lowest the value the
  64. better the quality.
  65. restrict_filenames (boolean): If True youtube-dl will restrict
  66. the downloaded file filename to ASCII characters only.
  67. output_format (int): This option sets the downloaded file
  68. output template. See formats.OUTPUT_FORMATS for more info.
  69. output_template (string): Can be any output template supported
  70. by youtube-dl.
  71. playlist_start (int): Playlist index to start downloading.
  72. playlist_end (int): Playlist index to stop downloading.
  73. max_downloads (int): Maximum number of video files to download
  74. from the given playlist.
  75. min_filesize (float): Minimum file size of the video file.
  76. If the video file is smaller than the given size then
  77. youtube-dl will abort the download process.
  78. max_filesize (float): Maximum file size of the video file.
  79. If the video file is larger than the given size then
  80. youtube-dl will abort the download process.
  81. min_filesize_unit (string): Minimum file size unit.
  82. Available values: '', 'k', 'm', 'g', 'y', 'p', 'e', 'z', 'y'.
  83. max_filesize_unit (string): Maximum file size unit.
  84. See 'min_filesize_unit' option for available values.
  85. write_subs (boolean): If True youtube-dl will try to download
  86. the subtitles file for the given URL.
  87. write_all_subs (boolean): If True youtube-dl will try to download
  88. all the available subtitles files for the given URL.
  89. write_auto_subs (boolean): If True youtube-dl will try to download
  90. the automatic subtitles file for the given URL.
  91. embed_subs (boolean): If True youtube-dl will merge the subtitles
  92. file with the video. (ONLY mp4 files).
  93. subs_lang (string): Language of the subtitles file to download.
  94. Needs 'write_subs' option.
  95. ignore_errors (boolean): If True youtube-dl will ignore the errors
  96. and continue the download process.
  97. open_dl_dir (boolean): If True youtube-dlg will open the
  98. destination folder after download process has been completed.
  99. write_description (boolean): If True youtube-dl will write video
  100. description to a .description file.
  101. write_info (boolean): If True youtube-dl will write video
  102. metadata to a .info.json file.
  103. write_thumbnail (boolean): If True youtube-dl will write
  104. thumbnail image to disk.
  105. retries (int): Number of youtube-dl retries.
  106. user_agent (string): Specify a custom user agent for youtube-dl.
  107. referer (string): Specify a custom referer to use if the video
  108. access is restricted to one domain.
  109. proxy (string): Use the specified HTTP/HTTPS proxy.
  110. shutdown (boolean): If True youtube-dlg will turn the computer
  111. off after the download process has been completed.
  112. sudo_password (string): SUDO password for the shutdown process if
  113. the user does not have elevated privileges.
  114. username (string): Username to login with.
  115. password (string): Password to login with.
  116. video_password (string): Video password for the given URL.
  117. youtubedl_path (string): Absolute path to the youtube-dl binary.
  118. Default is the self.config_path. You can change this option
  119. to point on /usr/local/bin etc.. if you want to use the
  120. youtube-dl binary on your system. This is also the directory
  121. where youtube-dlg will auto download the youtube-dl if not
  122. exists so you should make sure you have write access if you
  123. want to update the youtube-dl binary from within youtube-dlg.
  124. cmd_args (string): String that contains extra youtube-dl options
  125. seperated by spaces.
  126. enable_log (boolean): If True youtube-dlg will enable
  127. the LogManager. See main() function under __init__().
  128. log_time (boolean): See logmanager.LogManager add_time attribute.
  129. workers_number (int): Number of download workers that download manager
  130. will spawn. Must be greater than zero.
  131. locale_name (string): Locale name (e.g. ru_RU).
  132. main_win_size (tuple): Main window size (width, height).
  133. If window becomes to small the program will reset its size.
  134. See _settings_are_valid method MIN_FRAME_SIZE.
  135. opts_win_size (tuple): Options window size (width, height).
  136. If window becomes to small the program will reset its size.
  137. See _settings_are_valid method MIN_FRAME_SIZE.
  138. save_path_dirs (list): List that contains temporary save paths.
  139. selected_video_formats (list): List that contains the selected
  140. video formats to display on the main window.
  141. selected_audio_formats (list): List that contains the selected
  142. audio formats to display on the main window.
  143. selected_format (string): Current format selected on the main window.
  144. youtube_dl_debug (boolean): When True will pass '-v' flag to youtube-dl.
  145. ignore_config (boolean): When True will ignore youtube-dl config file options.
  146. confirm_exit (boolean): When True create popup to confirm exiting youtube-dl-gui.
  147. native_hls (boolean): When True youtube-dl will use the native HLS implementation.
  148. show_completion_popup (boolean): When True youtube-dl-gui will create a popup
  149. to inform the user for the download completion.
  150. confirm_deletion (boolean): When True ask user before item removal.
  151. nomtime (boolean): When True will not use the Last-modified header to
  152. set the file modification time.
  153. embed_thumbnail (boolean): When True will embed the thumbnail in
  154. the audio file as cover art.
  155. add_metadata (boolean): When True will write metadata to file.
  156. """
  157. #REFACTOR Remove old options & check options validation
  158. self.options = {
  159. 'save_path': os_path_expanduser('~'),
  160. 'save_path_dirs': [
  161. os_path_expanduser('~'),
  162. os.path.join(os_path_expanduser('~'), "Downloads"),
  163. os.path.join(os_path_expanduser('~'), "Desktop"),
  164. os.path.join(os_path_expanduser('~'), "Videos"),
  165. os.path.join(os_path_expanduser('~'), "Music"),
  166. ],
  167. 'video_format': '0',
  168. 'second_video_format': '0',
  169. 'to_audio': False,
  170. 'keep_video': False,
  171. 'audio_format': '',
  172. 'audio_quality': '5',
  173. 'restrict_filenames': False,
  174. 'output_format': 1,
  175. 'output_template': os.path.join('%(uploader)s', '%(title)s.%(ext)s'),
  176. 'playlist_start': 1,
  177. 'playlist_end': 0,
  178. 'max_downloads': 0,
  179. 'min_filesize': 0,
  180. 'max_filesize': 0,
  181. 'min_filesize_unit': '',
  182. 'max_filesize_unit': '',
  183. 'write_subs': False,
  184. 'write_all_subs': False,
  185. 'write_auto_subs': False,
  186. 'embed_subs': False,
  187. 'subs_lang': 'en',
  188. 'ignore_errors': True,
  189. 'open_dl_dir': False,
  190. 'write_description': False,
  191. 'write_info': False,
  192. 'write_thumbnail': False,
  193. 'retries': 10,
  194. 'user_agent': '',
  195. 'referer': '',
  196. 'proxy': '',
  197. 'shutdown': False,
  198. 'sudo_password': '',
  199. 'username': '',
  200. 'password': '',
  201. 'video_password': '',
  202. 'youtubedl_path': self.config_path,
  203. 'cmd_args': '',
  204. 'enable_log': True,
  205. 'log_time': True,
  206. 'workers_number': 3,
  207. 'locale_name': 'en_US',
  208. 'main_win_size': (740, 490),
  209. 'opts_win_size': (640, 490),
  210. 'selected_video_formats': ['webm', 'mp4'],
  211. 'selected_audio_formats': ['mp3', 'm4a', 'vorbis'],
  212. 'selected_format': '0',
  213. 'youtube_dl_debug': False,
  214. 'ignore_config': True,
  215. 'confirm_exit': True,
  216. 'native_hls': True,
  217. 'show_completion_popup': True,
  218. 'confirm_deletion': True,
  219. 'nomtime': False,
  220. 'embed_thumbnail': False,
  221. 'add_metadata': False
  222. }
  223. def load_from_file(self):
  224. """Load options from settings file. """
  225. if not os_path_exists(self.settings_file):
  226. return
  227. with open(self.settings_file, 'rb') as settings_file:
  228. try:
  229. options = json.load(settings_file)
  230. if self._settings_are_valid(options):
  231. self.options = options
  232. except:
  233. self.load_default()
  234. def save_to_file(self):
  235. """Save options to settings file. """
  236. check_path(self.config_path)
  237. with open(self.settings_file, 'wb') as settings_file:
  238. options = self._get_options()
  239. json.dump(options,
  240. settings_file,
  241. indent=4,
  242. separators=(',', ': '))
  243. def _settings_are_valid(self, settings_dictionary):
  244. """Check settings.json dictionary.
  245. Args:
  246. settings_dictionary (dict): Options dictionary loaded
  247. from the settings file. See load_from_file() method.
  248. Returns:
  249. True if settings.json dictionary is valid, else False.
  250. """
  251. VALID_VIDEO_FORMAT = ('0', '17', '36', '5', '34', '35', '43', '44', '45',
  252. '46', '18', '22', '37', '38', '160', '133', '134', '135', '136','137',
  253. '264', '138', '242', '243', '244', '247', '248', '271', '272', '82',
  254. '83', '84', '85', '100', '101', '102', '139', '140', '141', '171', '172')
  255. VALID_AUDIO_FORMAT = ('mp3', 'wav', 'aac', 'm4a', 'vorbis', 'opus', 'flac', '')
  256. VALID_AUDIO_QUALITY = ('0', '5', '9')
  257. VALID_FILESIZE_UNIT = ('', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y')
  258. VALID_SUB_LANGUAGE = ('en', 'el', 'pt', 'fr', 'it', 'ru', 'es', 'de', 'he', 'sv', 'tr')
  259. MIN_FRAME_SIZE = 100
  260. # Decode string formatted tuples back to normal tuples
  261. settings_dictionary['main_win_size'] = decode_tuple(settings_dictionary['main_win_size'])
  262. settings_dictionary['opts_win_size'] = decode_tuple(settings_dictionary['opts_win_size'])
  263. for key in self.options:
  264. if key not in settings_dictionary:
  265. return False
  266. if type(self.options[key]) != type(settings_dictionary[key]):
  267. return False
  268. # Check if each key has a valid value
  269. rules_dict = {
  270. 'video_format': FORMATS.keys(),
  271. 'second_video_format': VALID_VIDEO_FORMAT,
  272. 'audio_format': VALID_AUDIO_FORMAT,
  273. 'audio_quality': VALID_AUDIO_QUALITY,
  274. 'output_format': OUTPUT_FORMATS.keys(),
  275. 'min_filesize_unit': VALID_FILESIZE_UNIT,
  276. 'max_filesize_unit': VALID_FILESIZE_UNIT,
  277. 'subs_lang': VALID_SUB_LANGUAGE
  278. }
  279. for key, valid_list in rules_dict.items():
  280. if settings_dictionary[key] not in valid_list:
  281. return False
  282. # Check workers number value
  283. if settings_dictionary['workers_number'] < 1:
  284. return False
  285. # Check main-options frame size
  286. for size in settings_dictionary['main_win_size']:
  287. if size < MIN_FRAME_SIZE:
  288. return False
  289. for size in settings_dictionary['opts_win_size']:
  290. if size < MIN_FRAME_SIZE:
  291. return False
  292. return True
  293. def _get_options(self):
  294. """Return options dictionary without SENSITIVE_KEYS. """
  295. temp_options = self.options.copy()
  296. for key in self.SENSITIVE_KEYS:
  297. temp_options[key] = ''
  298. # Encode normal tuples to string formatted tuples
  299. temp_options['main_win_size'] = encode_tuple(temp_options['main_win_size'])
  300. temp_options['opts_win_size'] = encode_tuple(temp_options['opts_win_size'])
  301. return temp_options