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.

601 lines
26 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import io
  5. import os
  6. import re
  7. import shutil
  8. import socket
  9. import sys
  10. import time
  11. import traceback
  12. from .utils import *
  13. from .extractor import get_info_extractor, gen_extractors
  14. from .FileDownloader import FileDownloader
  15. class YoutubeDL(object):
  16. """YoutubeDL class.
  17. YoutubeDL objects are the ones responsible of downloading the
  18. actual video file and writing it to disk if the user has requested
  19. it, among some other tasks. In most cases there should be one per
  20. program. As, given a video URL, the downloader doesn't know how to
  21. extract all the needed information, task that InfoExtractors do, it
  22. has to pass the URL to one of them.
  23. For this, YoutubeDL objects have a method that allows
  24. InfoExtractors to be registered in a given order. When it is passed
  25. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  26. finds that reports being able to handle it. The InfoExtractor extracts
  27. all the information about the video or videos the URL refers to, and
  28. YoutubeDL process the extracted information, possibly using a File
  29. Downloader to download the video.
  30. YoutubeDL objects accept a lot of parameters. In order not to saturate
  31. the object constructor with arguments, it receives a dictionary of
  32. options instead. These options are available through the params
  33. attribute for the InfoExtractors to use. The YoutubeDL also
  34. registers itself as the downloader in charge for the InfoExtractors
  35. that are added to it, so this is a "mutual registration".
  36. Available options:
  37. username: Username for authentication purposes.
  38. password: Password for authentication purposes.
  39. videopassword: Password for acces a video.
  40. usenetrc: Use netrc for authentication instead.
  41. verbose: Print additional info to stdout.
  42. quiet: Do not print messages to stdout.
  43. forceurl: Force printing final URL.
  44. forcetitle: Force printing title.
  45. forceid: Force printing ID.
  46. forcethumbnail: Force printing thumbnail URL.
  47. forcedescription: Force printing description.
  48. forcefilename: Force printing final filename.
  49. simulate: Do not download the video files.
  50. format: Video format code.
  51. format_limit: Highest quality format to try.
  52. outtmpl: Template for output names.
  53. restrictfilenames: Do not allow "&" and spaces in file names
  54. ignoreerrors: Do not stop on download errors.
  55. nooverwrites: Prevent overwriting files.
  56. playliststart: Playlist item to start at.
  57. playlistend: Playlist item to end at.
  58. matchtitle: Download only matching titles.
  59. rejecttitle: Reject downloads for matching titles.
  60. logtostderr: Log messages to stderr instead of stdout.
  61. writedescription: Write the video description to a .description file
  62. writeinfojson: Write the video description to a .info.json file
  63. writethumbnail: Write the thumbnail image to a file
  64. writesubtitles: Write the video subtitles to a file
  65. writeautomaticsub: Write the automatic subtitles to a file
  66. allsubtitles: Downloads all the subtitles of the video
  67. (requires writesubtitles or writeautomaticsub)
  68. listsubtitles: Lists all available subtitles for the video
  69. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  70. subtitleslangs: List of languages of the subtitles to download
  71. keepvideo: Keep the video file after post-processing
  72. daterange: A DateRange object, download only if the upload_date is in the range.
  73. skip_download: Skip the actual download of the video file
  74. The following parameters are not used by YoutubeDL itself, they are used by
  75. the FileDownloader:
  76. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  77. noresizebuffer, retries, continuedl, noprogress, consoletitle
  78. """
  79. params = None
  80. _ies = []
  81. _pps = []
  82. _download_retcode = None
  83. _num_downloads = None
  84. _screen_file = None
  85. def __init__(self, params):
  86. """Create a FileDownloader object with the given options."""
  87. self._ies = []
  88. self._ies_instances = {}
  89. self._pps = []
  90. self._progress_hooks = []
  91. self._download_retcode = 0
  92. self._num_downloads = 0
  93. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  94. self.params = params
  95. self.fd = FileDownloader(self, self.params)
  96. if '%(stitle)s' in self.params['outtmpl']:
  97. self.report_warning(u'%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  98. def add_info_extractor(self, ie):
  99. """Add an InfoExtractor object to the end of the list."""
  100. self._ies.append(ie)
  101. self._ies_instances[ie.ie_key()] = ie
  102. ie.set_downloader(self)
  103. def get_info_extractor(self, ie_key):
  104. """
  105. Get an instance of an IE with name ie_key, it will try to get one from
  106. the _ies list, if there's no instance it will create a new one and add
  107. it to the extractor list.
  108. """
  109. ie = self._ies_instances.get(ie_key)
  110. if ie is None:
  111. ie = get_info_extractor(ie_key)()
  112. self.add_info_extractor(ie)
  113. return ie
  114. def add_default_info_extractors(self):
  115. """
  116. Add the InfoExtractors returned by gen_extractors to the end of the list
  117. """
  118. for ie in gen_extractors():
  119. self.add_info_extractor(ie)
  120. def add_post_processor(self, pp):
  121. """Add a PostProcessor object to the end of the chain."""
  122. self._pps.append(pp)
  123. pp.set_downloader(self)
  124. def to_screen(self, message, skip_eol=False):
  125. """Print message to stdout if not in quiet mode."""
  126. if not self.params.get('quiet', False):
  127. terminator = [u'\n', u''][skip_eol]
  128. output = message + terminator
  129. write_string(output, self._screen_file)
  130. def to_stderr(self, message):
  131. """Print message to stderr."""
  132. assert type(message) == type(u'')
  133. output = message + u'\n'
  134. if 'b' in getattr(self._screen_file, 'mode', '') or sys.version_info[0] < 3: # Python 2 lies about the mode of sys.stdout/sys.stderr
  135. output = output.encode(preferredencoding())
  136. sys.stderr.write(output)
  137. def fixed_template(self):
  138. """Checks if the output template is fixed."""
  139. return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
  140. def trouble(self, message=None, tb=None):
  141. """Determine action to take when a download problem appears.
  142. Depending on if the downloader has been configured to ignore
  143. download errors or not, this method may throw an exception or
  144. not when errors are found, after printing the message.
  145. tb, if given, is additional traceback information.
  146. """
  147. if message is not None:
  148. self.to_stderr(message)
  149. if self.params.get('verbose'):
  150. if tb is None:
  151. if sys.exc_info()[0]: # if .trouble has been called from an except block
  152. tb = u''
  153. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  154. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  155. tb += compat_str(traceback.format_exc())
  156. else:
  157. tb_data = traceback.format_list(traceback.extract_stack())
  158. tb = u''.join(tb_data)
  159. self.to_stderr(tb)
  160. if not self.params.get('ignoreerrors', False):
  161. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  162. exc_info = sys.exc_info()[1].exc_info
  163. else:
  164. exc_info = sys.exc_info()
  165. raise DownloadError(message, exc_info)
  166. self._download_retcode = 1
  167. def report_warning(self, message):
  168. '''
  169. Print the message to stderr, it will be prefixed with 'WARNING:'
  170. If stderr is a tty file the 'WARNING:' will be colored
  171. '''
  172. if sys.stderr.isatty() and os.name != 'nt':
  173. _msg_header=u'\033[0;33mWARNING:\033[0m'
  174. else:
  175. _msg_header=u'WARNING:'
  176. warning_message=u'%s %s' % (_msg_header,message)
  177. self.to_stderr(warning_message)
  178. def report_error(self, message, tb=None):
  179. '''
  180. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  181. in red if stderr is a tty file.
  182. '''
  183. if sys.stderr.isatty() and os.name != 'nt':
  184. _msg_header = u'\033[0;31mERROR:\033[0m'
  185. else:
  186. _msg_header = u'ERROR:'
  187. error_message = u'%s %s' % (_msg_header, message)
  188. self.trouble(error_message, tb)
  189. def slow_down(self, start_time, byte_counter):
  190. """Sleep if the download speed is over the rate limit."""
  191. rate_limit = self.params.get('ratelimit', None)
  192. if rate_limit is None or byte_counter == 0:
  193. return
  194. now = time.time()
  195. elapsed = now - start_time
  196. if elapsed <= 0.0:
  197. return
  198. speed = float(byte_counter) / elapsed
  199. if speed > rate_limit:
  200. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  201. def report_writedescription(self, descfn):
  202. """ Report that the description file is being written """
  203. self.to_screen(u'[info] Writing video description to: ' + descfn)
  204. def report_writesubtitles(self, sub_filename):
  205. """ Report that the subtitles file is being written """
  206. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  207. def report_writeinfojson(self, infofn):
  208. """ Report that the metadata file has been written """
  209. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  210. def report_file_already_downloaded(self, file_name):
  211. """Report file has already been fully downloaded."""
  212. try:
  213. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  214. except (UnicodeEncodeError) as err:
  215. self.to_screen(u'[download] The file has already been downloaded')
  216. def increment_downloads(self):
  217. """Increment the ordinal that assigns a number to each file."""
  218. self._num_downloads += 1
  219. def prepare_filename(self, info_dict):
  220. """Generate the output filename."""
  221. try:
  222. template_dict = dict(info_dict)
  223. template_dict['epoch'] = int(time.time())
  224. autonumber_size = self.params.get('autonumber_size')
  225. if autonumber_size is None:
  226. autonumber_size = 5
  227. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  228. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  229. if template_dict['playlist_index'] is not None:
  230. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  231. sanitize = lambda k,v: sanitize_filename(
  232. u'NA' if v is None else compat_str(v),
  233. restricted=self.params.get('restrictfilenames'),
  234. is_id=(k==u'id'))
  235. template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
  236. filename = self.params['outtmpl'] % template_dict
  237. return filename
  238. except KeyError as err:
  239. self.report_error(u'Erroneous output template')
  240. return None
  241. except ValueError as err:
  242. self.report_error(u'Error in output template: ' + str(err) + u' (encoding: ' + repr(preferredencoding()) + ')')
  243. return None
  244. def _match_entry(self, info_dict):
  245. """ Returns None iff the file should be downloaded """
  246. title = info_dict['title']
  247. matchtitle = self.params.get('matchtitle', False)
  248. if matchtitle:
  249. if not re.search(matchtitle, title, re.IGNORECASE):
  250. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  251. rejecttitle = self.params.get('rejecttitle', False)
  252. if rejecttitle:
  253. if re.search(rejecttitle, title, re.IGNORECASE):
  254. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  255. date = info_dict.get('upload_date', None)
  256. if date is not None:
  257. dateRange = self.params.get('daterange', DateRange())
  258. if date not in dateRange:
  259. return u'[download] %s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  260. return None
  261. def extract_info(self, url, download=True, ie_key=None, extra_info={}):
  262. '''
  263. Returns a list with a dictionary for each video we find.
  264. If 'download', also downloads the videos.
  265. extra_info is a dict containing the extra values to add to each result
  266. '''
  267. if ie_key:
  268. ies = [self.get_info_extractor(ie_key)]
  269. else:
  270. ies = self._ies
  271. for ie in ies:
  272. if not ie.suitable(url):
  273. continue
  274. if not ie.working():
  275. self.report_warning(u'The program functionality for this site has been marked as broken, '
  276. u'and will probably not work.')
  277. try:
  278. ie_result = ie.extract(url)
  279. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  280. break
  281. if isinstance(ie_result, list):
  282. # Backwards compatibility: old IE result format
  283. for result in ie_result:
  284. result.update(extra_info)
  285. ie_result = {
  286. '_type': 'compat_list',
  287. 'entries': ie_result,
  288. }
  289. else:
  290. ie_result.update(extra_info)
  291. if 'extractor' not in ie_result:
  292. ie_result['extractor'] = ie.IE_NAME
  293. return self.process_ie_result(ie_result, download=download)
  294. except ExtractorError as de: # An error we somewhat expected
  295. self.report_error(compat_str(de), de.format_traceback())
  296. break
  297. except Exception as e:
  298. if self.params.get('ignoreerrors', False):
  299. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  300. break
  301. else:
  302. raise
  303. else:
  304. self.report_error(u'no suitable InfoExtractor: %s' % url)
  305. def process_ie_result(self, ie_result, download=True, extra_info={}):
  306. """
  307. Take the result of the ie(may be modified) and resolve all unresolved
  308. references (URLs, playlist items).
  309. It will also download the videos if 'download'.
  310. Returns the resolved ie_result.
  311. """
  312. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  313. if result_type == 'video':
  314. ie_result.update(extra_info)
  315. if 'playlist' not in ie_result:
  316. # It isn't part of a playlist
  317. ie_result['playlist'] = None
  318. ie_result['playlist_index'] = None
  319. if download:
  320. self.process_info(ie_result)
  321. return ie_result
  322. elif result_type == 'url':
  323. # We have to add extra_info to the results because it may be
  324. # contained in a playlist
  325. return self.extract_info(ie_result['url'],
  326. download,
  327. ie_key=ie_result.get('ie_key'),
  328. extra_info=extra_info)
  329. elif result_type == 'playlist':
  330. # We process each entry in the playlist
  331. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  332. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  333. playlist_results = []
  334. n_all_entries = len(ie_result['entries'])
  335. playliststart = self.params.get('playliststart', 1) - 1
  336. playlistend = self.params.get('playlistend', -1)
  337. if playlistend == -1:
  338. entries = ie_result['entries'][playliststart:]
  339. else:
  340. entries = ie_result['entries'][playliststart:playlistend]
  341. n_entries = len(entries)
  342. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  343. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  344. for i,entry in enumerate(entries,1):
  345. self.to_screen(u'[download] Downloading video #%s of %s' %(i, n_entries))
  346. extra = {
  347. 'playlist': playlist,
  348. 'playlist_index': i + playliststart,
  349. }
  350. if not 'extractor' in entry:
  351. # We set the extractor, if it's an url it will be set then to
  352. # the new extractor, but if it's already a video we must make
  353. # sure it's present: see issue #877
  354. entry['extractor'] = ie_result['extractor']
  355. entry_result = self.process_ie_result(entry,
  356. download=download,
  357. extra_info=extra)
  358. playlist_results.append(entry_result)
  359. ie_result['entries'] = playlist_results
  360. return ie_result
  361. elif result_type == 'compat_list':
  362. def _fixup(r):
  363. r.setdefault('extractor', ie_result['extractor'])
  364. return r
  365. ie_result['entries'] = [
  366. self.process_ie_result(_fixup(r), download=download)
  367. for r in ie_result['entries']
  368. ]
  369. return ie_result
  370. else:
  371. raise Exception('Invalid result type: %s' % result_type)
  372. def process_info(self, info_dict):
  373. """Process a single resolved IE result."""
  374. assert info_dict.get('_type', 'video') == 'video'
  375. #We increment the download the download count here to match the previous behaviour.
  376. self.increment_downloads()
  377. info_dict['fulltitle'] = info_dict['title']
  378. if len(info_dict['title']) > 200:
  379. info_dict['title'] = info_dict['title'][:197] + u'...'
  380. # Keep for backwards compatibility
  381. info_dict['stitle'] = info_dict['title']
  382. if not 'format' in info_dict:
  383. info_dict['format'] = info_dict['ext']
  384. reason = self._match_entry(info_dict)
  385. if reason is not None:
  386. self.to_screen(u'[download] ' + reason)
  387. return
  388. max_downloads = self.params.get('max_downloads')
  389. if max_downloads is not None:
  390. if self._num_downloads > int(max_downloads):
  391. raise MaxDownloadsReached()
  392. filename = self.prepare_filename(info_dict)
  393. # Forced printings
  394. if self.params.get('forcetitle', False):
  395. compat_print(info_dict['title'])
  396. if self.params.get('forceid', False):
  397. compat_print(info_dict['id'])
  398. if self.params.get('forceurl', False):
  399. # For RTMP URLs, also include the playpath
  400. compat_print(info_dict['url'] + info_dict.get('play_path', u''))
  401. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  402. compat_print(info_dict['thumbnail'])
  403. if self.params.get('forcedescription', False) and 'description' in info_dict:
  404. compat_print(info_dict['description'])
  405. if self.params.get('forcefilename', False) and filename is not None:
  406. compat_print(filename)
  407. if self.params.get('forceformat', False):
  408. compat_print(info_dict['format'])
  409. # Do nothing else if in simulate mode
  410. if self.params.get('simulate', False):
  411. return
  412. if filename is None:
  413. return
  414. try:
  415. dn = os.path.dirname(encodeFilename(filename))
  416. if dn != '' and not os.path.exists(dn):
  417. os.makedirs(dn)
  418. except (OSError, IOError) as err:
  419. self.report_error(u'unable to create directory ' + compat_str(err))
  420. return
  421. if self.params.get('writedescription', False):
  422. try:
  423. descfn = filename + u'.description'
  424. self.report_writedescription(descfn)
  425. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  426. descfile.write(info_dict['description'])
  427. except (KeyError, TypeError):
  428. self.report_warning(u'There\'s no description to write.')
  429. except (OSError, IOError):
  430. self.report_error(u'Cannot write description file ' + descfn)
  431. return
  432. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  433. self.params.get('writeautomaticsub')])
  434. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  435. # subtitles download errors are already managed as troubles in relevant IE
  436. # that way it will silently go on when used with unsupporting IE
  437. subtitles = info_dict['subtitles']
  438. sub_format = self.params.get('subtitlesformat')
  439. for sub_lang in subtitles.keys():
  440. sub = subtitles[sub_lang]
  441. if sub is None:
  442. continue
  443. try:
  444. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  445. self.report_writesubtitles(sub_filename)
  446. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  447. subfile.write(sub)
  448. except (OSError, IOError):
  449. self.report_error(u'Cannot write subtitles file ' + descfn)
  450. return
  451. if self.params.get('writeinfojson', False):
  452. infofn = filename + u'.info.json'
  453. self.report_writeinfojson(infofn)
  454. try:
  455. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  456. write_json_file(json_info_dict, encodeFilename(infofn))
  457. except (OSError, IOError):
  458. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  459. return
  460. if self.params.get('writethumbnail', False):
  461. if info_dict.get('thumbnail') is not None:
  462. thumb_format = determine_ext(info_dict['thumbnail'], u'jpg')
  463. thumb_filename = filename.rpartition('.')[0] + u'.' + thumb_format
  464. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  465. (info_dict['extractor'], info_dict['id']))
  466. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  467. with open(thumb_filename, 'wb') as thumbf:
  468. shutil.copyfileobj(uf, thumbf)
  469. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  470. (info_dict['extractor'], info_dict['id'], thumb_filename))
  471. if not self.params.get('skip_download', False):
  472. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  473. success = True
  474. else:
  475. try:
  476. success = self.fd._do_download(filename, info_dict)
  477. except (OSError, IOError) as err:
  478. raise UnavailableVideoError(err)
  479. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  480. self.report_error(u'unable to download video data: %s' % str(err))
  481. return
  482. except (ContentTooShortError, ) as err:
  483. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  484. return
  485. if success:
  486. try:
  487. self.post_process(filename, info_dict)
  488. except (PostProcessingError) as err:
  489. self.report_error(u'postprocessing: %s' % str(err))
  490. return
  491. def download(self, url_list):
  492. """Download a given list of URLs."""
  493. if len(url_list) > 1 and self.fixed_template():
  494. raise SameFileError(self.params['outtmpl'])
  495. for url in url_list:
  496. try:
  497. #It also downloads the videos
  498. videos = self.extract_info(url)
  499. except UnavailableVideoError:
  500. self.report_error(u'unable to download video')
  501. except MaxDownloadsReached:
  502. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  503. raise
  504. return self._download_retcode
  505. def post_process(self, filename, ie_info):
  506. """Run all the postprocessors on the given file."""
  507. info = dict(ie_info)
  508. info['filepath'] = filename
  509. keep_video = None
  510. for pp in self._pps:
  511. try:
  512. keep_video_wish,new_info = pp.run(info)
  513. if keep_video_wish is not None:
  514. if keep_video_wish:
  515. keep_video = keep_video_wish
  516. elif keep_video is None:
  517. # No clear decision yet, let IE decide
  518. keep_video = keep_video_wish
  519. except PostProcessingError as e:
  520. self.report_error(e.msg)
  521. if keep_video is False and not self.params.get('keepvideo', False):
  522. try:
  523. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  524. os.remove(encodeFilename(filename))
  525. except (IOError, OSError):
  526. self.report_warning(u'Unable to remove downloaded video file')