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.

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