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.

303 lines
11 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env python2
  2. """Youtubedlg module to handle settings. """
  3. import json
  4. import os.path
  5. from .utils import check_path
  6. class OptionsManager(object):
  7. """Handles youtubedlg options.
  8. This class is responsible for storing and retrieving the options.
  9. Attributes:
  10. SETTINGS_FILENAME (string): Filename of the settings file.
  11. SENSITIVE_KEYS (tuple): Contains the keys that we don't want
  12. to store on the settings file. (SECURITY ISSUES).
  13. Args:
  14. config_path (string): Absolute path where OptionsManager
  15. should store the settings file.
  16. Note:
  17. See load_default() method for available options.
  18. Example:
  19. Access the options using the 'options' variable.
  20. opt_manager = OptionsManager('.')
  21. opt_manager.options['save_path'] = '~/Downloads'
  22. """
  23. SETTINGS_FILENAME = 'settings.json'
  24. SENSITIVE_KEYS = ('sudo_password', 'password', 'video_password')
  25. def __init__(self, config_path):
  26. self.config_path = config_path
  27. self.settings_file = os.path.join(config_path, self.SETTINGS_FILENAME)
  28. self.options = dict()
  29. self.load_default()
  30. self.load_from_file()
  31. def load_default(self):
  32. """Load the default options.
  33. Note:
  34. This method is automatically called by the constructor.
  35. Options Description:
  36. save_path (string): Path where youtube-dl should store the
  37. downloaded file. Default is $HOME.
  38. video_format (string): Video format to download.
  39. When this options is set to '0' youtube-dl will choose
  40. the best video format available for the given URL.
  41. second_video_format (string): Video format to mix with the first
  42. one (-f 18+17).
  43. to_audio (boolean): If True youtube-dl will post process the
  44. video file.
  45. keep_video (boolen): If True youtube-dl will keep the video file
  46. after post processing it.
  47. audio_format (string): Audio format of the post processed file.
  48. Available values are "mp3", "wav", "aac", "m4a", "vorbis".
  49. audio_quality (string): Audio quality of the post processed file.
  50. Available values are "9", "5", "0". The lowest the value the
  51. better the quality.
  52. restrict_filenames (boolean): If True youtube-dl will restrict
  53. the downloaded file filename to ASCII characters only.
  54. output_format (string): This option sets the downloaded file
  55. output template. Available values are 'id', 'title', 'custom'
  56. 'id' -> '%(id)s.%(ext)s'
  57. 'title' -> '%(title)s.%(ext)s'
  58. 'custom' -> Use 'output_template' as output template.
  59. output_template (string): Can be any output template supported
  60. by youtube-dl.
  61. playlist_start (int): Playlist index to start downloading.
  62. playlist_end (int): Playlist index to stop downloading.
  63. max_downloads (int): Maximum number of video files to download
  64. from the given playlist.
  65. min_filesize (float): Minimum file size of the video file.
  66. If the video file is smaller than the given size then
  67. youtube-dl will abort the download process.
  68. max_filesize (float): Maximum file size of the video file.
  69. If the video file is larger than the given size then
  70. youtube-dl will abort the download process.
  71. min_filesize_unit (string): Minimum file size unit.
  72. Available values: '', 'k', 'm', 'g', 'y', 'p', 'e', 'z', 'y'.
  73. max_filesize_unit (string): Maximum file size unit.
  74. See 'min_filesize_unit' option for available values.
  75. write_subs (boolean): If True youtube-dl will try to download
  76. the subtitles file for the given URL.
  77. write_all_subs (boolean): If True youtube-dl will try to download
  78. all the available subtitles files for the given URL.
  79. write_auto_subs (boolean): If True youtube-dl will try to download
  80. the automatic subtitles file for the given URL.
  81. embed_subs (boolean): If True youtube-dl will merge the subtitles
  82. file with the video. (ONLY mp4 files).
  83. subs_lang (string): Language of the subtitles file to download.
  84. Needs 'write_subs' option.
  85. ignore_errors (boolean): If True youtube-dl will ignore the errors
  86. and continue the download process.
  87. open_dl_dir (boolean): If True youtube-dlg will open the
  88. destination folder after download process has been completed.
  89. write_description (boolean): If True youtube-dl will write video
  90. description to a .description file.
  91. write_info (boolean): If True youtube-dl will write video
  92. metadata to a .info.json file.
  93. write_thumbnail (boolean): If True youtube-dl will write
  94. thumbnail image to disk.
  95. retries (int): Number of youtube-dl retries.
  96. user_agent (string): Specify a custom user agent for youtube-dl.
  97. referer (string): Specify a custom referer to use if the video
  98. access is restricted to one domain.
  99. proxy (string): Use the specified HTTP/HTTPS proxy.
  100. shutdown (boolean): If True youtube-dlg will turn the computer
  101. off after the download process has been completed.
  102. sudo_password (string): SUDO password for the shutdown process if
  103. the user does not have elevated privileges.
  104. username (string): Username to login with.
  105. password (string): Password to login with.
  106. video_password (string): Video password for the given URL.
  107. youtubedl_path (string): Absolute path to the youtube-dl binary.
  108. Default is the self.config_path. You can change this option
  109. to point on /usr/local/bin etc.. if you want to use the
  110. youtube-dl binary on your system. This is also the directory
  111. where youtube-dlg will auto download the youtube-dl if not
  112. exists so you should make sure you have write access if you
  113. want to update the youtube-dl binary from within youtube-dlg.
  114. cmd_args (string): String that contains extra youtube-dl options
  115. seperated by spaces.
  116. enable_log (boolean): If True youtube-dlg will enable
  117. the LogManager. See main() function under __init__().
  118. log_time (boolean): See logmanager.LogManager add_time attribute.
  119. """
  120. self.options = {
  121. 'save_path': os.path.expanduser('~'),
  122. 'video_format': '0',
  123. 'second_video_format': '0',
  124. 'to_audio': False,
  125. 'keep_video': False,
  126. 'audio_format': 'mp3',
  127. 'audio_quality': '5',
  128. 'restrict_filenames': False,
  129. 'output_format': 'title',
  130. 'output_template': '%(uploader)s/%(title)s.%(ext)s',
  131. 'playlist_start': 1,
  132. 'playlist_end': 0,
  133. 'max_downloads': 0,
  134. 'min_filesize': 0,
  135. 'max_filesize': 0,
  136. 'min_filesize_unit': '',
  137. 'max_filesize_unit': '',
  138. 'write_subs': False,
  139. 'write_all_subs': False,
  140. 'write_auto_subs': False,
  141. 'embed_subs': False,
  142. 'subs_lang': 'en',
  143. 'ignore_errors': True,
  144. 'open_dl_dir': True,
  145. 'write_description': False,
  146. 'write_info': False,
  147. 'write_thumbnail': False,
  148. 'retries': 10,
  149. 'user_agent': '',
  150. 'referer': '',
  151. 'proxy': '',
  152. 'shutdown': False,
  153. 'sudo_password': '',
  154. 'username': '',
  155. 'password': '',
  156. 'video_password': '',
  157. 'youtubedl_path': self.config_path,
  158. 'cmd_args': '',
  159. 'enable_log': True,
  160. 'log_time': False
  161. }
  162. def load_from_file(self):
  163. """Load options from settings file. """
  164. if not os.path.exists(self.settings_file):
  165. return
  166. with open(self.settings_file, 'rb') as settings_file:
  167. try:
  168. options = json.load(settings_file)
  169. except:
  170. self.load_default()
  171. if self._settings_are_valid(options):
  172. self.options = options
  173. def save_to_file(self):
  174. """Save options to settings file. """
  175. check_path(self.config_path)
  176. with open(self.settings_file, 'wb') as settings_file:
  177. options = self._get_options()
  178. json.dump(options,
  179. settings_file,
  180. indent=4,
  181. separators=(',', ': '))
  182. def _settings_are_valid(self, settings_dictionary):
  183. """Check settings.json dictionary.
  184. Args:
  185. settings_dictionary (dictionary): Options dictionary loaded
  186. from the settings file. See load_from_file() method.
  187. Returns:
  188. True if settings.json dictionary is valid, else False.
  189. """
  190. VALID_VIDEO_FORMAT = ('0', '17', '36', '5', '34', '35', '43', '44', '45',
  191. '46', '18', '22', '37', '38', '160', '133', '134', '135', '136','137',
  192. '264', '138', '242', '243', '244', '247', '248', '271', '272', '82',
  193. '83', '84', '85', '100', '101', '102', '139', '140', '141', '171', '172')
  194. VALID_AUDIO_FORMAT = ('mp3', 'wav', 'aac', 'm4a', 'vorbis')
  195. VALID_AUDIO_QUALITY = ('0', '5', '9')
  196. VALID_OUTPUT_FORMAT = ('title', 'id', 'custom')
  197. VALID_FILESIZE_UNIT = ('', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y')
  198. VALID_SUB_LANGUAGE = ('en', 'gr', 'pt', 'fr', 'it', 'ru', 'es', 'de')
  199. for key in self.options:
  200. if key not in settings_dictionary:
  201. return False
  202. # Check if each key has a valid value
  203. rules_dict = {
  204. 'video_format': VALID_VIDEO_FORMAT,
  205. 'second_video_format': VALID_VIDEO_FORMAT,
  206. 'audio_format': VALID_AUDIO_FORMAT,
  207. 'audio_quality': VALID_AUDIO_QUALITY,
  208. 'output_format': VALID_OUTPUT_FORMAT,
  209. 'min_filesize_unit': VALID_FILESIZE_UNIT,
  210. 'max_filesize_unit': VALID_FILESIZE_UNIT,
  211. 'subs_lang': VALID_SUB_LANGUAGE
  212. }
  213. for key, valid_list in rules_dict.items():
  214. if settings_dictionary[key] not in valid_list:
  215. return False
  216. return True
  217. def _get_options(self):
  218. """Return options dictionary without SENSITIVE_KEYS. """
  219. temp_options = self.options.copy()
  220. for key in self.SENSITIVE_KEYS:
  221. temp_options[key] = ''
  222. return temp_options