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.

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