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.

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