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.

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