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.

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