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.

616 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. test = self.params.get('test', False)
  235. # Check for rtmpdump first
  236. try:
  237. subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  238. except (OSError, IOError):
  239. self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
  240. return False
  241. verbosity_option = '--verbose' if self.params.get('verbose', False) else '--quiet'
  242. # Download using rtmpdump. rtmpdump returns exit code 2 when
  243. # the connection was interrumpted and resuming appears to be
  244. # possible. This is part of rtmpdump's normal usage, AFAIK.
  245. basic_args = ['rtmpdump', verbosity_option, '-r', url, '-o', tmpfilename]
  246. if player_url is not None:
  247. basic_args += ['--swfVfy', player_url]
  248. if page_url is not None:
  249. basic_args += ['--pageUrl', page_url]
  250. if play_path is not None:
  251. basic_args += ['--playpath', play_path]
  252. if tc_url is not None:
  253. basic_args += ['--tcUrl', url]
  254. if test:
  255. basic_args += ['--stop', '1']
  256. args = basic_args + [[], ['--resume', '--skip', '1']][self.params.get('continuedl', False)]
  257. if self.params.get('verbose', False):
  258. try:
  259. import pipes
  260. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  261. except ImportError:
  262. shell_quote = repr
  263. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  264. retval = subprocess.call(args)
  265. while (retval == 2 or retval == 1) and not test:
  266. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  267. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  268. time.sleep(5.0) # This seems to be needed
  269. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  270. cursize = os.path.getsize(encodeFilename(tmpfilename))
  271. if prevsize == cursize and retval == 1:
  272. break
  273. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  274. if prevsize == cursize and retval == 2 and cursize > 1024:
  275. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  276. retval = 0
  277. break
  278. if retval == 0 or (test and retval == 2):
  279. fsize = os.path.getsize(encodeFilename(tmpfilename))
  280. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  281. self.try_rename(tmpfilename, filename)
  282. self._hook_progress({
  283. 'downloaded_bytes': fsize,
  284. 'total_bytes': fsize,
  285. 'filename': filename,
  286. 'status': 'finished',
  287. })
  288. return True
  289. else:
  290. self.to_stderr(u"\n")
  291. self.report_error(u'rtmpdump exited with code %d' % retval)
  292. return False
  293. def _download_with_mplayer(self, filename, url):
  294. self.report_destination(filename)
  295. tmpfilename = self.temp_name(filename)
  296. args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
  297. # Check for mplayer first
  298. try:
  299. subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  300. except (OSError, IOError):
  301. self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0] )
  302. return False
  303. # Download using mplayer.
  304. retval = subprocess.call(args)
  305. if retval == 0:
  306. fsize = os.path.getsize(encodeFilename(tmpfilename))
  307. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  308. self.try_rename(tmpfilename, filename)
  309. self._hook_progress({
  310. 'downloaded_bytes': fsize,
  311. 'total_bytes': fsize,
  312. 'filename': filename,
  313. 'status': 'finished',
  314. })
  315. return True
  316. else:
  317. self.to_stderr(u"\n")
  318. self.report_error(u'mplayer exited with code %d' % retval)
  319. return False
  320. def _download_m3u8_with_ffmpeg(self, filename, url):
  321. self.report_destination(filename)
  322. tmpfilename = self.temp_name(filename)
  323. args = ['ffmpeg', '-y', '-i', url, '-f', 'mp4', tmpfilename]
  324. # Check for ffmpeg first
  325. try:
  326. subprocess.call(['ffmpeg', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  327. except (OSError, IOError):
  328. self.report_error(u'm3u8 download detected but "%s" could not be run' % args[0] )
  329. return False
  330. retval = subprocess.call(args)
  331. if retval == 0:
  332. fsize = os.path.getsize(encodeFilename(tmpfilename))
  333. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  334. self.try_rename(tmpfilename, filename)
  335. self._hook_progress({
  336. 'downloaded_bytes': fsize,
  337. 'total_bytes': fsize,
  338. 'filename': filename,
  339. 'status': 'finished',
  340. })
  341. return True
  342. else:
  343. self.to_stderr(u"\n")
  344. self.report_error(u'ffmpeg exited with code %d' % retval)
  345. return False
  346. def _do_download(self, filename, info_dict):
  347. url = info_dict['url']
  348. # Check file already present
  349. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  350. self.report_file_already_downloaded(filename)
  351. self._hook_progress({
  352. 'filename': filename,
  353. 'status': 'finished',
  354. 'total_bytes': os.path.getsize(encodeFilename(filename)),
  355. })
  356. return True
  357. # Attempt to download using rtmpdump
  358. if url.startswith('rtmp'):
  359. return self._download_with_rtmpdump(filename, url,
  360. info_dict.get('player_url', None),
  361. info_dict.get('page_url', None),
  362. info_dict.get('play_path', None),
  363. info_dict.get('tc_url', None))
  364. # Attempt to download using mplayer
  365. if url.startswith('mms') or url.startswith('rtsp'):
  366. return self._download_with_mplayer(filename, url)
  367. # m3u8 manifest are downloaded with ffmpeg
  368. if determine_ext(url) == u'm3u8':
  369. return self._download_m3u8_with_ffmpeg(filename, url)
  370. tmpfilename = self.temp_name(filename)
  371. stream = None
  372. # Do not include the Accept-Encoding header
  373. headers = {'Youtubedl-no-compression': 'True'}
  374. if 'user_agent' in info_dict:
  375. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  376. basic_request = compat_urllib_request.Request(url, None, headers)
  377. request = compat_urllib_request.Request(url, None, headers)
  378. if self.params.get('test', False):
  379. request.add_header('Range','bytes=0-10240')
  380. # Establish possible resume length
  381. if os.path.isfile(encodeFilename(tmpfilename)):
  382. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  383. else:
  384. resume_len = 0
  385. open_mode = 'wb'
  386. if resume_len != 0:
  387. if self.params.get('continuedl', False):
  388. self.report_resuming_byte(resume_len)
  389. request.add_header('Range','bytes=%d-' % resume_len)
  390. open_mode = 'ab'
  391. else:
  392. resume_len = 0
  393. count = 0
  394. retries = self.params.get('retries', 0)
  395. while count <= retries:
  396. # Establish connection
  397. try:
  398. if count == 0 and 'urlhandle' in info_dict:
  399. data = info_dict['urlhandle']
  400. data = compat_urllib_request.urlopen(request)
  401. break
  402. except (compat_urllib_error.HTTPError, ) as err:
  403. if (err.code < 500 or err.code >= 600) and err.code != 416:
  404. # Unexpected HTTP error
  405. raise
  406. elif err.code == 416:
  407. # Unable to resume (requested range not satisfiable)
  408. try:
  409. # Open the connection again without the range header
  410. data = compat_urllib_request.urlopen(basic_request)
  411. content_length = data.info()['Content-Length']
  412. except (compat_urllib_error.HTTPError, ) as err:
  413. if err.code < 500 or err.code >= 600:
  414. raise
  415. else:
  416. # Examine the reported length
  417. if (content_length is not None and
  418. (resume_len - 100 < int(content_length) < resume_len + 100)):
  419. # The file had already been fully downloaded.
  420. # Explanation to the above condition: in issue #175 it was revealed that
  421. # YouTube sometimes adds or removes a few bytes from the end of the file,
  422. # changing the file size slightly and causing problems for some users. So
  423. # I decided to implement a suggested change and consider the file
  424. # completely downloaded if the file size differs less than 100 bytes from
  425. # the one in the hard drive.
  426. self.report_file_already_downloaded(filename)
  427. self.try_rename(tmpfilename, filename)
  428. self._hook_progress({
  429. 'filename': filename,
  430. 'status': 'finished',
  431. })
  432. return True
  433. else:
  434. # The length does not match, we start the download over
  435. self.report_unable_to_resume()
  436. open_mode = 'wb'
  437. break
  438. # Retry
  439. count += 1
  440. if count <= retries:
  441. self.report_retry(count, retries)
  442. if count > retries:
  443. self.report_error(u'giving up after %s retries' % retries)
  444. return False
  445. data_len = data.info().get('Content-length', None)
  446. if data_len is not None:
  447. data_len = int(data_len) + resume_len
  448. min_data_len = self.params.get("min_filesize", None)
  449. max_data_len = self.params.get("max_filesize", None)
  450. if min_data_len is not None and data_len < min_data_len:
  451. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  452. return False
  453. if max_data_len is not None and data_len > max_data_len:
  454. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  455. return False
  456. data_len_str = self.format_bytes(data_len)
  457. byte_counter = 0 + resume_len
  458. block_size = self.params.get('buffersize', 1024)
  459. start = time.time()
  460. while True:
  461. # Download and write
  462. before = time.time()
  463. data_block = data.read(block_size)
  464. after = time.time()
  465. if len(data_block) == 0:
  466. break
  467. byte_counter += len(data_block)
  468. # Open file just in time
  469. if stream is None:
  470. try:
  471. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  472. assert stream is not None
  473. filename = self.undo_temp_name(tmpfilename)
  474. self.report_destination(filename)
  475. except (OSError, IOError) as err:
  476. self.report_error(u'unable to open for writing: %s' % str(err))
  477. return False
  478. try:
  479. stream.write(data_block)
  480. except (IOError, OSError) as err:
  481. self.to_stderr(u"\n")
  482. self.report_error(u'unable to write data: %s' % str(err))
  483. return False
  484. if not self.params.get('noresizebuffer', False):
  485. block_size = self.best_block_size(after - before, len(data_block))
  486. # Progress message
  487. speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
  488. if data_len is None:
  489. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  490. eta = None
  491. else:
  492. percent = self.calc_percent(byte_counter, data_len)
  493. eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  494. self.report_progress(percent, data_len_str, speed, eta)
  495. self._hook_progress({
  496. 'downloaded_bytes': byte_counter,
  497. 'total_bytes': data_len,
  498. 'tmpfilename': tmpfilename,
  499. 'filename': filename,
  500. 'status': 'downloading',
  501. 'eta': eta,
  502. 'speed': speed,
  503. })
  504. # Apply rate limit
  505. self.slow_down(start, byte_counter - resume_len)
  506. if stream is None:
  507. self.to_stderr(u"\n")
  508. self.report_error(u'Did not get any data blocks')
  509. return False
  510. stream.close()
  511. self.report_finish(data_len_str, (time.time() - start))
  512. if data_len is not None and byte_counter != data_len:
  513. raise ContentTooShortError(byte_counter, int(data_len))
  514. self.try_rename(tmpfilename, filename)
  515. # Update file modification time
  516. if self.params.get('updatetime', True):
  517. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  518. self._hook_progress({
  519. 'downloaded_bytes': byte_counter,
  520. 'total_bytes': byte_counter,
  521. 'filename': filename,
  522. 'status': 'finished',
  523. })
  524. return True
  525. def _hook_progress(self, status):
  526. for ph in self._progress_hooks:
  527. ph(status)
  528. def add_progress_hook(self, ph):
  529. """ ph gets called on download progress, with a dictionary with the entries
  530. * filename: The final filename
  531. * status: One of "downloading" and "finished"
  532. It can also have some of the following entries:
  533. * downloaded_bytes: Bytes on disks
  534. * total_bytes: Total bytes, None if unknown
  535. * tmpfilename: The filename we're currently writing to
  536. * eta: The estimated time in seconds, None if unknown
  537. * speed: The download speed in bytes/second, None if unknown
  538. Hooks are guaranteed to be called at least once (with status "finished")
  539. if the download is successful.
  540. """
  541. self._progress_hooks.append(ph)