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.

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