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.

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