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.

587 lines
24 KiB

  1. import math
  2. import os
  3. import re
  4. import subprocess
  5. import sys
  6. import time
  7. import traceback
  8. if os.name == 'nt':
  9. import ctypes
  10. from .utils import *
  11. class FileDownloader(object):
  12. """File Downloader class.
  13. File downloader objects are the ones responsible of downloading the
  14. actual video file and writing it to disk.
  15. File downloaders accept a lot of parameters. In order not to saturate
  16. the object constructor with arguments, it receives a dictionary of
  17. options instead.
  18. Available options:
  19. verbose: Print additional info to stdout.
  20. quiet: Do not print messages to stdout.
  21. ratelimit: Download speed limit, in bytes/sec.
  22. retries: Number of times to retry for HTTP error 5xx
  23. buffersize: Size of download buffer in bytes.
  24. noresizebuffer: Do not automatically resize the download buffer.
  25. continuedl: Try to continue downloads if possible.
  26. noprogress: Do not print the progress bar.
  27. logtostderr: Log messages to stderr instead of stdout.
  28. consoletitle: Display progress in console window's titlebar.
  29. nopart: Do not use temporary .part files.
  30. updatetime: Use the Last-modified header to set output file timestamps.
  31. test: Download only first bytes to test the downloader.
  32. min_filesize: Skip files smaller than this size
  33. max_filesize: Skip files larger than this size
  34. """
  35. params = None
  36. def __init__(self, ydl, params):
  37. """Create a FileDownloader object with the given options."""
  38. self.ydl = ydl
  39. self._progress_hooks = []
  40. self.params = params
  41. @staticmethod
  42. def format_bytes(bytes):
  43. if bytes is None:
  44. return 'N/A'
  45. if type(bytes) is str:
  46. bytes = float(bytes)
  47. if bytes == 0.0:
  48. exponent = 0
  49. else:
  50. exponent = int(math.log(bytes, 1024.0))
  51. suffix = ['B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'][exponent]
  52. converted = float(bytes) / float(1024 ** exponent)
  53. return '%.2f%s' % (converted, suffix)
  54. @staticmethod
  55. def format_seconds(seconds):
  56. (mins, secs) = divmod(seconds, 60)
  57. (hours, eta_mins) = divmod(mins, 60)
  58. if hours > 99:
  59. return '--:--:--'
  60. if hours == 0:
  61. return '%02d:%02d' % (mins, secs)
  62. else:
  63. return '%02d:%02d:%02d' % (hours, mins, secs)
  64. @staticmethod
  65. def calc_percent(byte_counter, data_len):
  66. if data_len is None:
  67. return '---.-%'
  68. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  69. @staticmethod
  70. def calc_eta(start, now, total, current):
  71. if total is None:
  72. return '--:--'
  73. dif = now - start
  74. if current == 0 or dif < 0.001: # One millisecond
  75. return '--:--'
  76. rate = float(current) / dif
  77. eta = int((float(total) - float(current)) / rate)
  78. return FileDownloader.format_seconds(eta)
  79. @staticmethod
  80. def calc_speed(start, now, bytes):
  81. dif = now - start
  82. if bytes == 0 or dif < 0.001: # One millisecond
  83. return '%10s' % '---b/s'
  84. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  85. @staticmethod
  86. def best_block_size(elapsed_time, bytes):
  87. new_min = max(bytes / 2.0, 1.0)
  88. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  89. if elapsed_time < 0.001:
  90. return int(new_max)
  91. rate = bytes / elapsed_time
  92. if rate > new_max:
  93. return int(new_max)
  94. if rate < new_min:
  95. return int(new_min)
  96. return int(rate)
  97. @staticmethod
  98. def parse_bytes(bytestr):
  99. """Parse a string indicating a byte quantity into an integer."""
  100. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  101. if matchobj is None:
  102. return None
  103. number = float(matchobj.group(1))
  104. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  105. return int(round(number * multiplier))
  106. def to_screen(self, *args, **kargs):
  107. self.ydl.to_screen(*args, **kargs)
  108. def to_stderr(self, message):
  109. self.ydl.to_screen(message)
  110. def to_cons_title(self, message):
  111. """Set console/terminal window title to message."""
  112. if not self.params.get('consoletitle', False):
  113. return
  114. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  115. # c_wchar_p() might not be necessary if `message` is
  116. # already of type unicode()
  117. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  118. elif 'TERM' in os.environ:
  119. self.to_screen('\033]0;%s\007' % message, skip_eol=True)
  120. def trouble(self, *args, **kargs):
  121. self.ydl.trouble(*args, **kargs)
  122. def report_warning(self, *args, **kargs):
  123. self.ydl.report_warning(*args, **kargs)
  124. def report_error(self, *args, **kargs):
  125. self.ydl.report_error(*args, **kargs)
  126. def slow_down(self, start_time, byte_counter):
  127. """Sleep if the download speed is over the rate limit."""
  128. rate_limit = self.params.get('ratelimit', None)
  129. if rate_limit is None or byte_counter == 0:
  130. return
  131. now = time.time()
  132. elapsed = now - start_time
  133. if elapsed <= 0.0:
  134. return
  135. speed = float(byte_counter) / elapsed
  136. if speed > rate_limit:
  137. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  138. def temp_name(self, filename):
  139. """Returns a temporary filename for the given filename."""
  140. if self.params.get('nopart', False) or filename == u'-' or \
  141. (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
  142. return filename
  143. return filename + u'.part'
  144. def undo_temp_name(self, filename):
  145. if filename.endswith(u'.part'):
  146. return filename[:-len(u'.part')]
  147. return filename
  148. def try_rename(self, old_filename, new_filename):
  149. try:
  150. if old_filename == new_filename:
  151. return
  152. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  153. except (IOError, OSError) as err:
  154. self.report_error(u'unable to rename file')
  155. def try_utime(self, filename, last_modified_hdr):
  156. """Try to set the last-modified time of the given file."""
  157. if last_modified_hdr is None:
  158. return
  159. if not os.path.isfile(encodeFilename(filename)):
  160. return
  161. timestr = last_modified_hdr
  162. if timestr is None:
  163. return
  164. filetime = timeconvert(timestr)
  165. if filetime is None:
  166. return filetime
  167. # Ignore obviously invalid dates
  168. if filetime == 0:
  169. return
  170. try:
  171. os.utime(filename, (time.time(), filetime))
  172. except:
  173. pass
  174. return filetime
  175. def report_destination(self, filename):
  176. """Report destination filename."""
  177. self.to_screen(u'[download] Destination: ' + filename)
  178. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  179. """Report download progress."""
  180. if self.params.get('noprogress', False):
  181. return
  182. clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
  183. if self.params.get('progress_with_newline', False):
  184. self.to_screen(u'[download] %s of %s at %s ETA %s' %
  185. (percent_str, data_len_str, speed_str, eta_str))
  186. else:
  187. self.to_screen(u'\r%s[download] %s of %s at %s ETA %s' %
  188. (clear_line, percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  189. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  190. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  191. def report_resuming_byte(self, resume_len):
  192. """Report attempt to resume at given byte."""
  193. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  194. def report_retry(self, count, retries):
  195. """Report retry in case of HTTP error 5xx"""
  196. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  197. def report_file_already_downloaded(self, file_name):
  198. """Report file has already been fully downloaded."""
  199. try:
  200. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  201. except (UnicodeEncodeError) as err:
  202. self.to_screen(u'[download] The file has already been downloaded')
  203. def report_unable_to_resume(self):
  204. """Report it was impossible to resume download."""
  205. self.to_screen(u'[download] Unable to resume')
  206. def report_finish(self, data_len_str, tot_time):
  207. """Report download finished."""
  208. if self.params.get('noprogress', False):
  209. self.to_screen(u'[download] Download completed')
  210. else:
  211. clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
  212. self.to_screen(u'\r%s[download] 100%% of %s in %s' %
  213. (clear_line, data_len_str, self.format_seconds(tot_time)))
  214. def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path, tc_url):
  215. self.report_destination(filename)
  216. tmpfilename = self.temp_name(filename)
  217. # Check for rtmpdump first
  218. try:
  219. subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  220. except (OSError, IOError):
  221. self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
  222. return False
  223. verbosity_option = '--verbose' if self.params.get('verbose', False) else '--quiet'
  224. # Download using rtmpdump. rtmpdump returns exit code 2 when
  225. # the connection was interrumpted and resuming appears to be
  226. # possible. This is part of rtmpdump's normal usage, AFAIK.
  227. basic_args = ['rtmpdump', verbosity_option, '-r', url, '-o', tmpfilename]
  228. if player_url is not None:
  229. basic_args += ['--swfVfy', player_url]
  230. if page_url is not None:
  231. basic_args += ['--pageUrl', page_url]
  232. if play_path is not None:
  233. basic_args += ['--playpath', play_path]
  234. if tc_url is not None:
  235. basic_args += ['--tcUrl', url]
  236. args = basic_args + [[], ['--resume', '--skip', '1']][self.params.get('continuedl', False)]
  237. if self.params.get('verbose', False):
  238. try:
  239. import pipes
  240. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  241. except ImportError:
  242. shell_quote = repr
  243. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  244. retval = subprocess.call(args)
  245. while retval == 2 or retval == 1:
  246. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  247. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  248. time.sleep(5.0) # This seems to be needed
  249. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  250. cursize = os.path.getsize(encodeFilename(tmpfilename))
  251. if prevsize == cursize and retval == 1:
  252. break
  253. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  254. if prevsize == cursize and retval == 2 and cursize > 1024:
  255. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  256. retval = 0
  257. break
  258. if retval == 0:
  259. fsize = os.path.getsize(encodeFilename(tmpfilename))
  260. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  261. self.try_rename(tmpfilename, filename)
  262. self._hook_progress({
  263. 'downloaded_bytes': fsize,
  264. 'total_bytes': fsize,
  265. 'filename': filename,
  266. 'status': 'finished',
  267. })
  268. return True
  269. else:
  270. self.to_stderr(u"\n")
  271. self.report_error(u'rtmpdump exited with code %d' % retval)
  272. return False
  273. def _download_with_mplayer(self, filename, url):
  274. self.report_destination(filename)
  275. tmpfilename = self.temp_name(filename)
  276. args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
  277. # Check for mplayer first
  278. try:
  279. subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  280. except (OSError, IOError):
  281. self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0] )
  282. return False
  283. # Download using mplayer.
  284. retval = subprocess.call(args)
  285. if retval == 0:
  286. fsize = os.path.getsize(encodeFilename(tmpfilename))
  287. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  288. self.try_rename(tmpfilename, filename)
  289. self._hook_progress({
  290. 'downloaded_bytes': fsize,
  291. 'total_bytes': fsize,
  292. 'filename': filename,
  293. 'status': 'finished',
  294. })
  295. return True
  296. else:
  297. self.to_stderr(u"\n")
  298. self.report_error(u'mplayer exited with code %d' % retval)
  299. return False
  300. def _download_m3u8_with_ffmpeg(self, filename, url):
  301. self.report_destination(filename)
  302. tmpfilename = self.temp_name(filename)
  303. args = ['ffmpeg', '-y', '-i', url, '-f', 'mp4', tmpfilename]
  304. # Check for ffmpeg first
  305. try:
  306. subprocess.call(['ffmpeg', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  307. except (OSError, IOError):
  308. self.report_error(u'm3u8 download detected but "%s" could not be run' % args[0] )
  309. return False
  310. retval = subprocess.call(args)
  311. if retval == 0:
  312. fsize = os.path.getsize(encodeFilename(tmpfilename))
  313. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  314. self.try_rename(tmpfilename, filename)
  315. self._hook_progress({
  316. 'downloaded_bytes': fsize,
  317. 'total_bytes': fsize,
  318. 'filename': filename,
  319. 'status': 'finished',
  320. })
  321. return True
  322. else:
  323. self.to_stderr(u"\n")
  324. self.report_error(u'ffmpeg exited with code %d' % retval)
  325. return False
  326. def _do_download(self, filename, info_dict):
  327. url = info_dict['url']
  328. # Check file already present
  329. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  330. self.report_file_already_downloaded(filename)
  331. self._hook_progress({
  332. 'filename': filename,
  333. 'status': 'finished',
  334. })
  335. return True
  336. # Attempt to download using rtmpdump
  337. if url.startswith('rtmp'):
  338. return self._download_with_rtmpdump(filename, url,
  339. info_dict.get('player_url', None),
  340. info_dict.get('page_url', None),
  341. info_dict.get('play_path', None),
  342. info_dict.get('tc_url', None))
  343. # Attempt to download using mplayer
  344. if url.startswith('mms') or url.startswith('rtsp'):
  345. return self._download_with_mplayer(filename, url)
  346. # m3u8 manifest are downloaded with ffmpeg
  347. if determine_ext(url) == u'm3u8':
  348. return self._download_m3u8_with_ffmpeg(filename, url)
  349. tmpfilename = self.temp_name(filename)
  350. stream = None
  351. # Do not include the Accept-Encoding header
  352. headers = {'Youtubedl-no-compression': 'True'}
  353. if 'user_agent' in info_dict:
  354. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  355. basic_request = compat_urllib_request.Request(url, None, headers)
  356. request = compat_urllib_request.Request(url, None, headers)
  357. if self.params.get('test', False):
  358. request.add_header('Range','bytes=0-10240')
  359. # Establish possible resume length
  360. if os.path.isfile(encodeFilename(tmpfilename)):
  361. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  362. else:
  363. resume_len = 0
  364. open_mode = 'wb'
  365. if resume_len != 0:
  366. if self.params.get('continuedl', False):
  367. self.report_resuming_byte(resume_len)
  368. request.add_header('Range','bytes=%d-' % resume_len)
  369. open_mode = 'ab'
  370. else:
  371. resume_len = 0
  372. count = 0
  373. retries = self.params.get('retries', 0)
  374. while count <= retries:
  375. # Establish connection
  376. try:
  377. if count == 0 and 'urlhandle' in info_dict:
  378. data = info_dict['urlhandle']
  379. data = compat_urllib_request.urlopen(request)
  380. break
  381. except (compat_urllib_error.HTTPError, ) as err:
  382. if (err.code < 500 or err.code >= 600) and err.code != 416:
  383. # Unexpected HTTP error
  384. raise
  385. elif err.code == 416:
  386. # Unable to resume (requested range not satisfiable)
  387. try:
  388. # Open the connection again without the range header
  389. data = compat_urllib_request.urlopen(basic_request)
  390. content_length = data.info()['Content-Length']
  391. except (compat_urllib_error.HTTPError, ) as err:
  392. if err.code < 500 or err.code >= 600:
  393. raise
  394. else:
  395. # Examine the reported length
  396. if (content_length is not None and
  397. (resume_len - 100 < int(content_length) < resume_len + 100)):
  398. # The file had already been fully downloaded.
  399. # Explanation to the above condition: in issue #175 it was revealed that
  400. # YouTube sometimes adds or removes a few bytes from the end of the file,
  401. # changing the file size slightly and causing problems for some users. So
  402. # I decided to implement a suggested change and consider the file
  403. # completely downloaded if the file size differs less than 100 bytes from
  404. # the one in the hard drive.
  405. self.report_file_already_downloaded(filename)
  406. self.try_rename(tmpfilename, filename)
  407. self._hook_progress({
  408. 'filename': filename,
  409. 'status': 'finished',
  410. })
  411. return True
  412. else:
  413. # The length does not match, we start the download over
  414. self.report_unable_to_resume()
  415. open_mode = 'wb'
  416. break
  417. # Retry
  418. count += 1
  419. if count <= retries:
  420. self.report_retry(count, retries)
  421. if count > retries:
  422. self.report_error(u'giving up after %s retries' % retries)
  423. return False
  424. data_len = data.info().get('Content-length', None)
  425. if data_len is not None:
  426. data_len = int(data_len) + resume_len
  427. min_data_len = self.params.get("min_filesize", None)
  428. max_data_len = self.params.get("max_filesize", None)
  429. if min_data_len is not None and data_len < min_data_len:
  430. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  431. return False
  432. if max_data_len is not None and data_len > max_data_len:
  433. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  434. return False
  435. data_len_str = self.format_bytes(data_len)
  436. byte_counter = 0 + resume_len
  437. block_size = self.params.get('buffersize', 1024)
  438. start = time.time()
  439. while True:
  440. # Download and write
  441. before = time.time()
  442. data_block = data.read(block_size)
  443. after = time.time()
  444. if len(data_block) == 0:
  445. break
  446. byte_counter += len(data_block)
  447. # Open file just in time
  448. if stream is None:
  449. try:
  450. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  451. assert stream is not None
  452. filename = self.undo_temp_name(tmpfilename)
  453. self.report_destination(filename)
  454. except (OSError, IOError) as err:
  455. self.report_error(u'unable to open for writing: %s' % str(err))
  456. return False
  457. try:
  458. stream.write(data_block)
  459. except (IOError, OSError) as err:
  460. self.to_stderr(u"\n")
  461. self.report_error(u'unable to write data: %s' % str(err))
  462. return False
  463. if not self.params.get('noresizebuffer', False):
  464. block_size = self.best_block_size(after - before, len(data_block))
  465. # Progress message
  466. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  467. if data_len is None:
  468. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  469. else:
  470. percent_str = self.calc_percent(byte_counter, data_len)
  471. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  472. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  473. self._hook_progress({
  474. 'downloaded_bytes': byte_counter,
  475. 'total_bytes': data_len,
  476. 'tmpfilename': tmpfilename,
  477. 'filename': filename,
  478. 'status': 'downloading',
  479. })
  480. # Apply rate limit
  481. self.slow_down(start, byte_counter - resume_len)
  482. if stream is None:
  483. self.to_stderr(u"\n")
  484. self.report_error(u'Did not get any data blocks')
  485. return False
  486. stream.close()
  487. self.report_finish(data_len_str, (time.time() - start))
  488. if data_len is not None and byte_counter != data_len:
  489. raise ContentTooShortError(byte_counter, int(data_len))
  490. self.try_rename(tmpfilename, filename)
  491. # Update file modification time
  492. if self.params.get('updatetime', True):
  493. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  494. self._hook_progress({
  495. 'downloaded_bytes': byte_counter,
  496. 'total_bytes': byte_counter,
  497. 'filename': filename,
  498. 'status': 'finished',
  499. })
  500. return True
  501. def _hook_progress(self, status):
  502. for ph in self._progress_hooks:
  503. ph(status)
  504. def add_progress_hook(self, ph):
  505. """ ph gets called on download progress, with a dictionary with the entries
  506. * filename: The final filename
  507. * status: One of "downloading" and "finished"
  508. It can also have some of the following entries:
  509. * downloaded_bytes: Bytes on disks
  510. * total_bytes: Total bytes, None if unknown
  511. * tmpfilename: The filename we're currently writing to
  512. Hooks are guaranteed to be called at least once (with status "finished")
  513. if the download is successful.
  514. """
  515. self._progress_hooks.append(ph)