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.

817 lines
34 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 socket
  9. import subprocess
  10. import sys
  11. import time
  12. import traceback
  13. if os.name == 'nt':
  14. import ctypes
  15. from .utils import *
  16. class FileDownloader(object):
  17. """File Downloader class.
  18. File downloader 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, file downloader objects have a method that allows
  25. InfoExtractors to be registered in a given order. When it is passed
  26. a URL, the file downloader 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. asks the FileDownloader to process the video information, possibly
  30. downloading the video.
  31. File downloaders 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 FileDownloader 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. usenetrc: Use netrc for authentication instead.
  41. quiet: Do not print messages to stdout.
  42. forceurl: Force printing final URL.
  43. forcetitle: Force printing title.
  44. forcethumbnail: Force printing thumbnail URL.
  45. forcedescription: Force printing description.
  46. forcefilename: Force printing final filename.
  47. simulate: Do not download the video files.
  48. format: Video format code.
  49. format_limit: Highest quality format to try.
  50. outtmpl: Template for output names.
  51. restrictfilenames: Do not allow "&" and spaces in file names
  52. ignoreerrors: Do not stop on download errors.
  53. ratelimit: Download speed limit, in bytes/sec.
  54. nooverwrites: Prevent overwriting files.
  55. retries: Number of times to retry for HTTP error 5xx
  56. buffersize: Size of download buffer in bytes.
  57. noresizebuffer: Do not automatically resize the download buffer.
  58. continuedl: Try to continue downloads if possible.
  59. noprogress: Do not print the progress bar.
  60. playliststart: Playlist item to start at.
  61. playlistend: Playlist item to end at.
  62. matchtitle: Download only matching titles.
  63. rejecttitle: Reject downloads for matching titles.
  64. logtostderr: Log messages to stderr instead of stdout.
  65. consoletitle: Display progress in console window's titlebar.
  66. nopart: Do not use temporary .part files.
  67. updatetime: Use the Last-modified header to set output file timestamps.
  68. writedescription: Write the video description to a .description file
  69. writeinfojson: Write the video description to a .info.json file
  70. writesubtitles: Write the video subtitles to a .srt file
  71. subtitleslang: Language of the subtitles to download
  72. test: Download only first bytes to test the downloader.
  73. keepvideo: Keep the video file after post-processing
  74. min_filesize: Skip files smaller than this size
  75. max_filesize: Skip files larger than this size
  76. """
  77. params = None
  78. _ies = []
  79. _pps = []
  80. _download_retcode = None
  81. _num_downloads = None
  82. _screen_file = None
  83. def __init__(self, params):
  84. """Create a FileDownloader object with the given options."""
  85. self._ies = []
  86. self._pps = []
  87. self._progress_hooks = []
  88. self._download_retcode = 0
  89. self._num_downloads = 0
  90. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  91. self.params = params
  92. if '%(stitle)s' in self.params['outtmpl']:
  93. self.to_stderr(u'WARNING: %(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  94. @staticmethod
  95. def format_bytes(bytes):
  96. if bytes is None:
  97. return 'N/A'
  98. if type(bytes) is str:
  99. bytes = float(bytes)
  100. if bytes == 0.0:
  101. exponent = 0
  102. else:
  103. exponent = int(math.log(bytes, 1024.0))
  104. suffix = 'bkMGTPEZY'[exponent]
  105. converted = float(bytes) / float(1024 ** exponent)
  106. return '%.2f%s' % (converted, suffix)
  107. @staticmethod
  108. def calc_percent(byte_counter, data_len):
  109. if data_len is None:
  110. return '---.-%'
  111. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  112. @staticmethod
  113. def calc_eta(start, now, total, current):
  114. if total is None:
  115. return '--:--'
  116. dif = now - start
  117. if current == 0 or dif < 0.001: # One millisecond
  118. return '--:--'
  119. rate = float(current) / dif
  120. eta = int((float(total) - float(current)) / rate)
  121. (eta_mins, eta_secs) = divmod(eta, 60)
  122. if eta_mins > 99:
  123. return '--:--'
  124. return '%02d:%02d' % (eta_mins, eta_secs)
  125. @staticmethod
  126. def calc_speed(start, now, bytes):
  127. dif = now - start
  128. if bytes == 0 or dif < 0.001: # One millisecond
  129. return '%10s' % '---b/s'
  130. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  131. @staticmethod
  132. def best_block_size(elapsed_time, bytes):
  133. new_min = max(bytes / 2.0, 1.0)
  134. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  135. if elapsed_time < 0.001:
  136. return int(new_max)
  137. rate = bytes / elapsed_time
  138. if rate > new_max:
  139. return int(new_max)
  140. if rate < new_min:
  141. return int(new_min)
  142. return int(rate)
  143. @staticmethod
  144. def parse_bytes(bytestr):
  145. """Parse a string indicating a byte quantity into an integer."""
  146. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  147. if matchobj is None:
  148. return None
  149. number = float(matchobj.group(1))
  150. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  151. return int(round(number * multiplier))
  152. def add_info_extractor(self, ie):
  153. """Add an InfoExtractor object to the end of the list."""
  154. self._ies.append(ie)
  155. ie.set_downloader(self)
  156. def add_post_processor(self, pp):
  157. """Add a PostProcessor object to the end of the chain."""
  158. self._pps.append(pp)
  159. pp.set_downloader(self)
  160. def to_screen(self, message, skip_eol=False):
  161. """Print message to stdout if not in quiet mode."""
  162. assert type(message) == type(u'')
  163. if not self.params.get('quiet', False):
  164. terminator = [u'\n', u''][skip_eol]
  165. output = message + terminator
  166. 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
  167. output = output.encode(preferredencoding(), 'ignore')
  168. self._screen_file.write(output)
  169. self._screen_file.flush()
  170. def to_stderr(self, message):
  171. """Print message to stderr."""
  172. assert type(message) == type(u'')
  173. output = message + u'\n'
  174. 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
  175. output = output.encode(preferredencoding())
  176. sys.stderr.write(output)
  177. def to_cons_title(self, message):
  178. """Set console/terminal window title to message."""
  179. if not self.params.get('consoletitle', False):
  180. return
  181. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  182. # c_wchar_p() might not be necessary if `message` is
  183. # already of type unicode()
  184. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  185. elif 'TERM' in os.environ:
  186. self.to_screen('\033]0;%s\007' % message, skip_eol=True)
  187. def fixed_template(self):
  188. """Checks if the output template is fixed."""
  189. return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
  190. def trouble(self, message=None, tb=None):
  191. """Determine action to take when a download problem appears.
  192. Depending on if the downloader has been configured to ignore
  193. download errors or not, this method may throw an exception or
  194. not when errors are found, after printing the message.
  195. tb, if given, is additional traceback information.
  196. """
  197. if message is not None:
  198. self.to_stderr(message)
  199. if self.params.get('verbose'):
  200. if tb is None:
  201. tb_data = traceback.format_list(traceback.extract_stack())
  202. tb = u''.join(tb_data)
  203. self.to_stderr(tb)
  204. if not self.params.get('ignoreerrors', False):
  205. raise DownloadError(message)
  206. self._download_retcode = 1
  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 temp_name(self, filename):
  220. """Returns a temporary filename for the given filename."""
  221. if self.params.get('nopart', False) or filename == u'-' or \
  222. (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
  223. return filename
  224. return filename + u'.part'
  225. def undo_temp_name(self, filename):
  226. if filename.endswith(u'.part'):
  227. return filename[:-len(u'.part')]
  228. return filename
  229. def try_rename(self, old_filename, new_filename):
  230. try:
  231. if old_filename == new_filename:
  232. return
  233. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  234. except (IOError, OSError) as err:
  235. self.trouble(u'ERROR: unable to rename file')
  236. def try_utime(self, filename, last_modified_hdr):
  237. """Try to set the last-modified time of the given file."""
  238. if last_modified_hdr is None:
  239. return
  240. if not os.path.isfile(encodeFilename(filename)):
  241. return
  242. timestr = last_modified_hdr
  243. if timestr is None:
  244. return
  245. filetime = timeconvert(timestr)
  246. if filetime is None:
  247. return filetime
  248. try:
  249. os.utime(filename, (time.time(), filetime))
  250. except:
  251. pass
  252. return filetime
  253. def report_writedescription(self, descfn):
  254. """ Report that the description file is being written """
  255. self.to_screen(u'[info] Writing video description to: ' + descfn)
  256. def report_writesubtitles(self, srtfn):
  257. """ Report that the subtitles file is being written """
  258. self.to_screen(u'[info] Writing video subtitles to: ' + srtfn)
  259. def report_writeinfojson(self, infofn):
  260. """ Report that the metadata file has been written """
  261. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  262. def report_destination(self, filename):
  263. """Report destination filename."""
  264. self.to_screen(u'[download] Destination: ' + filename)
  265. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  266. """Report download progress."""
  267. if self.params.get('noprogress', False):
  268. return
  269. self.to_screen(u'\r[download] %s of %s at %s ETA %s' %
  270. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  271. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  272. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  273. def report_resuming_byte(self, resume_len):
  274. """Report attempt to resume at given byte."""
  275. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  276. def report_retry(self, count, retries):
  277. """Report retry in case of HTTP error 5xx"""
  278. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  279. def report_file_already_downloaded(self, file_name):
  280. """Report file has already been fully downloaded."""
  281. try:
  282. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  283. except (UnicodeEncodeError) as err:
  284. self.to_screen(u'[download] The file has already been downloaded')
  285. def report_unable_to_resume(self):
  286. """Report it was impossible to resume download."""
  287. self.to_screen(u'[download] Unable to resume')
  288. def report_finish(self):
  289. """Report download finished."""
  290. if self.params.get('noprogress', False):
  291. self.to_screen(u'[download] Download completed')
  292. else:
  293. self.to_screen(u'')
  294. def increment_downloads(self):
  295. """Increment the ordinal that assigns a number to each file."""
  296. self._num_downloads += 1
  297. def prepare_filename(self, info_dict):
  298. """Generate the output filename."""
  299. try:
  300. template_dict = dict(info_dict)
  301. template_dict['epoch'] = int(time.time())
  302. template_dict['autonumber'] = u'%05d' % self._num_downloads
  303. sanitize = lambda k,v: sanitize_filename(
  304. u'NA' if v is None else compat_str(v),
  305. restricted=self.params.get('restrictfilenames'),
  306. is_id=(k==u'id'))
  307. template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
  308. filename = self.params['outtmpl'] % template_dict
  309. return filename
  310. except (ValueError, KeyError) as err:
  311. self.trouble(u'ERROR: invalid system charset or erroneous output template')
  312. return None
  313. def _match_entry(self, info_dict):
  314. """ Returns None iff the file should be downloaded """
  315. title = info_dict['title']
  316. matchtitle = self.params.get('matchtitle', False)
  317. if matchtitle:
  318. matchtitle = matchtitle.decode('utf8')
  319. if not re.search(matchtitle, title, re.IGNORECASE):
  320. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  321. rejecttitle = self.params.get('rejecttitle', False)
  322. if rejecttitle:
  323. rejecttitle = rejecttitle.decode('utf8')
  324. if re.search(rejecttitle, title, re.IGNORECASE):
  325. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  326. return None
  327. def process_info(self, info_dict):
  328. """Process a single dictionary returned by an InfoExtractor."""
  329. # Keep for backwards compatibility
  330. info_dict['stitle'] = info_dict['title']
  331. if not 'format' in info_dict:
  332. info_dict['format'] = info_dict['ext']
  333. reason = self._match_entry(info_dict)
  334. if reason is not None:
  335. self.to_screen(u'[download] ' + reason)
  336. return
  337. max_downloads = self.params.get('max_downloads')
  338. if max_downloads is not None:
  339. if self._num_downloads > int(max_downloads):
  340. raise MaxDownloadsReached()
  341. filename = self.prepare_filename(info_dict)
  342. # Forced printings
  343. if self.params.get('forcetitle', False):
  344. compat_print(info_dict['title'])
  345. if self.params.get('forceurl', False):
  346. compat_print(info_dict['url'])
  347. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  348. compat_print(info_dict['thumbnail'])
  349. if self.params.get('forcedescription', False) and 'description' in info_dict:
  350. compat_print(info_dict['description'])
  351. if self.params.get('forcefilename', False) and filename is not None:
  352. compat_print(filename)
  353. if self.params.get('forceformat', False):
  354. compat_print(info_dict['format'])
  355. # Do nothing else if in simulate mode
  356. if self.params.get('simulate', False):
  357. return
  358. if filename is None:
  359. return
  360. try:
  361. dn = os.path.dirname(encodeFilename(filename))
  362. if dn != '' and not os.path.exists(dn): # dn is already encoded
  363. os.makedirs(dn)
  364. except (OSError, IOError) as err:
  365. self.trouble(u'ERROR: unable to create directory ' + compat_str(err))
  366. return
  367. if self.params.get('writedescription', False):
  368. try:
  369. descfn = filename + u'.description'
  370. self.report_writedescription(descfn)
  371. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  372. descfile.write(info_dict['description'])
  373. except (OSError, IOError):
  374. self.trouble(u'ERROR: Cannot write description file ' + descfn)
  375. return
  376. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  377. # subtitles download errors are already managed as troubles in relevant IE
  378. # that way it will silently go on when used with unsupporting IE
  379. try:
  380. srtfn = filename.rsplit('.', 1)[0] + u'.srt'
  381. self.report_writesubtitles(srtfn)
  382. with io.open(encodeFilename(srtfn), 'w', encoding='utf-8') as srtfile:
  383. srtfile.write(info_dict['subtitles'])
  384. except (OSError, IOError):
  385. self.trouble(u'ERROR: Cannot write subtitles file ' + descfn)
  386. return
  387. if self.params.get('writeinfojson', False):
  388. infofn = filename + u'.info.json'
  389. self.report_writeinfojson(infofn)
  390. try:
  391. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  392. write_json_file(json_info_dict, encodeFilename(infofn))
  393. except (OSError, IOError):
  394. self.trouble(u'ERROR: Cannot write metadata to JSON file ' + infofn)
  395. return
  396. if not self.params.get('skip_download', False):
  397. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  398. success = True
  399. else:
  400. try:
  401. success = self._do_download(filename, info_dict)
  402. except (OSError, IOError) as err:
  403. raise UnavailableVideoError()
  404. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  405. self.trouble(u'ERROR: unable to download video data: %s' % str(err))
  406. return
  407. except (ContentTooShortError, ) as err:
  408. self.trouble(u'ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  409. return
  410. if success:
  411. try:
  412. self.post_process(filename, info_dict)
  413. except (PostProcessingError) as err:
  414. self.trouble(u'ERROR: postprocessing: %s' % str(err))
  415. return
  416. def download(self, url_list):
  417. """Download a given list of URLs."""
  418. if len(url_list) > 1 and self.fixed_template():
  419. raise SameFileError(self.params['outtmpl'])
  420. for url in url_list:
  421. suitable_found = False
  422. for ie in self._ies:
  423. # Go to next InfoExtractor if not suitable
  424. if not ie.suitable(url):
  425. continue
  426. # Warn if the _WORKING attribute is False
  427. if not ie.working():
  428. self.to_stderr(u'WARNING: the program functionality for this site has been marked as broken, '
  429. u'and will probably not work. If you want to go on, use the -i option.')
  430. # Suitable InfoExtractor found
  431. suitable_found = True
  432. # Extract information from URL and process it
  433. try:
  434. videos = ie.extract(url)
  435. except ExtractorError as de: # An error we somewhat expected
  436. self.trouble(u'ERROR: ' + compat_str(de), de.format_traceback())
  437. break
  438. except Exception as e:
  439. if self.params.get('ignoreerrors', False):
  440. self.trouble(u'ERROR: ' + compat_str(e), tb=compat_str(traceback.format_exc()))
  441. break
  442. else:
  443. raise
  444. if len(videos or []) > 1 and self.fixed_template():
  445. raise SameFileError(self.params['outtmpl'])
  446. for video in videos or []:
  447. video['extractor'] = ie.IE_NAME
  448. try:
  449. self.increment_downloads()
  450. self.process_info(video)
  451. except UnavailableVideoError:
  452. self.trouble(u'\nERROR: unable to download video')
  453. # Suitable InfoExtractor had been found; go to next URL
  454. break
  455. if not suitable_found:
  456. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  457. return self._download_retcode
  458. def post_process(self, filename, ie_info):
  459. """Run all the postprocessors on the given file."""
  460. info = dict(ie_info)
  461. info['filepath'] = filename
  462. keep_video = None
  463. for pp in self._pps:
  464. try:
  465. keep_video_wish,new_info = pp.run(info)
  466. if keep_video_wish is not None:
  467. if keep_video_wish:
  468. keep_video = keep_video_wish
  469. elif keep_video is None:
  470. # No clear decision yet, let IE decide
  471. keep_video = keep_video_wish
  472. except PostProcessingError as e:
  473. self.to_stderr(u'ERROR: ' + e.msg)
  474. if keep_video is False and not self.params.get('keepvideo', False):
  475. try:
  476. self.to_stderr(u'Deleting original file %s (pass -k to keep)' % filename)
  477. os.remove(encodeFilename(filename))
  478. except (IOError, OSError):
  479. self.to_stderr(u'WARNING: Unable to remove downloaded video file')
  480. def _download_with_rtmpdump(self, filename, url, player_url, page_url):
  481. self.report_destination(filename)
  482. tmpfilename = self.temp_name(filename)
  483. # Check for rtmpdump first
  484. try:
  485. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  486. except (OSError, IOError):
  487. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  488. return False
  489. # Download using rtmpdump. rtmpdump returns exit code 2 when
  490. # the connection was interrumpted and resuming appears to be
  491. # possible. This is part of rtmpdump's normal usage, AFAIK.
  492. basic_args = ['rtmpdump', '-q', '-r', url, '-o', tmpfilename]
  493. if player_url is not None:
  494. basic_args += ['-W', player_url]
  495. if page_url is not None:
  496. basic_args += ['--pageUrl', page_url]
  497. args = basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)]
  498. if self.params.get('verbose', False):
  499. try:
  500. import pipes
  501. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  502. except ImportError:
  503. shell_quote = repr
  504. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  505. retval = subprocess.call(args)
  506. while retval == 2 or retval == 1:
  507. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  508. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  509. time.sleep(5.0) # This seems to be needed
  510. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  511. cursize = os.path.getsize(encodeFilename(tmpfilename))
  512. if prevsize == cursize and retval == 1:
  513. break
  514. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  515. if prevsize == cursize and retval == 2 and cursize > 1024:
  516. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  517. retval = 0
  518. break
  519. if retval == 0:
  520. fsize = os.path.getsize(encodeFilename(tmpfilename))
  521. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  522. self.try_rename(tmpfilename, filename)
  523. self._hook_progress({
  524. 'downloaded_bytes': fsize,
  525. 'total_bytes': fsize,
  526. 'filename': filename,
  527. 'status': 'finished',
  528. })
  529. return True
  530. else:
  531. self.trouble(u'\nERROR: rtmpdump exited with code %d' % retval)
  532. return False
  533. def _do_download(self, filename, info_dict):
  534. url = info_dict['url']
  535. # Check file already present
  536. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  537. self.report_file_already_downloaded(filename)
  538. self._hook_progress({
  539. 'filename': filename,
  540. 'status': 'finished',
  541. })
  542. return True
  543. # Attempt to download using rtmpdump
  544. if url.startswith('rtmp'):
  545. return self._download_with_rtmpdump(filename, url,
  546. info_dict.get('player_url', None),
  547. info_dict.get('page_url', None))
  548. tmpfilename = self.temp_name(filename)
  549. stream = None
  550. # Do not include the Accept-Encoding header
  551. headers = {'Youtubedl-no-compression': 'True'}
  552. if 'user_agent' in info_dict:
  553. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  554. basic_request = compat_urllib_request.Request(url, None, headers)
  555. request = compat_urllib_request.Request(url, None, headers)
  556. if self.params.get('test', False):
  557. request.add_header('Range','bytes=0-10240')
  558. # Establish possible resume length
  559. if os.path.isfile(encodeFilename(tmpfilename)):
  560. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  561. else:
  562. resume_len = 0
  563. open_mode = 'wb'
  564. if resume_len != 0:
  565. if self.params.get('continuedl', False):
  566. self.report_resuming_byte(resume_len)
  567. request.add_header('Range','bytes=%d-' % resume_len)
  568. open_mode = 'ab'
  569. else:
  570. resume_len = 0
  571. count = 0
  572. retries = self.params.get('retries', 0)
  573. while count <= retries:
  574. # Establish connection
  575. try:
  576. if count == 0 and 'urlhandle' in info_dict:
  577. data = info_dict['urlhandle']
  578. data = compat_urllib_request.urlopen(request)
  579. break
  580. except (compat_urllib_error.HTTPError, ) as err:
  581. if (err.code < 500 or err.code >= 600) and err.code != 416:
  582. # Unexpected HTTP error
  583. raise
  584. elif err.code == 416:
  585. # Unable to resume (requested range not satisfiable)
  586. try:
  587. # Open the connection again without the range header
  588. data = compat_urllib_request.urlopen(basic_request)
  589. content_length = data.info()['Content-Length']
  590. except (compat_urllib_error.HTTPError, ) as err:
  591. if err.code < 500 or err.code >= 600:
  592. raise
  593. else:
  594. # Examine the reported length
  595. if (content_length is not None and
  596. (resume_len - 100 < int(content_length) < resume_len + 100)):
  597. # The file had already been fully downloaded.
  598. # Explanation to the above condition: in issue #175 it was revealed that
  599. # YouTube sometimes adds or removes a few bytes from the end of the file,
  600. # changing the file size slightly and causing problems for some users. So
  601. # I decided to implement a suggested change and consider the file
  602. # completely downloaded if the file size differs less than 100 bytes from
  603. # the one in the hard drive.
  604. self.report_file_already_downloaded(filename)
  605. self.try_rename(tmpfilename, filename)
  606. self._hook_progress({
  607. 'filename': filename,
  608. 'status': 'finished',
  609. })
  610. return True
  611. else:
  612. # The length does not match, we start the download over
  613. self.report_unable_to_resume()
  614. open_mode = 'wb'
  615. break
  616. # Retry
  617. count += 1
  618. if count <= retries:
  619. self.report_retry(count, retries)
  620. if count > retries:
  621. self.trouble(u'ERROR: giving up after %s retries' % retries)
  622. return False
  623. data_len = data.info().get('Content-length', None)
  624. if data_len is not None:
  625. data_len = int(data_len) + resume_len
  626. min_data_len = self.params.get("min_filesize", None)
  627. max_data_len = self.params.get("max_filesize", None)
  628. if min_data_len is not None and data_len < min_data_len:
  629. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  630. return False
  631. if max_data_len is not None and data_len > max_data_len:
  632. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  633. return False
  634. data_len_str = self.format_bytes(data_len)
  635. byte_counter = 0 + resume_len
  636. block_size = self.params.get('buffersize', 1024)
  637. start = time.time()
  638. while True:
  639. # Download and write
  640. before = time.time()
  641. data_block = data.read(block_size)
  642. after = time.time()
  643. if len(data_block) == 0:
  644. break
  645. byte_counter += len(data_block)
  646. # Open file just in time
  647. if stream is None:
  648. try:
  649. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  650. assert stream is not None
  651. filename = self.undo_temp_name(tmpfilename)
  652. self.report_destination(filename)
  653. except (OSError, IOError) as err:
  654. self.trouble(u'ERROR: unable to open for writing: %s' % str(err))
  655. return False
  656. try:
  657. stream.write(data_block)
  658. except (IOError, OSError) as err:
  659. self.trouble(u'\nERROR: unable to write data: %s' % str(err))
  660. return False
  661. if not self.params.get('noresizebuffer', False):
  662. block_size = self.best_block_size(after - before, len(data_block))
  663. # Progress message
  664. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  665. if data_len is None:
  666. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  667. else:
  668. percent_str = self.calc_percent(byte_counter, data_len)
  669. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  670. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  671. self._hook_progress({
  672. 'downloaded_bytes': byte_counter,
  673. 'total_bytes': data_len,
  674. 'tmpfilename': tmpfilename,
  675. 'filename': filename,
  676. 'status': 'downloading',
  677. })
  678. # Apply rate limit
  679. self.slow_down(start, byte_counter - resume_len)
  680. if stream is None:
  681. self.trouble(u'\nERROR: Did not get any data blocks')
  682. return False
  683. stream.close()
  684. self.report_finish()
  685. if data_len is not None and byte_counter != data_len:
  686. raise ContentTooShortError(byte_counter, int(data_len))
  687. self.try_rename(tmpfilename, filename)
  688. # Update file modification time
  689. if self.params.get('updatetime', True):
  690. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  691. self._hook_progress({
  692. 'downloaded_bytes': byte_counter,
  693. 'total_bytes': byte_counter,
  694. 'filename': filename,
  695. 'status': 'finished',
  696. })
  697. return True
  698. def _hook_progress(self, status):
  699. for ph in self._progress_hooks:
  700. ph(status)
  701. def add_progress_hook(self, ph):
  702. """ ph gets called on download progress, with a dictionary with the entries
  703. * filename: The final filename
  704. * status: One of "downloading" and "finished"
  705. It can also have some of the following entries:
  706. * downloaded_bytes: Bytes on disks
  707. * total_bytes: Total bytes, None if unknown
  708. * tmpfilename: The filename we're currently writing to
  709. Hooks are guaranteed to be called at least once (with status "finished")
  710. if the download is successful.
  711. """
  712. self._progress_hooks.append(ph)