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.

748 lines
32 KiB

11 years ago
11 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import errno
  5. import io
  6. import os
  7. import re
  8. import shutil
  9. import socket
  10. import sys
  11. import time
  12. import traceback
  13. from .utils import *
  14. from .extractor import get_info_extractor, gen_extractors
  15. from .FileDownloader import FileDownloader
  16. class YoutubeDL(object):
  17. """YoutubeDL class.
  18. YoutubeDL objects are the ones responsible of downloading the
  19. actual video file and writing it to disk if the user has requested
  20. it, among some other tasks. In most cases there should be one per
  21. program. As, given a video URL, the downloader doesn't know how to
  22. extract all the needed information, task that InfoExtractors do, it
  23. has to pass the URL to one of them.
  24. For this, YoutubeDL objects have a method that allows
  25. InfoExtractors to be registered in a given order. When it is passed
  26. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  27. finds that reports being able to handle it. The InfoExtractor extracts
  28. all the information about the video or videos the URL refers to, and
  29. YoutubeDL process the extracted information, possibly using a File
  30. Downloader to download the video.
  31. YoutubeDL objects accept a lot of parameters. In order not to saturate
  32. the object constructor with arguments, it receives a dictionary of
  33. options instead. These options are available through the params
  34. attribute for the InfoExtractors to use. The YoutubeDL also
  35. registers itself as the downloader in charge for the InfoExtractors
  36. that are added to it, so this is a "mutual registration".
  37. Available options:
  38. username: Username for authentication purposes.
  39. password: Password for authentication purposes.
  40. videopassword: Password for acces a video.
  41. usenetrc: Use netrc for authentication instead.
  42. verbose: Print additional info to stdout.
  43. quiet: Do not print messages to stdout.
  44. forceurl: Force printing final URL.
  45. forcetitle: Force printing title.
  46. forceid: Force printing ID.
  47. forcethumbnail: Force printing thumbnail URL.
  48. forcedescription: Force printing description.
  49. forcefilename: Force printing final filename.
  50. simulate: Do not download the video files.
  51. format: Video format code.
  52. format_limit: Highest quality format to try.
  53. outtmpl: Template for output names.
  54. restrictfilenames: Do not allow "&" and spaces in file names
  55. ignoreerrors: Do not stop on download errors.
  56. nooverwrites: Prevent overwriting files.
  57. playliststart: Playlist item to start at.
  58. playlistend: Playlist item to end at.
  59. matchtitle: Download only matching titles.
  60. rejecttitle: Reject downloads for matching titles.
  61. logtostderr: Log messages to stderr instead of stdout.
  62. writedescription: Write the video description to a .description file
  63. writeinfojson: Write the video description to a .info.json file
  64. writethumbnail: Write the thumbnail image to a file
  65. writesubtitles: Write the video subtitles to a file
  66. writeautomaticsub: Write the automatic subtitles to a file
  67. allsubtitles: Downloads all the subtitles of the video
  68. (requires writesubtitles or writeautomaticsub)
  69. listsubtitles: Lists all available subtitles for the video
  70. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  71. subtitleslangs: List of languages of the subtitles to download
  72. keepvideo: Keep the video file after post-processing
  73. daterange: A DateRange object, download only if the upload_date is in the range.
  74. skip_download: Skip the actual download of the video file
  75. cachedir: Location of the cache files in the filesystem.
  76. None to disable filesystem cache.
  77. noplaylist: Download single video instead of a playlist if in doubt.
  78. age_limit: An integer representing the user's age in years.
  79. Unsuitable videos for the given age are skipped.
  80. downloadarchive: File name of a file where all downloads are recorded.
  81. Videos already present in the file are not downloaded
  82. again.
  83. The following parameters are not used by YoutubeDL itself, they are used by
  84. the FileDownloader:
  85. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  86. noresizebuffer, retries, continuedl, noprogress, consoletitle
  87. """
  88. params = None
  89. _ies = []
  90. _pps = []
  91. _download_retcode = None
  92. _num_downloads = None
  93. _screen_file = None
  94. def __init__(self, params):
  95. """Create a FileDownloader object with the given options."""
  96. self._ies = []
  97. self._ies_instances = {}
  98. self._pps = []
  99. self._progress_hooks = []
  100. self._download_retcode = 0
  101. self._num_downloads = 0
  102. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  103. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  104. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  105. and not params['restrictfilenames']):
  106. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  107. self.report_warning(
  108. u'Assuming --restrict-filenames since file system encoding '
  109. u'cannot encode all charactes. '
  110. u'Set the LC_ALL environment variable to fix this.')
  111. params['restrictfilenames'] = True
  112. self.params = params
  113. self.fd = FileDownloader(self, self.params)
  114. if '%(stitle)s' in self.params['outtmpl']:
  115. 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.')
  116. def add_info_extractor(self, ie):
  117. """Add an InfoExtractor object to the end of the list."""
  118. self._ies.append(ie)
  119. self._ies_instances[ie.ie_key()] = ie
  120. ie.set_downloader(self)
  121. def get_info_extractor(self, ie_key):
  122. """
  123. Get an instance of an IE with name ie_key, it will try to get one from
  124. the _ies list, if there's no instance it will create a new one and add
  125. it to the extractor list.
  126. """
  127. ie = self._ies_instances.get(ie_key)
  128. if ie is None:
  129. ie = get_info_extractor(ie_key)()
  130. self.add_info_extractor(ie)
  131. return ie
  132. def add_default_info_extractors(self):
  133. """
  134. Add the InfoExtractors returned by gen_extractors to the end of the list
  135. """
  136. for ie in gen_extractors():
  137. self.add_info_extractor(ie)
  138. def add_post_processor(self, pp):
  139. """Add a PostProcessor object to the end of the chain."""
  140. self._pps.append(pp)
  141. pp.set_downloader(self)
  142. def to_screen(self, message, skip_eol=False):
  143. """Print message to stdout if not in quiet mode."""
  144. if not self.params.get('quiet', False):
  145. terminator = [u'\n', u''][skip_eol]
  146. output = message + terminator
  147. write_string(output, self._screen_file)
  148. def to_stderr(self, message):
  149. """Print message to stderr."""
  150. assert type(message) == type(u'')
  151. output = message + u'\n'
  152. 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
  153. output = output.encode(preferredencoding())
  154. sys.stderr.write(output)
  155. def fixed_template(self):
  156. """Checks if the output template is fixed."""
  157. return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
  158. def trouble(self, message=None, tb=None):
  159. """Determine action to take when a download problem appears.
  160. Depending on if the downloader has been configured to ignore
  161. download errors or not, this method may throw an exception or
  162. not when errors are found, after printing the message.
  163. tb, if given, is additional traceback information.
  164. """
  165. if message is not None:
  166. self.to_stderr(message)
  167. if self.params.get('verbose'):
  168. if tb is None:
  169. if sys.exc_info()[0]: # if .trouble has been called from an except block
  170. tb = u''
  171. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  172. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  173. tb += compat_str(traceback.format_exc())
  174. else:
  175. tb_data = traceback.format_list(traceback.extract_stack())
  176. tb = u''.join(tb_data)
  177. self.to_stderr(tb)
  178. if not self.params.get('ignoreerrors', False):
  179. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  180. exc_info = sys.exc_info()[1].exc_info
  181. else:
  182. exc_info = sys.exc_info()
  183. raise DownloadError(message, exc_info)
  184. self._download_retcode = 1
  185. def report_warning(self, message):
  186. '''
  187. Print the message to stderr, it will be prefixed with 'WARNING:'
  188. If stderr is a tty file the 'WARNING:' will be colored
  189. '''
  190. if sys.stderr.isatty() and os.name != 'nt':
  191. _msg_header=u'\033[0;33mWARNING:\033[0m'
  192. else:
  193. _msg_header=u'WARNING:'
  194. warning_message=u'%s %s' % (_msg_header,message)
  195. self.to_stderr(warning_message)
  196. def report_error(self, message, tb=None):
  197. '''
  198. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  199. in red if stderr is a tty file.
  200. '''
  201. if sys.stderr.isatty() and os.name != 'nt':
  202. _msg_header = u'\033[0;31mERROR:\033[0m'
  203. else:
  204. _msg_header = u'ERROR:'
  205. error_message = u'%s %s' % (_msg_header, message)
  206. self.trouble(error_message, tb)
  207. def slow_down(self, start_time, byte_counter):
  208. """Sleep if the download speed is over the rate limit."""
  209. rate_limit = self.params.get('ratelimit', None)
  210. if rate_limit is None or byte_counter == 0:
  211. return
  212. now = time.time()
  213. elapsed = now - start_time
  214. if elapsed <= 0.0:
  215. return
  216. speed = float(byte_counter) / elapsed
  217. if speed > rate_limit:
  218. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  219. def report_writedescription(self, descfn):
  220. """ Report that the description file is being written """
  221. self.to_screen(u'[info] Writing video description to: ' + descfn)
  222. def report_writesubtitles(self, sub_filename):
  223. """ Report that the subtitles file is being written """
  224. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  225. def report_writeinfojson(self, infofn):
  226. """ Report that the metadata file has been written """
  227. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  228. def report_file_already_downloaded(self, file_name):
  229. """Report file has already been fully downloaded."""
  230. try:
  231. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  232. except (UnicodeEncodeError) as err:
  233. self.to_screen(u'[download] The file has already been downloaded')
  234. def increment_downloads(self):
  235. """Increment the ordinal that assigns a number to each file."""
  236. self._num_downloads += 1
  237. def prepare_filename(self, info_dict):
  238. """Generate the output filename."""
  239. try:
  240. template_dict = dict(info_dict)
  241. template_dict['epoch'] = int(time.time())
  242. autonumber_size = self.params.get('autonumber_size')
  243. if autonumber_size is None:
  244. autonumber_size = 5
  245. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  246. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  247. if template_dict['playlist_index'] is not None:
  248. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  249. sanitize = lambda k,v: sanitize_filename(
  250. u'NA' if v is None else compat_str(v),
  251. restricted=self.params.get('restrictfilenames'),
  252. is_id=(k==u'id'))
  253. template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
  254. filename = self.params['outtmpl'] % template_dict
  255. return filename
  256. except KeyError as err:
  257. self.report_error(u'Erroneous output template')
  258. return None
  259. except ValueError as err:
  260. self.report_error(u'Error in output template: ' + str(err) + u' (encoding: ' + repr(preferredencoding()) + ')')
  261. return None
  262. def _match_entry(self, info_dict):
  263. """ Returns None iff the file should be downloaded """
  264. title = info_dict['title']
  265. matchtitle = self.params.get('matchtitle', False)
  266. if matchtitle:
  267. if not re.search(matchtitle, title, re.IGNORECASE):
  268. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  269. rejecttitle = self.params.get('rejecttitle', False)
  270. if rejecttitle:
  271. if re.search(rejecttitle, title, re.IGNORECASE):
  272. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  273. date = info_dict.get('upload_date', None)
  274. if date is not None:
  275. dateRange = self.params.get('daterange', DateRange())
  276. if date not in dateRange:
  277. return u'[download] %s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  278. age_limit = self.params.get('age_limit')
  279. if age_limit is not None:
  280. if age_limit < info_dict.get('age_limit', 0):
  281. return u'Skipping "' + title + '" because it is age restricted'
  282. if self.in_download_archive(info_dict):
  283. return (u'%(title)s has already been recorded in archive'
  284. % info_dict)
  285. return None
  286. def extract_info(self, url, download=True, ie_key=None, extra_info={}):
  287. '''
  288. Returns a list with a dictionary for each video we find.
  289. If 'download', also downloads the videos.
  290. extra_info is a dict containing the extra values to add to each result
  291. '''
  292. if ie_key:
  293. ies = [self.get_info_extractor(ie_key)]
  294. else:
  295. ies = self._ies
  296. for ie in ies:
  297. if not ie.suitable(url):
  298. continue
  299. if not ie.working():
  300. self.report_warning(u'The program functionality for this site has been marked as broken, '
  301. u'and will probably not work.')
  302. try:
  303. ie_result = ie.extract(url)
  304. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  305. break
  306. if isinstance(ie_result, list):
  307. # Backwards compatibility: old IE result format
  308. for result in ie_result:
  309. result.update(extra_info)
  310. ie_result = {
  311. '_type': 'compat_list',
  312. 'entries': ie_result,
  313. }
  314. else:
  315. ie_result.update(extra_info)
  316. if 'extractor' not in ie_result:
  317. ie_result['extractor'] = ie.IE_NAME
  318. return self.process_ie_result(ie_result, download=download)
  319. except ExtractorError as de: # An error we somewhat expected
  320. self.report_error(compat_str(de), de.format_traceback())
  321. break
  322. except Exception as e:
  323. if self.params.get('ignoreerrors', False):
  324. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  325. break
  326. else:
  327. raise
  328. else:
  329. self.report_error(u'no suitable InfoExtractor: %s' % url)
  330. def process_ie_result(self, ie_result, download=True, extra_info={}):
  331. """
  332. Take the result of the ie(may be modified) and resolve all unresolved
  333. references (URLs, playlist items).
  334. It will also download the videos if 'download'.
  335. Returns the resolved ie_result.
  336. """
  337. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  338. if result_type == 'video':
  339. ie_result.update(extra_info)
  340. return self.process_video_result(ie_result)
  341. elif result_type == 'url':
  342. # We have to add extra_info to the results because it may be
  343. # contained in a playlist
  344. return self.extract_info(ie_result['url'],
  345. download,
  346. ie_key=ie_result.get('ie_key'),
  347. extra_info=extra_info)
  348. elif result_type == 'playlist':
  349. # We process each entry in the playlist
  350. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  351. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  352. playlist_results = []
  353. n_all_entries = len(ie_result['entries'])
  354. playliststart = self.params.get('playliststart', 1) - 1
  355. playlistend = self.params.get('playlistend', -1)
  356. if playlistend == -1:
  357. entries = ie_result['entries'][playliststart:]
  358. else:
  359. entries = ie_result['entries'][playliststart:playlistend]
  360. n_entries = len(entries)
  361. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  362. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  363. for i,entry in enumerate(entries,1):
  364. self.to_screen(u'[download] Downloading video #%s of %s' %(i, n_entries))
  365. extra = {
  366. 'playlist': playlist,
  367. 'playlist_index': i + playliststart,
  368. }
  369. if not 'extractor' in entry:
  370. # We set the extractor, if it's an url it will be set then to
  371. # the new extractor, but if it's already a video we must make
  372. # sure it's present: see issue #877
  373. entry['extractor'] = ie_result['extractor']
  374. entry_result = self.process_ie_result(entry,
  375. download=download,
  376. extra_info=extra)
  377. playlist_results.append(entry_result)
  378. ie_result['entries'] = playlist_results
  379. return ie_result
  380. elif result_type == 'compat_list':
  381. def _fixup(r):
  382. r.setdefault('extractor', ie_result['extractor'])
  383. return r
  384. ie_result['entries'] = [
  385. self.process_ie_result(_fixup(r), download=download)
  386. for r in ie_result['entries']
  387. ]
  388. return ie_result
  389. else:
  390. raise Exception('Invalid result type: %s' % result_type)
  391. def process_video_result(self, info_dict, download=True):
  392. assert info_dict.get('_type', 'video') == 'video'
  393. if 'playlist' not in info_dict:
  394. # It isn't part of a playlist
  395. info_dict['playlist'] = None
  396. info_dict['playlist_index'] = None
  397. # This extractors handle format selection themselves
  398. if info_dict['extractor'] in [u'youtube', u'Youku', u'YouPorn', u'mixcloud']:
  399. self.process_info(info_dict)
  400. return info_dict
  401. # We now pick which formats have to be downloaded
  402. if info_dict.get('formats') is None:
  403. # There's only one format available
  404. formats = [info_dict]
  405. else:
  406. formats = info_dict['formats']
  407. # We check that all the formats have the format and format_id fields
  408. for (i, format) in enumerate(formats):
  409. if format.get('format') is None:
  410. if format.get('height') is not None:
  411. if format.get('width') is not None:
  412. format_desc = u'%sx%s' % (format['width'], format['height'])
  413. else:
  414. format_desc = u'%sp' % format['height']
  415. else:
  416. format_desc = compat_str(i)
  417. format['format'] = format_desc
  418. if format.get('format_id') is None:
  419. format['format_id'] = '???'
  420. if self.params.get('listformats', None):
  421. self.list_formats(info_dict)
  422. return
  423. format_limit = self.params.get('format_limit', None)
  424. if format_limit:
  425. formats = [f for f in formats if f['format_id'] <= format_limit]
  426. if self.params.get('prefer_free_formats'):
  427. def _free_formats_key(f):
  428. try:
  429. ext_ord = [u'flv', u'mp4', u'webm'].index(f['ext'])
  430. except ValueError:
  431. ext_ord = -1
  432. # We only compare the extension if they have the same height and width
  433. return (f.get('height'), f.get('width'), ext_ord)
  434. formats = sorted(formats, key=_free_formats_key)
  435. req_format = self.params.get('format', 'best')
  436. formats_to_download = []
  437. if req_format == 'best' or req_format is None:
  438. formats_to_download = [formats[-1]]
  439. elif req_format == 'worst':
  440. formats_to_download = [formats[0]]
  441. # The -1 is for supporting YoutubeIE
  442. elif req_format in ('-1', 'all'):
  443. formats_to_download = formats
  444. else:
  445. # We can accept formats requestd in the format: 34/10/5, we pick
  446. # the first that is availble, starting from left
  447. req_formats = req_format.split('/')
  448. for rf in req_formats:
  449. matches = filter(lambda f:f['format_id'] == rf ,formats)
  450. if matches:
  451. formats_to_download = [matches[0]]
  452. break
  453. if not formats_to_download:
  454. raise ExtractorError(u'requested format not available')
  455. if download:
  456. if len(formats_to_download) > 1:
  457. self.to_screen(u'[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  458. for format in formats_to_download:
  459. new_info = dict(info_dict)
  460. new_info.update(format)
  461. self.process_info(new_info)
  462. # We update the info dict with the best quality format (backwards compatibility)
  463. info_dict.update(formats_to_download[-1])
  464. return info_dict
  465. def process_info(self, info_dict):
  466. """Process a single resolved IE result."""
  467. assert info_dict.get('_type', 'video') == 'video'
  468. #We increment the download the download count here to match the previous behaviour.
  469. self.increment_downloads()
  470. info_dict['fulltitle'] = info_dict['title']
  471. if len(info_dict['title']) > 200:
  472. info_dict['title'] = info_dict['title'][:197] + u'...'
  473. # Keep for backwards compatibility
  474. info_dict['stitle'] = info_dict['title']
  475. if not 'format' in info_dict:
  476. info_dict['format'] = info_dict['ext']
  477. reason = self._match_entry(info_dict)
  478. if reason is not None:
  479. self.to_screen(u'[download] ' + reason)
  480. return
  481. max_downloads = self.params.get('max_downloads')
  482. if max_downloads is not None:
  483. if self._num_downloads > int(max_downloads):
  484. raise MaxDownloadsReached()
  485. filename = self.prepare_filename(info_dict)
  486. # Forced printings
  487. if self.params.get('forcetitle', False):
  488. compat_print(info_dict['title'])
  489. if self.params.get('forceid', False):
  490. compat_print(info_dict['id'])
  491. if self.params.get('forceurl', False):
  492. # For RTMP URLs, also include the playpath
  493. compat_print(info_dict['url'] + info_dict.get('play_path', u''))
  494. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  495. compat_print(info_dict['thumbnail'])
  496. if self.params.get('forcedescription', False) and 'description' in info_dict:
  497. compat_print(info_dict['description'])
  498. if self.params.get('forcefilename', False) and filename is not None:
  499. compat_print(filename)
  500. if self.params.get('forceformat', False):
  501. compat_print(info_dict['format'])
  502. # Do nothing else if in simulate mode
  503. if self.params.get('simulate', False):
  504. return
  505. if filename is None:
  506. return
  507. try:
  508. dn = os.path.dirname(encodeFilename(filename))
  509. if dn != '' and not os.path.exists(dn):
  510. os.makedirs(dn)
  511. except (OSError, IOError) as err:
  512. self.report_error(u'unable to create directory ' + compat_str(err))
  513. return
  514. if self.params.get('writedescription', False):
  515. try:
  516. descfn = filename + u'.description'
  517. self.report_writedescription(descfn)
  518. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  519. descfile.write(info_dict['description'])
  520. except (KeyError, TypeError):
  521. self.report_warning(u'There\'s no description to write.')
  522. except (OSError, IOError):
  523. self.report_error(u'Cannot write description file ' + descfn)
  524. return
  525. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  526. self.params.get('writeautomaticsub')])
  527. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  528. # subtitles download errors are already managed as troubles in relevant IE
  529. # that way it will silently go on when used with unsupporting IE
  530. subtitles = info_dict['subtitles']
  531. sub_format = self.params.get('subtitlesformat')
  532. for sub_lang in subtitles.keys():
  533. sub = subtitles[sub_lang]
  534. if sub is None:
  535. continue
  536. try:
  537. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  538. self.report_writesubtitles(sub_filename)
  539. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  540. subfile.write(sub)
  541. except (OSError, IOError):
  542. self.report_error(u'Cannot write subtitles file ' + descfn)
  543. return
  544. if self.params.get('writeinfojson', False):
  545. infofn = filename + u'.info.json'
  546. self.report_writeinfojson(infofn)
  547. try:
  548. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  549. write_json_file(json_info_dict, encodeFilename(infofn))
  550. except (OSError, IOError):
  551. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  552. return
  553. if self.params.get('writethumbnail', False):
  554. if info_dict.get('thumbnail') is not None:
  555. thumb_format = determine_ext(info_dict['thumbnail'], u'jpg')
  556. thumb_filename = filename.rpartition('.')[0] + u'.' + thumb_format
  557. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  558. (info_dict['extractor'], info_dict['id']))
  559. try:
  560. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  561. with open(thumb_filename, 'wb') as thumbf:
  562. shutil.copyfileobj(uf, thumbf)
  563. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  564. (info_dict['extractor'], info_dict['id'], thumb_filename))
  565. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  566. self.report_warning(u'Unable to download thumbnail "%s": %s' %
  567. (info_dict['thumbnail'], compat_str(err)))
  568. if not self.params.get('skip_download', False):
  569. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  570. success = True
  571. else:
  572. try:
  573. success = self.fd._do_download(filename, info_dict)
  574. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  575. self.report_error(u'unable to download video data: %s' % str(err))
  576. return
  577. except (OSError, IOError) as err:
  578. raise UnavailableVideoError(err)
  579. except (ContentTooShortError, ) as err:
  580. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  581. return
  582. if success:
  583. try:
  584. self.post_process(filename, info_dict)
  585. except (PostProcessingError) as err:
  586. self.report_error(u'postprocessing: %s' % str(err))
  587. return
  588. self.record_download_archive(info_dict)
  589. def download(self, url_list):
  590. """Download a given list of URLs."""
  591. if len(url_list) > 1 and self.fixed_template():
  592. raise SameFileError(self.params['outtmpl'])
  593. for url in url_list:
  594. try:
  595. #It also downloads the videos
  596. videos = self.extract_info(url)
  597. except UnavailableVideoError:
  598. self.report_error(u'unable to download video')
  599. except MaxDownloadsReached:
  600. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  601. raise
  602. return self._download_retcode
  603. def post_process(self, filename, ie_info):
  604. """Run all the postprocessors on the given file."""
  605. info = dict(ie_info)
  606. info['filepath'] = filename
  607. keep_video = None
  608. for pp in self._pps:
  609. try:
  610. keep_video_wish,new_info = pp.run(info)
  611. if keep_video_wish is not None:
  612. if keep_video_wish:
  613. keep_video = keep_video_wish
  614. elif keep_video is None:
  615. # No clear decision yet, let IE decide
  616. keep_video = keep_video_wish
  617. except PostProcessingError as e:
  618. self.report_error(e.msg)
  619. if keep_video is False and not self.params.get('keepvideo', False):
  620. try:
  621. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  622. os.remove(encodeFilename(filename))
  623. except (IOError, OSError):
  624. self.report_warning(u'Unable to remove downloaded video file')
  625. def in_download_archive(self, info_dict):
  626. fn = self.params.get('download_archive')
  627. if fn is None:
  628. return False
  629. vid_id = info_dict['extractor'] + u' ' + info_dict['id']
  630. try:
  631. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  632. for line in archive_file:
  633. if line.strip() == vid_id:
  634. return True
  635. except IOError as ioe:
  636. if ioe.errno != errno.ENOENT:
  637. raise
  638. return False
  639. def record_download_archive(self, info_dict):
  640. fn = self.params.get('download_archive')
  641. if fn is None:
  642. return
  643. vid_id = info_dict['extractor'] + u' ' + info_dict['id']
  644. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  645. archive_file.write(vid_id + u'\n')
  646. def list_formats(self, info_dict):
  647. formats_s = []
  648. for format in info_dict.get('formats', [info_dict]):
  649. formats_s.append("%s\t:\t%s\t[%s]" % (format['format_id'],
  650. format['ext'],
  651. format.get('format', '???'),
  652. )
  653. )
  654. if len(formats_s) != 1:
  655. formats_s[0] += ' (worst)'
  656. formats_s[-1] += ' (best)'
  657. formats_s = "\n".join(formats_s)
  658. self.to_screen(u"[info] Available formats for %s:\nformat code\textension\n%s" % (info_dict['id'], formats_s))