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.

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