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.

1060 lines
46 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import math
  5. import io
  6. import os
  7. import re
  8. import shutil
  9. import socket
  10. import subprocess
  11. import sys
  12. import time
  13. import traceback
  14. if os.name == 'nt':
  15. import ctypes
  16. from .utils import *
  17. from .InfoExtractors import get_info_extractor
  18. class FileDownloader(object):
  19. """File Downloader class.
  20. File downloader objects are the ones responsible of downloading the
  21. actual video file and writing it to disk if the user has requested
  22. it, among some other tasks. In most cases there should be one per
  23. program. As, given a video URL, the downloader doesn't know how to
  24. extract all the needed information, task that InfoExtractors do, it
  25. has to pass the URL to one of them.
  26. For this, file downloader objects have a method that allows
  27. InfoExtractors to be registered in a given order. When it is passed
  28. a URL, the file downloader handles it to the first InfoExtractor it
  29. finds that reports being able to handle it. The InfoExtractor extracts
  30. all the information about the video or videos the URL refers to, and
  31. asks the FileDownloader to process the video information, possibly
  32. downloading the video.
  33. File downloaders accept a lot of parameters. In order not to saturate
  34. the object constructor with arguments, it receives a dictionary of
  35. options instead. These options are available through the params
  36. attribute for the InfoExtractors to use. The FileDownloader also
  37. registers itself as the downloader in charge for the InfoExtractors
  38. that are added to it, so this is a "mutual registration".
  39. Available options:
  40. username: Username for authentication purposes.
  41. password: Password for authentication purposes.
  42. usenetrc: Use netrc for authentication instead.
  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. ratelimit: Download speed limit, in bytes/sec.
  57. nooverwrites: Prevent overwriting files.
  58. retries: Number of times to retry for HTTP error 5xx
  59. buffersize: Size of download buffer in bytes.
  60. noresizebuffer: Do not automatically resize the download buffer.
  61. continuedl: Try to continue downloads if possible.
  62. noprogress: Do not print the progress bar.
  63. playliststart: Playlist item to start at.
  64. playlistend: Playlist item to end at.
  65. matchtitle: Download only matching titles.
  66. rejecttitle: Reject downloads for matching titles.
  67. logtostderr: Log messages to stderr instead of stdout.
  68. consoletitle: Display progress in console window's titlebar.
  69. nopart: Do not use temporary .part files.
  70. updatetime: Use the Last-modified header to set output file timestamps.
  71. writedescription: Write the video description to a .description file
  72. writeinfojson: Write the video description to a .info.json file
  73. writethumbnail: Write the thumbnail image to a file
  74. writesubtitles: Write the video subtitles to a file
  75. allsubtitles: Downloads all the subtitles of the video
  76. listsubtitles: Lists all available subtitles for the video
  77. subtitlesformat: Subtitle format [sbv/srt] (default=srt)
  78. subtitleslang: Language of the subtitles to download
  79. test: Download only first bytes to test the downloader.
  80. keepvideo: Keep the video file after post-processing
  81. min_filesize: Skip files smaller than this size
  82. max_filesize: Skip files larger than this size
  83. daterange: A DateRange object, download only if the upload_date is in the range.
  84. skip_download: Skip the actual download of the video file
  85. """
  86. params = None
  87. _ies = []
  88. _pps = []
  89. _download_retcode = None
  90. _num_downloads = None
  91. _screen_file = None
  92. def __init__(self, params):
  93. """Create a FileDownloader object with the given options."""
  94. self._ies = []
  95. self._pps = []
  96. self._progress_hooks = []
  97. self._download_retcode = 0
  98. self._num_downloads = 0
  99. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  100. self.params = params
  101. if '%(stitle)s' in self.params['outtmpl']:
  102. 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.')
  103. @staticmethod
  104. def format_bytes(bytes):
  105. if bytes is None:
  106. return 'N/A'
  107. if type(bytes) is str:
  108. bytes = float(bytes)
  109. if bytes == 0.0:
  110. exponent = 0
  111. else:
  112. exponent = int(math.log(bytes, 1024.0))
  113. suffix = ['B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'][exponent]
  114. converted = float(bytes) / float(1024 ** exponent)
  115. return '%.2f%s' % (converted, suffix)
  116. @staticmethod
  117. def calc_percent(byte_counter, data_len):
  118. if data_len is None:
  119. return '---.-%'
  120. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  121. @staticmethod
  122. def calc_eta(start, now, total, current):
  123. if total is None:
  124. return '--:--'
  125. dif = now - start
  126. if current == 0 or dif < 0.001: # One millisecond
  127. return '--:--'
  128. rate = float(current) / dif
  129. eta = int((float(total) - float(current)) / rate)
  130. (eta_mins, eta_secs) = divmod(eta, 60)
  131. if eta_mins > 99:
  132. return '--:--'
  133. return '%02d:%02d' % (eta_mins, eta_secs)
  134. @staticmethod
  135. def calc_speed(start, now, bytes):
  136. dif = now - start
  137. if bytes == 0 or dif < 0.001: # One millisecond
  138. return '%10s' % '---b/s'
  139. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  140. @staticmethod
  141. def best_block_size(elapsed_time, bytes):
  142. new_min = max(bytes / 2.0, 1.0)
  143. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  144. if elapsed_time < 0.001:
  145. return int(new_max)
  146. rate = bytes / elapsed_time
  147. if rate > new_max:
  148. return int(new_max)
  149. if rate < new_min:
  150. return int(new_min)
  151. return int(rate)
  152. @staticmethod
  153. def parse_bytes(bytestr):
  154. """Parse a string indicating a byte quantity into an integer."""
  155. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  156. if matchobj is None:
  157. return None
  158. number = float(matchobj.group(1))
  159. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  160. return int(round(number * multiplier))
  161. def add_info_extractor(self, ie):
  162. """Add an InfoExtractor object to the end of the list."""
  163. self._ies.append(ie)
  164. ie.set_downloader(self)
  165. def add_post_processor(self, pp):
  166. """Add a PostProcessor object to the end of the chain."""
  167. self._pps.append(pp)
  168. pp.set_downloader(self)
  169. def to_screen(self, message, skip_eol=False):
  170. """Print message to stdout if not in quiet mode."""
  171. assert type(message) == type(u'')
  172. if not self.params.get('quiet', False):
  173. terminator = [u'\n', u''][skip_eol]
  174. output = message + terminator
  175. 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
  176. output = output.encode(preferredencoding(), 'ignore')
  177. self._screen_file.write(output)
  178. self._screen_file.flush()
  179. def to_stderr(self, message):
  180. """Print message to stderr."""
  181. assert type(message) == type(u'')
  182. output = message + u'\n'
  183. 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
  184. output = output.encode(preferredencoding())
  185. sys.stderr.write(output)
  186. def to_cons_title(self, message):
  187. """Set console/terminal window title to message."""
  188. if not self.params.get('consoletitle', False):
  189. return
  190. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  191. # c_wchar_p() might not be necessary if `message` is
  192. # already of type unicode()
  193. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  194. elif 'TERM' in os.environ:
  195. self.to_screen('\033]0;%s\007' % message, skip_eol=True)
  196. def fixed_template(self):
  197. """Checks if the output template is fixed."""
  198. return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
  199. def trouble(self, message=None, tb=None):
  200. """Determine action to take when a download problem appears.
  201. Depending on if the downloader has been configured to ignore
  202. download errors or not, this method may throw an exception or
  203. not when errors are found, after printing the message.
  204. tb, if given, is additional traceback information.
  205. """
  206. if message is not None:
  207. self.to_stderr(message)
  208. if self.params.get('verbose'):
  209. if tb is None:
  210. if sys.exc_info()[0]: # if .trouble has been called from an except block
  211. tb = u''
  212. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  213. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  214. tb += compat_str(traceback.format_exc())
  215. else:
  216. tb_data = traceback.format_list(traceback.extract_stack())
  217. tb = u''.join(tb_data)
  218. self.to_stderr(tb)
  219. if not self.params.get('ignoreerrors', False):
  220. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  221. exc_info = sys.exc_info()[1].exc_info
  222. else:
  223. exc_info = sys.exc_info()
  224. raise DownloadError(message, exc_info)
  225. self._download_retcode = 1
  226. def report_warning(self, message):
  227. '''
  228. Print the message to stderr, it will be prefixed with 'WARNING:'
  229. If stderr is a tty file the 'WARNING:' will be colored
  230. '''
  231. if sys.stderr.isatty() and os.name != 'nt':
  232. _msg_header=u'\033[0;33mWARNING:\033[0m'
  233. else:
  234. _msg_header=u'WARNING:'
  235. warning_message=u'%s %s' % (_msg_header,message)
  236. self.to_stderr(warning_message)
  237. def report_error(self, message, tb=None):
  238. '''
  239. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  240. in red if stderr is a tty file.
  241. '''
  242. if sys.stderr.isatty() and os.name != 'nt':
  243. _msg_header = u'\033[0;31mERROR:\033[0m'
  244. else:
  245. _msg_header = u'ERROR:'
  246. error_message = u'%s %s' % (_msg_header, message)
  247. self.trouble(error_message, tb)
  248. def slow_down(self, start_time, byte_counter):
  249. """Sleep if the download speed is over the rate limit."""
  250. rate_limit = self.params.get('ratelimit', None)
  251. if rate_limit is None or byte_counter == 0:
  252. return
  253. now = time.time()
  254. elapsed = now - start_time
  255. if elapsed <= 0.0:
  256. return
  257. speed = float(byte_counter) / elapsed
  258. if speed > rate_limit:
  259. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  260. def temp_name(self, filename):
  261. """Returns a temporary filename for the given filename."""
  262. if self.params.get('nopart', False) or filename == u'-' or \
  263. (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
  264. return filename
  265. return filename + u'.part'
  266. def undo_temp_name(self, filename):
  267. if filename.endswith(u'.part'):
  268. return filename[:-len(u'.part')]
  269. return filename
  270. def try_rename(self, old_filename, new_filename):
  271. try:
  272. if old_filename == new_filename:
  273. return
  274. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  275. except (IOError, OSError) as err:
  276. self.report_error(u'unable to rename file')
  277. def try_utime(self, filename, last_modified_hdr):
  278. """Try to set the last-modified time of the given file."""
  279. if last_modified_hdr is None:
  280. return
  281. if not os.path.isfile(encodeFilename(filename)):
  282. return
  283. timestr = last_modified_hdr
  284. if timestr is None:
  285. return
  286. filetime = timeconvert(timestr)
  287. if filetime is None:
  288. return filetime
  289. try:
  290. os.utime(filename, (time.time(), filetime))
  291. except:
  292. pass
  293. return filetime
  294. def report_writedescription(self, descfn):
  295. """ Report that the description file is being written """
  296. self.to_screen(u'[info] Writing video description to: ' + descfn)
  297. def report_writesubtitles(self, sub_filename):
  298. """ Report that the subtitles file is being written """
  299. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  300. def report_writeinfojson(self, infofn):
  301. """ Report that the metadata file has been written """
  302. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  303. def report_destination(self, filename):
  304. """Report destination filename."""
  305. self.to_screen(u'[download] Destination: ' + filename)
  306. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  307. """Report download progress."""
  308. if self.params.get('noprogress', False):
  309. return
  310. clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
  311. if self.params.get('progress_with_newline', False):
  312. self.to_screen(u'[download] %s of %s at %s ETA %s' %
  313. (percent_str, data_len_str, speed_str, eta_str))
  314. else:
  315. self.to_screen(u'\r%s[download] %s of %s at %s ETA %s' %
  316. (clear_line, percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  317. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  318. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  319. def report_resuming_byte(self, resume_len):
  320. """Report attempt to resume at given byte."""
  321. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  322. def report_retry(self, count, retries):
  323. """Report retry in case of HTTP error 5xx"""
  324. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  325. def report_file_already_downloaded(self, file_name):
  326. """Report file has already been fully downloaded."""
  327. try:
  328. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  329. except (UnicodeEncodeError) as err:
  330. self.to_screen(u'[download] The file has already been downloaded')
  331. def report_unable_to_resume(self):
  332. """Report it was impossible to resume download."""
  333. self.to_screen(u'[download] Unable to resume')
  334. def report_finish(self):
  335. """Report download finished."""
  336. if self.params.get('noprogress', False):
  337. self.to_screen(u'[download] Download completed')
  338. else:
  339. self.to_screen(u'')
  340. def increment_downloads(self):
  341. """Increment the ordinal that assigns a number to each file."""
  342. self._num_downloads += 1
  343. def prepare_filename(self, info_dict):
  344. """Generate the output filename."""
  345. try:
  346. template_dict = dict(info_dict)
  347. template_dict['epoch'] = int(time.time())
  348. autonumber_size = self.params.get('autonumber_size')
  349. if autonumber_size is None:
  350. autonumber_size = 5
  351. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  352. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  353. if template_dict['playlist_index'] is not None:
  354. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  355. sanitize = lambda k,v: sanitize_filename(
  356. u'NA' if v is None else compat_str(v),
  357. restricted=self.params.get('restrictfilenames'),
  358. is_id=(k==u'id'))
  359. template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
  360. filename = self.params['outtmpl'] % template_dict
  361. return filename
  362. except KeyError as err:
  363. self.report_error(u'Erroneous output template')
  364. return None
  365. except ValueError as err:
  366. self.report_error(u'Insufficient system charset ' + repr(preferredencoding()))
  367. return None
  368. def _match_entry(self, info_dict):
  369. """ Returns None iff the file should be downloaded """
  370. title = info_dict['title']
  371. matchtitle = self.params.get('matchtitle', False)
  372. if matchtitle:
  373. if not re.search(matchtitle, title, re.IGNORECASE):
  374. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  375. rejecttitle = self.params.get('rejecttitle', False)
  376. if rejecttitle:
  377. if re.search(rejecttitle, title, re.IGNORECASE):
  378. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  379. date = info_dict.get('upload_date', None)
  380. if date is not None:
  381. dateRange = self.params.get('daterange', DateRange())
  382. if date not in dateRange:
  383. return u'[download] %s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  384. return None
  385. def extract_info(self, url, download=True, ie_key=None, extra_info={}):
  386. '''
  387. Returns a list with a dictionary for each video we find.
  388. If 'download', also downloads the videos.
  389. extra_info is a dict containing the extra values to add to each result
  390. '''
  391. if ie_key:
  392. ie = get_info_extractor(ie_key)()
  393. ie.set_downloader(self)
  394. ies = [ie]
  395. else:
  396. ies = self._ies
  397. for ie in ies:
  398. if not ie.suitable(url):
  399. continue
  400. if not ie.working():
  401. self.report_warning(u'The program functionality for this site has been marked as broken, '
  402. u'and will probably not work.')
  403. try:
  404. ie_result = ie.extract(url)
  405. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  406. break
  407. if isinstance(ie_result, list):
  408. # Backwards compatibility: old IE result format
  409. for result in ie_result:
  410. result.update(extra_info)
  411. ie_result = {
  412. '_type': 'compat_list',
  413. 'entries': ie_result,
  414. }
  415. else:
  416. ie_result.update(extra_info)
  417. if 'extractor' not in ie_result:
  418. ie_result['extractor'] = ie.IE_NAME
  419. return self.process_ie_result(ie_result, download=download)
  420. except ExtractorError as de: # An error we somewhat expected
  421. self.report_error(compat_str(de), de.format_traceback())
  422. break
  423. except Exception as e:
  424. if self.params.get('ignoreerrors', False):
  425. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  426. break
  427. else:
  428. raise
  429. else:
  430. self.report_error(u'no suitable InfoExtractor: %s' % url)
  431. def process_ie_result(self, ie_result, download=True, extra_info={}):
  432. """
  433. Take the result of the ie(may be modified) and resolve all unresolved
  434. references (URLs, playlist items).
  435. It will also download the videos if 'download'.
  436. Returns the resolved ie_result.
  437. """
  438. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  439. if result_type == 'video':
  440. if 'playlist' not in ie_result:
  441. # It isn't part of a playlist
  442. ie_result['playlist'] = None
  443. ie_result['playlist_index'] = None
  444. if download:
  445. self.process_info(ie_result)
  446. return ie_result
  447. elif result_type == 'url':
  448. # We have to add extra_info to the results because it may be
  449. # contained in a playlist
  450. return self.extract_info(ie_result['url'],
  451. download,
  452. ie_key=ie_result.get('ie_key'),
  453. extra_info=extra_info)
  454. elif result_type == 'playlist':
  455. # We process each entry in the playlist
  456. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  457. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  458. playlist_results = []
  459. n_all_entries = len(ie_result['entries'])
  460. playliststart = self.params.get('playliststart', 1) - 1
  461. playlistend = self.params.get('playlistend', -1)
  462. if playlistend == -1:
  463. entries = ie_result['entries'][playliststart:]
  464. else:
  465. entries = ie_result['entries'][playliststart:playlistend]
  466. n_entries = len(entries)
  467. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  468. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  469. for i,entry in enumerate(entries,1):
  470. self.to_screen(u'[download] Downloading video #%s of %s' %(i, n_entries))
  471. extra = {
  472. 'playlist': playlist,
  473. 'playlist_index': i + playliststart,
  474. }
  475. if not 'extractor' in entry:
  476. # We set the extractor, if it's an url it will be set then to
  477. # the new extractor, but if it's already a video we must make
  478. # sure it's present: see issue #877
  479. entry['extractor'] = ie_result['extractor']
  480. entry_result = self.process_ie_result(entry,
  481. download=download,
  482. extra_info=extra)
  483. playlist_results.append(entry_result)
  484. ie_result['entries'] = playlist_results
  485. return ie_result
  486. elif result_type == 'compat_list':
  487. def _fixup(r):
  488. r.setdefault('extractor', ie_result['extractor'])
  489. return r
  490. ie_result['entries'] = [
  491. self.process_ie_result(_fixup(r), download=download)
  492. for r in ie_result['entries']
  493. ]
  494. return ie_result
  495. else:
  496. raise Exception('Invalid result type: %s' % result_type)
  497. def process_info(self, info_dict):
  498. """Process a single resolved IE result."""
  499. assert info_dict.get('_type', 'video') == 'video'
  500. #We increment the download the download count here to match the previous behaviour.
  501. self.increment_downloads()
  502. info_dict['fulltitle'] = info_dict['title']
  503. if len(info_dict['title']) > 200:
  504. info_dict['title'] = info_dict['title'][:197] + u'...'
  505. # Keep for backwards compatibility
  506. info_dict['stitle'] = info_dict['title']
  507. if not 'format' in info_dict:
  508. info_dict['format'] = info_dict['ext']
  509. reason = self._match_entry(info_dict)
  510. if reason is not None:
  511. self.to_screen(u'[download] ' + reason)
  512. return
  513. max_downloads = self.params.get('max_downloads')
  514. if max_downloads is not None:
  515. if self._num_downloads > int(max_downloads):
  516. raise MaxDownloadsReached()
  517. filename = self.prepare_filename(info_dict)
  518. # Forced printings
  519. if self.params.get('forcetitle', False):
  520. compat_print(info_dict['title'])
  521. if self.params.get('forceid', False):
  522. compat_print(info_dict['id'])
  523. if self.params.get('forceurl', False):
  524. compat_print(info_dict['url'])
  525. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  526. compat_print(info_dict['thumbnail'])
  527. if self.params.get('forcedescription', False) and 'description' in info_dict:
  528. compat_print(info_dict['description'])
  529. if self.params.get('forcefilename', False) and filename is not None:
  530. compat_print(filename)
  531. if self.params.get('forceformat', False):
  532. compat_print(info_dict['format'])
  533. # Do nothing else if in simulate mode
  534. if self.params.get('simulate', False):
  535. return
  536. if filename is None:
  537. return
  538. try:
  539. dn = os.path.dirname(encodeFilename(filename))
  540. if dn != '' and not os.path.exists(dn):
  541. os.makedirs(dn)
  542. except (OSError, IOError) as err:
  543. self.report_error(u'unable to create directory ' + compat_str(err))
  544. return
  545. if self.params.get('writedescription', False):
  546. try:
  547. descfn = filename + u'.description'
  548. self.report_writedescription(descfn)
  549. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  550. descfile.write(info_dict['description'])
  551. except (OSError, IOError):
  552. self.report_error(u'Cannot write description file ' + descfn)
  553. return
  554. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  555. # subtitles download errors are already managed as troubles in relevant IE
  556. # that way it will silently go on when used with unsupporting IE
  557. subtitle = info_dict['subtitles'][0]
  558. (sub_error, sub_lang, sub) = subtitle
  559. sub_format = self.params.get('subtitlesformat')
  560. if sub_error:
  561. self.report_warning("Some error while getting the subtitles")
  562. else:
  563. try:
  564. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  565. self.report_writesubtitles(sub_filename)
  566. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  567. subfile.write(sub)
  568. except (OSError, IOError):
  569. self.report_error(u'Cannot write subtitles file ' + descfn)
  570. return
  571. if self.params.get('allsubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  572. subtitles = info_dict['subtitles']
  573. sub_format = self.params.get('subtitlesformat')
  574. for subtitle in subtitles:
  575. (sub_error, sub_lang, sub) = subtitle
  576. if sub_error:
  577. self.report_warning("Some error while getting the subtitles")
  578. else:
  579. try:
  580. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  581. self.report_writesubtitles(sub_filename)
  582. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  583. subfile.write(sub)
  584. except (OSError, IOError):
  585. self.report_error(u'Cannot write subtitles file ' + descfn)
  586. return
  587. if self.params.get('writeinfojson', False):
  588. infofn = filename + u'.info.json'
  589. self.report_writeinfojson(infofn)
  590. try:
  591. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  592. write_json_file(json_info_dict, encodeFilename(infofn))
  593. except (OSError, IOError):
  594. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  595. return
  596. if self.params.get('writethumbnail', False):
  597. if 'thumbnail' in info_dict:
  598. thumb_format = info_dict['thumbnail'].rpartition(u'/')[2].rpartition(u'.')[2]
  599. if not thumb_format:
  600. thumb_format = 'jpg'
  601. thumb_filename = filename.rpartition('.')[0] + u'.' + thumb_format
  602. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  603. (info_dict['extractor'], info_dict['id']))
  604. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  605. with open(thumb_filename, 'wb') as thumbf:
  606. shutil.copyfileobj(uf, thumbf)
  607. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  608. (info_dict['extractor'], info_dict['id'], thumb_filename))
  609. if not self.params.get('skip_download', False):
  610. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  611. success = True
  612. else:
  613. try:
  614. success = self._do_download(filename, info_dict)
  615. except (OSError, IOError) as err:
  616. raise UnavailableVideoError()
  617. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  618. self.report_error(u'unable to download video data: %s' % str(err))
  619. return
  620. except (ContentTooShortError, ) as err:
  621. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  622. return
  623. if success:
  624. try:
  625. self.post_process(filename, info_dict)
  626. except (PostProcessingError) as err:
  627. self.report_error(u'postprocessing: %s' % str(err))
  628. return
  629. def download(self, url_list):
  630. """Download a given list of URLs."""
  631. if len(url_list) > 1 and self.fixed_template():
  632. raise SameFileError(self.params['outtmpl'])
  633. for url in url_list:
  634. try:
  635. #It also downloads the videos
  636. videos = self.extract_info(url)
  637. except UnavailableVideoError:
  638. self.report_error(u'unable to download video')
  639. except MaxDownloadsReached:
  640. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  641. raise
  642. return self._download_retcode
  643. def post_process(self, filename, ie_info):
  644. """Run all the postprocessors on the given file."""
  645. info = dict(ie_info)
  646. info['filepath'] = filename
  647. keep_video = None
  648. for pp in self._pps:
  649. try:
  650. keep_video_wish,new_info = pp.run(info)
  651. if keep_video_wish is not None:
  652. if keep_video_wish:
  653. keep_video = keep_video_wish
  654. elif keep_video is None:
  655. # No clear decision yet, let IE decide
  656. keep_video = keep_video_wish
  657. except PostProcessingError as e:
  658. self.to_stderr(u'ERROR: ' + e.msg)
  659. if keep_video is False and not self.params.get('keepvideo', False):
  660. try:
  661. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  662. os.remove(encodeFilename(filename))
  663. except (IOError, OSError):
  664. self.report_warning(u'Unable to remove downloaded video file')
  665. def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path, tc_url):
  666. self.report_destination(filename)
  667. tmpfilename = self.temp_name(filename)
  668. # Check for rtmpdump first
  669. try:
  670. subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  671. except (OSError, IOError):
  672. self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
  673. return False
  674. verbosity_option = '--verbose' if self.params.get('verbose', False) else '--quiet'
  675. # Download using rtmpdump. rtmpdump returns exit code 2 when
  676. # the connection was interrumpted and resuming appears to be
  677. # possible. This is part of rtmpdump's normal usage, AFAIK.
  678. basic_args = ['rtmpdump', verbosity_option, '-r', url, '-o', tmpfilename]
  679. if player_url is not None:
  680. basic_args += ['--swfVfy', player_url]
  681. if page_url is not None:
  682. basic_args += ['--pageUrl', page_url]
  683. if play_path is not None:
  684. basic_args += ['--playpath', play_path]
  685. if tc_url is not None:
  686. basic_args += ['--tcUrl', url]
  687. args = basic_args + [[], ['--resume', '--skip', '1']][self.params.get('continuedl', False)]
  688. if self.params.get('verbose', False):
  689. try:
  690. import pipes
  691. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  692. except ImportError:
  693. shell_quote = repr
  694. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  695. retval = subprocess.call(args)
  696. while retval == 2 or retval == 1:
  697. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  698. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  699. time.sleep(5.0) # This seems to be needed
  700. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  701. cursize = os.path.getsize(encodeFilename(tmpfilename))
  702. if prevsize == cursize and retval == 1:
  703. break
  704. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  705. if prevsize == cursize and retval == 2 and cursize > 1024:
  706. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  707. retval = 0
  708. break
  709. if retval == 0:
  710. fsize = os.path.getsize(encodeFilename(tmpfilename))
  711. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  712. self.try_rename(tmpfilename, filename)
  713. self._hook_progress({
  714. 'downloaded_bytes': fsize,
  715. 'total_bytes': fsize,
  716. 'filename': filename,
  717. 'status': 'finished',
  718. })
  719. return True
  720. else:
  721. self.to_stderr(u"\n")
  722. self.report_error(u'rtmpdump exited with code %d' % retval)
  723. return False
  724. def _download_with_mplayer(self, filename, url):
  725. self.report_destination(filename)
  726. tmpfilename = self.temp_name(filename)
  727. args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
  728. # Check for mplayer first
  729. try:
  730. subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  731. except (OSError, IOError):
  732. self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0] )
  733. return False
  734. # Download using mplayer.
  735. retval = subprocess.call(args)
  736. if retval == 0:
  737. fsize = os.path.getsize(encodeFilename(tmpfilename))
  738. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  739. self.try_rename(tmpfilename, filename)
  740. self._hook_progress({
  741. 'downloaded_bytes': fsize,
  742. 'total_bytes': fsize,
  743. 'filename': filename,
  744. 'status': 'finished',
  745. })
  746. return True
  747. else:
  748. self.to_stderr(u"\n")
  749. self.report_error(u'mplayer exited with code %d' % retval)
  750. return False
  751. def _do_download(self, filename, info_dict):
  752. url = info_dict['url']
  753. # Check file already present
  754. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  755. self.report_file_already_downloaded(filename)
  756. self._hook_progress({
  757. 'filename': filename,
  758. 'status': 'finished',
  759. })
  760. return True
  761. # Attempt to download using rtmpdump
  762. if url.startswith('rtmp'):
  763. return self._download_with_rtmpdump(filename, url,
  764. info_dict.get('player_url', None),
  765. info_dict.get('page_url', None),
  766. info_dict.get('play_path', None),
  767. info_dict.get('tc_url', None))
  768. # Attempt to download using mplayer
  769. if url.startswith('mms') or url.startswith('rtsp'):
  770. return self._download_with_mplayer(filename, url)
  771. tmpfilename = self.temp_name(filename)
  772. stream = None
  773. # Do not include the Accept-Encoding header
  774. headers = {'Youtubedl-no-compression': 'True'}
  775. if 'user_agent' in info_dict:
  776. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  777. basic_request = compat_urllib_request.Request(url, None, headers)
  778. request = compat_urllib_request.Request(url, None, headers)
  779. if self.params.get('test', False):
  780. request.add_header('Range','bytes=0-10240')
  781. # Establish possible resume length
  782. if os.path.isfile(encodeFilename(tmpfilename)):
  783. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  784. else:
  785. resume_len = 0
  786. open_mode = 'wb'
  787. if resume_len != 0:
  788. if self.params.get('continuedl', False):
  789. self.report_resuming_byte(resume_len)
  790. request.add_header('Range','bytes=%d-' % resume_len)
  791. open_mode = 'ab'
  792. else:
  793. resume_len = 0
  794. count = 0
  795. retries = self.params.get('retries', 0)
  796. while count <= retries:
  797. # Establish connection
  798. try:
  799. if count == 0 and 'urlhandle' in info_dict:
  800. data = info_dict['urlhandle']
  801. data = compat_urllib_request.urlopen(request)
  802. break
  803. except (compat_urllib_error.HTTPError, ) as err:
  804. if (err.code < 500 or err.code >= 600) and err.code != 416:
  805. # Unexpected HTTP error
  806. raise
  807. elif err.code == 416:
  808. # Unable to resume (requested range not satisfiable)
  809. try:
  810. # Open the connection again without the range header
  811. data = compat_urllib_request.urlopen(basic_request)
  812. content_length = data.info()['Content-Length']
  813. except (compat_urllib_error.HTTPError, ) as err:
  814. if err.code < 500 or err.code >= 600:
  815. raise
  816. else:
  817. # Examine the reported length
  818. if (content_length is not None and
  819. (resume_len - 100 < int(content_length) < resume_len + 100)):
  820. # The file had already been fully downloaded.
  821. # Explanation to the above condition: in issue #175 it was revealed that
  822. # YouTube sometimes adds or removes a few bytes from the end of the file,
  823. # changing the file size slightly and causing problems for some users. So
  824. # I decided to implement a suggested change and consider the file
  825. # completely downloaded if the file size differs less than 100 bytes from
  826. # the one in the hard drive.
  827. self.report_file_already_downloaded(filename)
  828. self.try_rename(tmpfilename, filename)
  829. self._hook_progress({
  830. 'filename': filename,
  831. 'status': 'finished',
  832. })
  833. return True
  834. else:
  835. # The length does not match, we start the download over
  836. self.report_unable_to_resume()
  837. open_mode = 'wb'
  838. break
  839. # Retry
  840. count += 1
  841. if count <= retries:
  842. self.report_retry(count, retries)
  843. if count > retries:
  844. self.report_error(u'giving up after %s retries' % retries)
  845. return False
  846. data_len = data.info().get('Content-length', None)
  847. if data_len is not None:
  848. data_len = int(data_len) + resume_len
  849. min_data_len = self.params.get("min_filesize", None)
  850. max_data_len = self.params.get("max_filesize", None)
  851. if min_data_len is not None and data_len < min_data_len:
  852. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  853. return False
  854. if max_data_len is not None and data_len > max_data_len:
  855. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  856. return False
  857. data_len_str = self.format_bytes(data_len)
  858. byte_counter = 0 + resume_len
  859. block_size = self.params.get('buffersize', 1024)
  860. start = time.time()
  861. while True:
  862. # Download and write
  863. before = time.time()
  864. data_block = data.read(block_size)
  865. after = time.time()
  866. if len(data_block) == 0:
  867. break
  868. byte_counter += len(data_block)
  869. # Open file just in time
  870. if stream is None:
  871. try:
  872. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  873. assert stream is not None
  874. filename = self.undo_temp_name(tmpfilename)
  875. self.report_destination(filename)
  876. except (OSError, IOError) as err:
  877. self.report_error(u'unable to open for writing: %s' % str(err))
  878. return False
  879. try:
  880. stream.write(data_block)
  881. except (IOError, OSError) as err:
  882. self.to_stderr(u"\n")
  883. self.report_error(u'unable to write data: %s' % str(err))
  884. return False
  885. if not self.params.get('noresizebuffer', False):
  886. block_size = self.best_block_size(after - before, len(data_block))
  887. # Progress message
  888. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  889. if data_len is None:
  890. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  891. else:
  892. percent_str = self.calc_percent(byte_counter, data_len)
  893. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  894. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  895. self._hook_progress({
  896. 'downloaded_bytes': byte_counter,
  897. 'total_bytes': data_len,
  898. 'tmpfilename': tmpfilename,
  899. 'filename': filename,
  900. 'status': 'downloading',
  901. })
  902. # Apply rate limit
  903. self.slow_down(start, byte_counter - resume_len)
  904. if stream is None:
  905. self.to_stderr(u"\n")
  906. self.report_error(u'Did not get any data blocks')
  907. return False
  908. stream.close()
  909. self.report_finish()
  910. if data_len is not None and byte_counter != data_len:
  911. raise ContentTooShortError(byte_counter, int(data_len))
  912. self.try_rename(tmpfilename, filename)
  913. # Update file modification time
  914. if self.params.get('updatetime', True):
  915. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  916. self._hook_progress({
  917. 'downloaded_bytes': byte_counter,
  918. 'total_bytes': byte_counter,
  919. 'filename': filename,
  920. 'status': 'finished',
  921. })
  922. return True
  923. def _hook_progress(self, status):
  924. for ph in self._progress_hooks:
  925. ph(status)
  926. def add_progress_hook(self, ph):
  927. """ ph gets called on download progress, with a dictionary with the entries
  928. * filename: The final filename
  929. * status: One of "downloading" and "finished"
  930. It can also have some of the following entries:
  931. * downloaded_bytes: Bytes on disks
  932. * total_bytes: Total bytes, None if unknown
  933. * tmpfilename: The filename we're currently writing to
  934. Hooks are guaranteed to be called at least once (with status "finished")
  935. if the download is successful.
  936. """
  937. self._progress_hooks.append(ph)