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.

619 lines
27 KiB

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