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.

370 lines
13 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. """
  144. #TODO Remove old options & check options validation
  145. self.options = {
  146. 'save_path': os_path_expanduser('~'),
  147. 'save_path_dirs': [],
  148. 'video_format': '0',
  149. 'second_video_format': '0',
  150. 'to_audio': False,
  151. 'keep_video': False,
  152. 'audio_format': '',
  153. 'audio_quality': '5',
  154. 'restrict_filenames': False,
  155. 'output_format': 1,
  156. 'output_template': os.path.join('%(uploader)s', '%(title)s.%(ext)s'),
  157. 'playlist_start': 1,
  158. 'playlist_end': 0,
  159. 'max_downloads': 0,
  160. 'min_filesize': 0,
  161. 'max_filesize': 0,
  162. 'min_filesize_unit': '',
  163. 'max_filesize_unit': '',
  164. 'write_subs': False,
  165. 'write_all_subs': False,
  166. 'write_auto_subs': False,
  167. 'embed_subs': False,
  168. 'subs_lang': 'en',
  169. 'ignore_errors': True,
  170. 'open_dl_dir': False,
  171. 'write_description': False,
  172. 'write_info': False,
  173. 'write_thumbnail': False,
  174. 'retries': 10,
  175. 'user_agent': '',
  176. 'referer': '',
  177. 'proxy': '',
  178. 'shutdown': False,
  179. 'sudo_password': '',
  180. 'username': '',
  181. 'password': '',
  182. 'video_password': '',
  183. 'youtubedl_path': self.config_path,
  184. 'cmd_args': '',
  185. 'enable_log': True,
  186. 'log_time': True,
  187. 'workers_number': 3,
  188. 'locale_name': 'en_US',
  189. 'main_win_size': (710, 490),
  190. 'opts_win_size': (640, 470),
  191. 'selected_video_formats': ['webm', 'mp4'],
  192. 'selected_audio_formats': ['mp3', 'vorbis'],
  193. 'selected_format': '0'
  194. }
  195. def load_from_file(self):
  196. """Load options from settings file. """
  197. if not os_path_exists(self.settings_file):
  198. return
  199. with open(self.settings_file, 'rb') as settings_file:
  200. try:
  201. options = json.load(settings_file)
  202. if self._settings_are_valid(options):
  203. self.options = options
  204. except:
  205. self.load_default()
  206. def save_to_file(self):
  207. """Save options to settings file. """
  208. check_path(self.config_path)
  209. with open(self.settings_file, 'wb') as settings_file:
  210. options = self._get_options()
  211. json.dump(options,
  212. settings_file,
  213. indent=4,
  214. separators=(',', ': '))
  215. def _settings_are_valid(self, settings_dictionary):
  216. """Check settings.json dictionary.
  217. Args:
  218. settings_dictionary (dict): Options dictionary loaded
  219. from the settings file. See load_from_file() method.
  220. Returns:
  221. True if settings.json dictionary is valid, else False.
  222. """
  223. VALID_VIDEO_FORMAT = ('0', '17', '36', '5', '34', '35', '43', '44', '45',
  224. '46', '18', '22', '37', '38', '160', '133', '134', '135', '136','137',
  225. '264', '138', '242', '243', '244', '247', '248', '271', '272', '82',
  226. '83', '84', '85', '100', '101', '102', '139', '140', '141', '171', '172')
  227. VALID_AUDIO_FORMAT = ('mp3', 'wav', 'aac', 'm4a', 'vorbis', 'opus', '')
  228. VALID_AUDIO_QUALITY = ('0', '5', '9')
  229. VALID_FILESIZE_UNIT = ('', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y')
  230. VALID_SUB_LANGUAGE = ('en', 'gr', 'pt', 'fr', 'it', 'ru', 'es', 'de')
  231. MIN_FRAME_SIZE = 100
  232. # Decode string formatted tuples back to normal tuples
  233. settings_dictionary['main_win_size'] = decode_tuple(settings_dictionary['main_win_size'])
  234. settings_dictionary['opts_win_size'] = decode_tuple(settings_dictionary['opts_win_size'])
  235. for key in self.options:
  236. if key not in settings_dictionary:
  237. return False
  238. if type(self.options[key]) != type(settings_dictionary[key]):
  239. return False
  240. # Check if each key has a valid value
  241. rules_dict = {
  242. 'video_format': FORMATS.keys(),
  243. 'second_video_format': VALID_VIDEO_FORMAT,
  244. 'audio_format': VALID_AUDIO_FORMAT,
  245. 'audio_quality': VALID_AUDIO_QUALITY,
  246. 'output_format': OUTPUT_FORMATS.keys(),
  247. 'min_filesize_unit': VALID_FILESIZE_UNIT,
  248. 'max_filesize_unit': VALID_FILESIZE_UNIT,
  249. 'subs_lang': VALID_SUB_LANGUAGE
  250. }
  251. for key, valid_list in rules_dict.items():
  252. if settings_dictionary[key] not in valid_list:
  253. return False
  254. # Check workers number value
  255. if settings_dictionary['workers_number'] < 1:
  256. return False
  257. # Check main-options frame size
  258. for size in settings_dictionary['main_win_size']:
  259. if size < MIN_FRAME_SIZE:
  260. return False
  261. for size in settings_dictionary['opts_win_size']:
  262. if size < MIN_FRAME_SIZE:
  263. return False
  264. return True
  265. def _get_options(self):
  266. """Return options dictionary without SENSITIVE_KEYS. """
  267. temp_options = self.options.copy()
  268. for key in self.SENSITIVE_KEYS:
  269. temp_options[key] = ''
  270. # Encode normal tuples to string formatted tuples
  271. temp_options['main_win_size'] = encode_tuple(temp_options['main_win_size'])
  272. temp_options['opts_win_size'] = encode_tuple(temp_options['opts_win_size'])
  273. return temp_options