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.

821 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. if self.params.get('progress_with_newline', False):
  270. self.to_screen(u'[download] %s of %s at %s ETA %s' %
  271. (percent_str, data_len_str, speed_str, eta_str))
  272. else:
  273. self.to_screen(u'\r[download] %s of %s at %s ETA %s' %
  274. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  275. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  276. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  277. def report_resuming_byte(self, resume_len):
  278. """Report attempt to resume at given byte."""
  279. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  280. def report_retry(self, count, retries):
  281. """Report retry in case of HTTP error 5xx"""
  282. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  283. def report_file_already_downloaded(self, file_name):
  284. """Report file has already been fully downloaded."""
  285. try:
  286. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  287. except (UnicodeEncodeError) as err:
  288. self.to_screen(u'[download] The file has already been downloaded')
  289. def report_unable_to_resume(self):
  290. """Report it was impossible to resume download."""
  291. self.to_screen(u'[download] Unable to resume')
  292. def report_finish(self):
  293. """Report download finished."""
  294. if self.params.get('noprogress', False):
  295. self.to_screen(u'[download] Download completed')
  296. else:
  297. self.to_screen(u'')
  298. def increment_downloads(self):
  299. """Increment the ordinal that assigns a number to each file."""
  300. self._num_downloads += 1
  301. def prepare_filename(self, info_dict):
  302. """Generate the output filename."""
  303. try:
  304. template_dict = dict(info_dict)
  305. template_dict['epoch'] = int(time.time())
  306. template_dict['autonumber'] = u'%05d' % self._num_downloads
  307. sanitize = lambda k,v: sanitize_filename(
  308. u'NA' if v is None else compat_str(v),
  309. restricted=self.params.get('restrictfilenames'),
  310. is_id=(k==u'id'))
  311. template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
  312. filename = self.params['outtmpl'] % template_dict
  313. return filename
  314. except (ValueError, KeyError) as err:
  315. self.trouble(u'ERROR: invalid system charset or erroneous output template')
  316. return None
  317. def _match_entry(self, info_dict):
  318. """ Returns None iff the file should be downloaded """
  319. title = info_dict['title']
  320. matchtitle = self.params.get('matchtitle', False)
  321. if matchtitle:
  322. matchtitle = matchtitle.decode('utf8')
  323. if not re.search(matchtitle, title, re.IGNORECASE):
  324. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  325. rejecttitle = self.params.get('rejecttitle', False)
  326. if rejecttitle:
  327. rejecttitle = rejecttitle.decode('utf8')
  328. if re.search(rejecttitle, title, re.IGNORECASE):
  329. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  330. return None
  331. def process_info(self, info_dict):
  332. """Process a single dictionary returned by an InfoExtractor."""
  333. # Keep for backwards compatibility
  334. info_dict['stitle'] = info_dict['title']
  335. if not 'format' in info_dict:
  336. info_dict['format'] = info_dict['ext']
  337. reason = self._match_entry(info_dict)
  338. if reason is not None:
  339. self.to_screen(u'[download] ' + reason)
  340. return
  341. max_downloads = self.params.get('max_downloads')
  342. if max_downloads is not None:
  343. if self._num_downloads > int(max_downloads):
  344. raise MaxDownloadsReached()
  345. filename = self.prepare_filename(info_dict)
  346. # Forced printings
  347. if self.params.get('forcetitle', False):
  348. compat_print(info_dict['title'])
  349. if self.params.get('forceurl', False):
  350. compat_print(info_dict['url'])
  351. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  352. compat_print(info_dict['thumbnail'])
  353. if self.params.get('forcedescription', False) and 'description' in info_dict:
  354. compat_print(info_dict['description'])
  355. if self.params.get('forcefilename', False) and filename is not None:
  356. compat_print(filename)
  357. if self.params.get('forceformat', False):
  358. compat_print(info_dict['format'])
  359. # Do nothing else if in simulate mode
  360. if self.params.get('simulate', False):
  361. return
  362. if filename is None:
  363. return
  364. try:
  365. dn = os.path.dirname(encodeFilename(filename))
  366. if dn != '' and not os.path.exists(dn): # dn is already encoded
  367. os.makedirs(dn)
  368. except (OSError, IOError) as err:
  369. self.trouble(u'ERROR: unable to create directory ' + compat_str(err))
  370. return
  371. if self.params.get('writedescription', False):
  372. try:
  373. descfn = filename + u'.description'
  374. self.report_writedescription(descfn)
  375. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  376. descfile.write(info_dict['description'])
  377. except (OSError, IOError):
  378. self.trouble(u'ERROR: Cannot write description file ' + descfn)
  379. return
  380. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  381. # subtitles download errors are already managed as troubles in relevant IE
  382. # that way it will silently go on when used with unsupporting IE
  383. try:
  384. srtfn = filename.rsplit('.', 1)[0] + u'.srt'
  385. self.report_writesubtitles(srtfn)
  386. with io.open(encodeFilename(srtfn), 'w', encoding='utf-8') as srtfile:
  387. srtfile.write(info_dict['subtitles'])
  388. except (OSError, IOError):
  389. self.trouble(u'ERROR: Cannot write subtitles file ' + descfn)
  390. return
  391. if self.params.get('writeinfojson', False):
  392. infofn = filename + u'.info.json'
  393. self.report_writeinfojson(infofn)
  394. try:
  395. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  396. write_json_file(json_info_dict, encodeFilename(infofn))
  397. except (OSError, IOError):
  398. self.trouble(u'ERROR: Cannot write metadata to JSON file ' + infofn)
  399. return
  400. if not self.params.get('skip_download', False):
  401. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  402. success = True
  403. else:
  404. try:
  405. success = self._do_download(filename, info_dict)
  406. except (OSError, IOError) as err:
  407. raise UnavailableVideoError()
  408. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  409. self.trouble(u'ERROR: unable to download video data: %s' % str(err))
  410. return
  411. except (ContentTooShortError, ) as err:
  412. self.trouble(u'ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  413. return
  414. if success:
  415. try:
  416. self.post_process(filename, info_dict)
  417. except (PostProcessingError) as err:
  418. self.trouble(u'ERROR: postprocessing: %s' % str(err))
  419. return
  420. def download(self, url_list):
  421. """Download a given list of URLs."""
  422. if len(url_list) > 1 and self.fixed_template():
  423. raise SameFileError(self.params['outtmpl'])
  424. for url in url_list:
  425. suitable_found = False
  426. for ie in self._ies:
  427. # Go to next InfoExtractor if not suitable
  428. if not ie.suitable(url):
  429. continue
  430. # Warn if the _WORKING attribute is False
  431. if not ie.working():
  432. self.to_stderr(u'WARNING: the program functionality for this site has been marked as broken, '
  433. u'and will probably not work. If you want to go on, use the -i option.')
  434. # Suitable InfoExtractor found
  435. suitable_found = True
  436. # Extract information from URL and process it
  437. try:
  438. videos = ie.extract(url)
  439. except ExtractorError as de: # An error we somewhat expected
  440. self.trouble(u'ERROR: ' + compat_str(de), de.format_traceback())
  441. break
  442. except Exception as e:
  443. if self.params.get('ignoreerrors', False):
  444. self.trouble(u'ERROR: ' + compat_str(e), tb=compat_str(traceback.format_exc()))
  445. break
  446. else:
  447. raise
  448. if len(videos or []) > 1 and self.fixed_template():
  449. raise SameFileError(self.params['outtmpl'])
  450. for video in videos or []:
  451. video['extractor'] = ie.IE_NAME
  452. try:
  453. self.increment_downloads()
  454. self.process_info(video)
  455. except UnavailableVideoError:
  456. self.trouble(u'\nERROR: unable to download video')
  457. # Suitable InfoExtractor had been found; go to next URL
  458. break
  459. if not suitable_found:
  460. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  461. return self._download_retcode
  462. def post_process(self, filename, ie_info):
  463. """Run all the postprocessors on the given file."""
  464. info = dict(ie_info)
  465. info['filepath'] = filename
  466. keep_video = None
  467. for pp in self._pps:
  468. try:
  469. keep_video_wish,new_info = pp.run(info)
  470. if keep_video_wish is not None:
  471. if keep_video_wish:
  472. keep_video = keep_video_wish
  473. elif keep_video is None:
  474. # No clear decision yet, let IE decide
  475. keep_video = keep_video_wish
  476. except PostProcessingError as e:
  477. self.to_stderr(u'ERROR: ' + e.msg)
  478. if keep_video is False and not self.params.get('keepvideo', False):
  479. try:
  480. self.to_stderr(u'Deleting original file %s (pass -k to keep)' % filename)
  481. os.remove(encodeFilename(filename))
  482. except (IOError, OSError):
  483. self.to_stderr(u'WARNING: Unable to remove downloaded video file')
  484. def _download_with_rtmpdump(self, filename, url, player_url, page_url):
  485. self.report_destination(filename)
  486. tmpfilename = self.temp_name(filename)
  487. # Check for rtmpdump first
  488. try:
  489. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  490. except (OSError, IOError):
  491. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  492. return False
  493. # Download using rtmpdump. rtmpdump returns exit code 2 when
  494. # the connection was interrumpted and resuming appears to be
  495. # possible. This is part of rtmpdump's normal usage, AFAIK.
  496. basic_args = ['rtmpdump', '-q', '-r', url, '-o', tmpfilename]
  497. if player_url is not None:
  498. basic_args += ['-W', player_url]
  499. if page_url is not None:
  500. basic_args += ['--pageUrl', page_url]
  501. args = basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)]
  502. if self.params.get('verbose', False):
  503. try:
  504. import pipes
  505. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  506. except ImportError:
  507. shell_quote = repr
  508. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  509. retval = subprocess.call(args)
  510. while retval == 2 or retval == 1:
  511. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  512. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  513. time.sleep(5.0) # This seems to be needed
  514. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  515. cursize = os.path.getsize(encodeFilename(tmpfilename))
  516. if prevsize == cursize and retval == 1:
  517. break
  518. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  519. if prevsize == cursize and retval == 2 and cursize > 1024:
  520. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  521. retval = 0
  522. break
  523. if retval == 0:
  524. fsize = os.path.getsize(encodeFilename(tmpfilename))
  525. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  526. self.try_rename(tmpfilename, filename)
  527. self._hook_progress({
  528. 'downloaded_bytes': fsize,
  529. 'total_bytes': fsize,
  530. 'filename': filename,
  531. 'status': 'finished',
  532. })
  533. return True
  534. else:
  535. self.trouble(u'\nERROR: rtmpdump exited with code %d' % retval)
  536. return False
  537. def _do_download(self, filename, info_dict):
  538. url = info_dict['url']
  539. # Check file already present
  540. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  541. self.report_file_already_downloaded(filename)
  542. self._hook_progress({
  543. 'filename': filename,
  544. 'status': 'finished',
  545. })
  546. return True
  547. # Attempt to download using rtmpdump
  548. if url.startswith('rtmp'):
  549. return self._download_with_rtmpdump(filename, url,
  550. info_dict.get('player_url', None),
  551. info_dict.get('page_url', None))
  552. tmpfilename = self.temp_name(filename)
  553. stream = None
  554. # Do not include the Accept-Encoding header
  555. headers = {'Youtubedl-no-compression': 'True'}
  556. if 'user_agent' in info_dict:
  557. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  558. basic_request = compat_urllib_request.Request(url, None, headers)
  559. request = compat_urllib_request.Request(url, None, headers)
  560. if self.params.get('test', False):
  561. request.add_header('Range','bytes=0-10240')
  562. # Establish possible resume length
  563. if os.path.isfile(encodeFilename(tmpfilename)):
  564. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  565. else:
  566. resume_len = 0
  567. open_mode = 'wb'
  568. if resume_len != 0:
  569. if self.params.get('continuedl', False):
  570. self.report_resuming_byte(resume_len)
  571. request.add_header('Range','bytes=%d-' % resume_len)
  572. open_mode = 'ab'
  573. else:
  574. resume_len = 0
  575. count = 0
  576. retries = self.params.get('retries', 0)
  577. while count <= retries:
  578. # Establish connection
  579. try:
  580. if count == 0 and 'urlhandle' in info_dict:
  581. data = info_dict['urlhandle']
  582. data = compat_urllib_request.urlopen(request)
  583. break
  584. except (compat_urllib_error.HTTPError, ) as err:
  585. if (err.code < 500 or err.code >= 600) and err.code != 416:
  586. # Unexpected HTTP error
  587. raise
  588. elif err.code == 416:
  589. # Unable to resume (requested range not satisfiable)
  590. try:
  591. # Open the connection again without the range header
  592. data = compat_urllib_request.urlopen(basic_request)
  593. content_length = data.info()['Content-Length']
  594. except (compat_urllib_error.HTTPError, ) as err:
  595. if err.code < 500 or err.code >= 600:
  596. raise
  597. else:
  598. # Examine the reported length
  599. if (content_length is not None and
  600. (resume_len - 100 < int(content_length) < resume_len + 100)):
  601. # The file had already been fully downloaded.
  602. # Explanation to the above condition: in issue #175 it was revealed that
  603. # YouTube sometimes adds or removes a few bytes from the end of the file,
  604. # changing the file size slightly and causing problems for some users. So
  605. # I decided to implement a suggested change and consider the file
  606. # completely downloaded if the file size differs less than 100 bytes from
  607. # the one in the hard drive.
  608. self.report_file_already_downloaded(filename)
  609. self.try_rename(tmpfilename, filename)
  610. self._hook_progress({
  611. 'filename': filename,
  612. 'status': 'finished',
  613. })
  614. return True
  615. else:
  616. # The length does not match, we start the download over
  617. self.report_unable_to_resume()
  618. open_mode = 'wb'
  619. break
  620. # Retry
  621. count += 1
  622. if count <= retries:
  623. self.report_retry(count, retries)
  624. if count > retries:
  625. self.trouble(u'ERROR: giving up after %s retries' % retries)
  626. return False
  627. data_len = data.info().get('Content-length', None)
  628. if data_len is not None:
  629. data_len = int(data_len) + resume_len
  630. min_data_len = self.params.get("min_filesize", None)
  631. max_data_len = self.params.get("max_filesize", None)
  632. if min_data_len is not None and data_len < min_data_len:
  633. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  634. return False
  635. if max_data_len is not None and data_len > max_data_len:
  636. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  637. return False
  638. data_len_str = self.format_bytes(data_len)
  639. byte_counter = 0 + resume_len
  640. block_size = self.params.get('buffersize', 1024)
  641. start = time.time()
  642. while True:
  643. # Download and write
  644. before = time.time()
  645. data_block = data.read(block_size)
  646. after = time.time()
  647. if len(data_block) == 0:
  648. break
  649. byte_counter += len(data_block)
  650. # Open file just in time
  651. if stream is None:
  652. try:
  653. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  654. assert stream is not None
  655. filename = self.undo_temp_name(tmpfilename)
  656. self.report_destination(filename)
  657. except (OSError, IOError) as err:
  658. self.trouble(u'ERROR: unable to open for writing: %s' % str(err))
  659. return False
  660. try:
  661. stream.write(data_block)
  662. except (IOError, OSError) as err:
  663. self.trouble(u'\nERROR: unable to write data: %s' % str(err))
  664. return False
  665. if not self.params.get('noresizebuffer', False):
  666. block_size = self.best_block_size(after - before, len(data_block))
  667. # Progress message
  668. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  669. if data_len is None:
  670. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  671. else:
  672. percent_str = self.calc_percent(byte_counter, data_len)
  673. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  674. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  675. self._hook_progress({
  676. 'downloaded_bytes': byte_counter,
  677. 'total_bytes': data_len,
  678. 'tmpfilename': tmpfilename,
  679. 'filename': filename,
  680. 'status': 'downloading',
  681. })
  682. # Apply rate limit
  683. self.slow_down(start, byte_counter - resume_len)
  684. if stream is None:
  685. self.trouble(u'\nERROR: Did not get any data blocks')
  686. return False
  687. stream.close()
  688. self.report_finish()
  689. if data_len is not None and byte_counter != data_len:
  690. raise ContentTooShortError(byte_counter, int(data_len))
  691. self.try_rename(tmpfilename, filename)
  692. # Update file modification time
  693. if self.params.get('updatetime', True):
  694. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  695. self._hook_progress({
  696. 'downloaded_bytes': byte_counter,
  697. 'total_bytes': byte_counter,
  698. 'filename': filename,
  699. 'status': 'finished',
  700. })
  701. return True
  702. def _hook_progress(self, status):
  703. for ph in self._progress_hooks:
  704. ph(status)
  705. def add_progress_hook(self, ph):
  706. """ ph gets called on download progress, with a dictionary with the entries
  707. * filename: The final filename
  708. * status: One of "downloading" and "finished"
  709. It can also have some of the following entries:
  710. * downloaded_bytes: Bytes on disks
  711. * total_bytes: Total bytes, None if unknown
  712. * tmpfilename: The filename we're currently writing to
  713. Hooks are guaranteed to be called at least once (with status "finished")
  714. if the download is successful.
  715. """
  716. self._progress_hooks.append(ph)