FileDownloader.py 30 KB

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