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.

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