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.

708 lines
25 KiB

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