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.

968 lines
41 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import math
  5. import io
  6. import os
  7. import re
  8. import socket
  9. import subprocess
  10. import sys
  11. import time
  12. import traceback
  13. if os.name == 'nt':
  14. import ctypes
  15. from .utils import *
  16. class FileDownloader(object):
  17. """File Downloader class.
  18. File downloader objects are the ones responsible of downloading the
  19. actual video file and writing it to disk if the user has requested
  20. it, among some other tasks. In most cases there should be one per
  21. program. As, given a video URL, the downloader doesn't know how to
  22. extract all the needed information, task that InfoExtractors do, it
  23. has to pass the URL to one of them.
  24. For this, file downloader objects have a method that allows
  25. InfoExtractors to be registered in a given order. When it is passed
  26. a URL, the file downloader handles it to the first InfoExtractor it
  27. finds that reports being able to handle it. The InfoExtractor extracts
  28. all the information about the video or videos the URL refers to, and
  29. asks the FileDownloader to process the video information, possibly
  30. downloading the video.
  31. File downloaders accept a lot of parameters. In order not to saturate
  32. the object constructor with arguments, it receives a dictionary of
  33. options instead. These options are available through the params
  34. attribute for the InfoExtractors to use. The FileDownloader also
  35. registers itself as the downloader in charge for the InfoExtractors
  36. that are added to it, so this is a "mutual registration".
  37. Available options:
  38. username: Username for authentication purposes.
  39. password: Password for authentication purposes.
  40. usenetrc: Use netrc for authentication instead.
  41. quiet: Do not print messages to stdout.
  42. forceurl: Force printing final URL.
  43. forcetitle: Force printing title.
  44. forcethumbnail: Force printing thumbnail URL.
  45. forcedescription: Force printing description.
  46. forcefilename: Force printing final filename.
  47. simulate: Do not download the video files.
  48. format: Video format code.
  49. format_limit: Highest quality format to try.
  50. outtmpl: Template for output names.
  51. restrictfilenames: Do not allow "&" and spaces in file names
  52. ignoreerrors: Do not stop on download errors.
  53. ratelimit: Download speed limit, in bytes/sec.
  54. nooverwrites: Prevent overwriting files.
  55. retries: Number of times to retry for HTTP error 5xx
  56. buffersize: Size of download buffer in bytes.
  57. noresizebuffer: Do not automatically resize the download buffer.
  58. continuedl: Try to continue downloads if possible.
  59. noprogress: Do not print the progress bar.
  60. playliststart: Playlist item to start at.
  61. playlistend: Playlist item to end at.
  62. matchtitle: Download only matching titles.
  63. rejecttitle: Reject downloads for matching titles.
  64. logtostderr: Log messages to stderr instead of stdout.
  65. consoletitle: Display progress in console window's titlebar.
  66. nopart: Do not use temporary .part files.
  67. updatetime: Use the Last-modified header to set output file timestamps.
  68. writedescription: Write the video description to a .description file
  69. writeinfojson: Write the video description to a .info.json file
  70. writesubtitles: Write the video subtitles to a file
  71. onlysubtitles: Downloads only the subtitles of the video
  72. allsubtitles: Downloads all the subtitles of the video
  73. listsubtitles: Lists all available subtitles for the video
  74. subtitlesformat: Subtitle format [sbv/srt] (default=srt)
  75. subtitleslang: Language of the subtitles to download
  76. test: Download only first bytes to test the downloader.
  77. keepvideo: Keep the video file after post-processing
  78. min_filesize: Skip files smaller than this size
  79. max_filesize: Skip files larger than this size
  80. """
  81. params = None
  82. _ies = []
  83. _pps = []
  84. _download_retcode = None
  85. _num_downloads = None
  86. _screen_file = None
  87. def __init__(self, params):
  88. """Create a FileDownloader object with the given options."""
  89. self._ies = []
  90. self._pps = []
  91. self._progress_hooks = []
  92. self._download_retcode = 0
  93. self._num_downloads = 0
  94. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  95. self.params = params
  96. if '%(stitle)s' in self.params['outtmpl']:
  97. self.report_warning(u'%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  98. @staticmethod
  99. def format_bytes(bytes):
  100. if bytes is None:
  101. return 'N/A'
  102. if type(bytes) is str:
  103. bytes = float(bytes)
  104. if bytes == 0.0:
  105. exponent = 0
  106. else:
  107. exponent = int(math.log(bytes, 1024.0))
  108. suffix = 'bkMGTPEZY'[exponent]
  109. converted = float(bytes) / float(1024 ** exponent)
  110. return '%.2f%s' % (converted, suffix)
  111. @staticmethod
  112. def calc_percent(byte_counter, data_len):
  113. if data_len is None:
  114. return '---.-%'
  115. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  116. @staticmethod
  117. def calc_eta(start, now, total, current):
  118. if total is None:
  119. return '--:--'
  120. dif = now - start
  121. if current == 0 or dif < 0.001: # One millisecond
  122. return '--:--'
  123. rate = float(current) / dif
  124. eta = int((float(total) - float(current)) / rate)
  125. (eta_mins, eta_secs) = divmod(eta, 60)
  126. if eta_mins > 99:
  127. return '--:--'
  128. return '%02d:%02d' % (eta_mins, eta_secs)
  129. @staticmethod
  130. def calc_speed(start, now, bytes):
  131. dif = now - start
  132. if bytes == 0 or dif < 0.001: # One millisecond
  133. return '%10s' % '---b/s'
  134. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  135. @staticmethod
  136. def best_block_size(elapsed_time, bytes):
  137. new_min = max(bytes / 2.0, 1.0)
  138. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  139. if elapsed_time < 0.001:
  140. return int(new_max)
  141. rate = bytes / elapsed_time
  142. if rate > new_max:
  143. return int(new_max)
  144. if rate < new_min:
  145. return int(new_min)
  146. return int(rate)
  147. @staticmethod
  148. def parse_bytes(bytestr):
  149. """Parse a string indicating a byte quantity into an integer."""
  150. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  151. if matchobj is None:
  152. return None
  153. number = float(matchobj.group(1))
  154. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  155. return int(round(number * multiplier))
  156. def add_info_extractor(self, ie):
  157. """Add an InfoExtractor object to the end of the list."""
  158. self._ies.append(ie)
  159. ie.set_downloader(self)
  160. def add_post_processor(self, pp):
  161. """Add a PostProcessor object to the end of the chain."""
  162. self._pps.append(pp)
  163. pp.set_downloader(self)
  164. def to_screen(self, message, skip_eol=False):
  165. """Print message to stdout if not in quiet mode."""
  166. assert type(message) == type(u'')
  167. if not self.params.get('quiet', False):
  168. terminator = [u'\n', u''][skip_eol]
  169. output = message + terminator
  170. if 'b' in getattr(self._screen_file, 'mode', '') or sys.version_info[0] < 3: # Python 2 lies about the mode of sys.stdout/sys.stderr
  171. output = output.encode(preferredencoding(), 'ignore')
  172. self._screen_file.write(output)
  173. self._screen_file.flush()
  174. def to_stderr(self, message):
  175. """Print message to stderr."""
  176. assert type(message) == type(u'')
  177. output = message + u'\n'
  178. if 'b' in getattr(self._screen_file, 'mode', '') or sys.version_info[0] < 3: # Python 2 lies about the mode of sys.stdout/sys.stderr
  179. output = output.encode(preferredencoding())
  180. sys.stderr.write(output)
  181. def to_cons_title(self, message):
  182. """Set console/terminal window title to message."""
  183. if not self.params.get('consoletitle', False):
  184. return
  185. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  186. # c_wchar_p() might not be necessary if `message` is
  187. # already of type unicode()
  188. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  189. elif 'TERM' in os.environ:
  190. self.to_screen('\033]0;%s\007' % message, skip_eol=True)
  191. def fixed_template(self):
  192. """Checks if the output template is fixed."""
  193. return (re.search(u'(?u)%\\(.+?\\)s', self.params['outtmpl']) is None)
  194. def trouble(self, message=None, tb=None):
  195. """Determine action to take when a download problem appears.
  196. Depending on if the downloader has been configured to ignore
  197. download errors or not, this method may throw an exception or
  198. not when errors are found, after printing the message.
  199. tb, if given, is additional traceback information.
  200. """
  201. if message is not None:
  202. self.to_stderr(message)
  203. if self.params.get('verbose'):
  204. if tb is None:
  205. if sys.exc_info()[0]: # if .trouble has been called from an except block
  206. tb = u''
  207. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  208. tb += u''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  209. tb += compat_str(traceback.format_exc())
  210. else:
  211. tb_data = traceback.format_list(traceback.extract_stack())
  212. tb = u''.join(tb_data)
  213. self.to_stderr(tb)
  214. if not self.params.get('ignoreerrors', False):
  215. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  216. exc_info = sys.exc_info()[1].exc_info
  217. else:
  218. exc_info = sys.exc_info()
  219. raise DownloadError(message, exc_info)
  220. self._download_retcode = 1
  221. def report_warning(self, message):
  222. '''
  223. Print the message to stderr, it will be prefixed with 'WARNING:'
  224. If stderr is a tty file the 'WARNING:' will be colored
  225. '''
  226. if sys.stderr.isatty():
  227. _msg_header=u'\033[0;33mWARNING:\033[0m'
  228. else:
  229. _msg_header=u'WARNING:'
  230. warning_message=u'%s %s' % (_msg_header,message)
  231. self.to_stderr(warning_message)
  232. def report_error(self, message, tb=None):
  233. '''
  234. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  235. in red if stderr is a tty file.
  236. '''
  237. if sys.stderr.isatty():
  238. _msg_header = u'\033[0;31mERROR:\033[0m'
  239. else:
  240. _msg_header = u'ERROR:'
  241. error_message = u'%s %s' % (_msg_header, message)
  242. self.trouble(error_message, tb)
  243. def slow_down(self, start_time, byte_counter):
  244. """Sleep if the download speed is over the rate limit."""
  245. rate_limit = self.params.get('ratelimit', None)
  246. if rate_limit is None or byte_counter == 0:
  247. return
  248. now = time.time()
  249. elapsed = now - start_time
  250. if elapsed <= 0.0:
  251. return
  252. speed = float(byte_counter) / elapsed
  253. if speed > rate_limit:
  254. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  255. def temp_name(self, filename):
  256. """Returns a temporary filename for the given filename."""
  257. if self.params.get('nopart', False) or filename == u'-' or \
  258. (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
  259. return filename
  260. return filename + u'.part'
  261. def undo_temp_name(self, filename):
  262. if filename.endswith(u'.part'):
  263. return filename[:-len(u'.part')]
  264. return filename
  265. def try_rename(self, old_filename, new_filename):
  266. try:
  267. if old_filename == new_filename:
  268. return
  269. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  270. except (IOError, OSError) as err:
  271. self.report_error(u'unable to rename file')
  272. def try_utime(self, filename, last_modified_hdr):
  273. """Try to set the last-modified time of the given file."""
  274. if last_modified_hdr is None:
  275. return
  276. if not os.path.isfile(encodeFilename(filename)):
  277. return
  278. timestr = last_modified_hdr
  279. if timestr is None:
  280. return
  281. filetime = timeconvert(timestr)
  282. if filetime is None:
  283. return filetime
  284. try:
  285. os.utime(filename, (time.time(), filetime))
  286. except:
  287. pass
  288. return filetime
  289. def report_writedescription(self, descfn):
  290. """ Report that the description file is being written """
  291. self.to_screen(u'[info] Writing video description to: ' + descfn)
  292. def report_writesubtitles(self, sub_filename):
  293. """ Report that the subtitles file is being written """
  294. self.to_screen(u'[info] Writing video subtitles to: ' + sub_filename)
  295. def report_writeinfojson(self, infofn):
  296. """ Report that the metadata file has been written """
  297. self.to_screen(u'[info] Video description metadata as JSON to: ' + infofn)
  298. def report_destination(self, filename):
  299. """Report destination filename."""
  300. self.to_screen(u'[download] Destination: ' + filename)
  301. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  302. """Report download progress."""
  303. if self.params.get('noprogress', False):
  304. return
  305. if self.params.get('progress_with_newline', False):
  306. self.to_screen(u'[download] %s of %s at %s ETA %s' %
  307. (percent_str, data_len_str, speed_str, eta_str))
  308. else:
  309. self.to_screen(u'\r[download] %s of %s at %s ETA %s' %
  310. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  311. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  312. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  313. def report_resuming_byte(self, resume_len):
  314. """Report attempt to resume at given byte."""
  315. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  316. def report_retry(self, count, retries):
  317. """Report retry in case of HTTP error 5xx"""
  318. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  319. def report_file_already_downloaded(self, file_name):
  320. """Report file has already been fully downloaded."""
  321. try:
  322. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  323. except (UnicodeEncodeError) as err:
  324. self.to_screen(u'[download] The file has already been downloaded')
  325. def report_unable_to_resume(self):
  326. """Report it was impossible to resume download."""
  327. self.to_screen(u'[download] Unable to resume')
  328. def report_finish(self):
  329. """Report download finished."""
  330. if self.params.get('noprogress', False):
  331. self.to_screen(u'[download] Download completed')
  332. else:
  333. self.to_screen(u'')
  334. def increment_downloads(self):
  335. """Increment the ordinal that assigns a number to each file."""
  336. self._num_downloads += 1
  337. def prepare_filename(self, info_dict):
  338. """Generate the output filename."""
  339. try:
  340. template_dict = dict(info_dict)
  341. template_dict['epoch'] = int(time.time())
  342. autonumber_size = self.params.get('autonumber_size')
  343. if autonumber_size is None:
  344. autonumber_size = 5
  345. autonumber_templ = u'%0' + str(autonumber_size) + u'd'
  346. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  347. if template_dict['playlist_index'] is not None:
  348. template_dict['playlist_index'] = u'%05d' % template_dict['playlist_index']
  349. sanitize = lambda k,v: sanitize_filename(
  350. u'NA' if v is None else compat_str(v),
  351. restricted=self.params.get('restrictfilenames'),
  352. is_id=(k==u'id'))
  353. template_dict = dict((k, sanitize(k, v)) for k,v in template_dict.items())
  354. filename = self.params['outtmpl'] % template_dict
  355. return filename
  356. except KeyError as err:
  357. self.trouble(u'ERROR: Erroneous output template')
  358. return None
  359. except ValueError as err:
  360. self.trouble(u'ERROR: Insufficient system charset ' + repr(preferredencoding()))
  361. return None
  362. def _match_entry(self, info_dict):
  363. """ Returns None iff the file should be downloaded """
  364. title = info_dict['title']
  365. matchtitle = self.params.get('matchtitle', False)
  366. if matchtitle:
  367. if not re.search(matchtitle, title, re.IGNORECASE):
  368. return u'[download] "' + title + '" title did not match pattern "' + matchtitle + '"'
  369. rejecttitle = self.params.get('rejecttitle', False)
  370. if rejecttitle:
  371. if re.search(rejecttitle, title, re.IGNORECASE):
  372. return u'"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  373. return None
  374. def extract_info(self, url, download = True):
  375. '''
  376. Returns a list with a dictionary for each video we find.
  377. If 'download', also downloads the videos.
  378. '''
  379. suitable_found = False
  380. for ie in self._ies:
  381. # Go to next InfoExtractor if not suitable
  382. if not ie.suitable(url):
  383. continue
  384. # Warn if the _WORKING attribute is False
  385. if not ie.working():
  386. self.to_stderr(u'WARNING: the program functionality for this site has been marked as broken, '
  387. u'and will probably not work. If you want to go on, use the -i option.')
  388. # Suitable InfoExtractor found
  389. suitable_found = True
  390. # Extract information from URL and process it
  391. try:
  392. ie_results = ie.extract(url)
  393. results = []
  394. for ie_result in ie_results:
  395. if not 'extractor' in ie_result:
  396. #The extractor has already been set somewhere else
  397. ie_result['extractor'] = ie.IE_NAME
  398. results.append(self.process_ie_result(ie_result, download))
  399. return results
  400. except ExtractorError as de: # An error we somewhat expected
  401. self.trouble(u'ERROR: ' + compat_str(de), de.format_traceback())
  402. break
  403. except Exception as e:
  404. if self.params.get('ignoreerrors', False):
  405. self.trouble(u'ERROR: ' + compat_str(e), tb=compat_str(traceback.format_exc()))
  406. break
  407. else:
  408. raise
  409. if not suitable_found:
  410. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  411. def process_ie_result(self, ie_result, download = True):
  412. """
  413. Take the result of the ie and return a list of videos.
  414. For url elements it will search the suitable ie and get the videos
  415. For playlist elements it will process each of the elements of the 'entries' key
  416. It will also download the videos if 'download'.
  417. """
  418. result_type = ie_result.get('_type', 'video') #If not given we suppose it's a video, support the dafault old system
  419. if result_type == 'video':
  420. if 'playlist' not in ie_result:
  421. #It isn't part of a playlist
  422. ie_result['playlist'] = None
  423. ie_result['playlist_index'] = None
  424. if download:
  425. #Do the download:
  426. self.process_info(ie_result)
  427. return ie_result
  428. elif result_type == 'url':
  429. #We get the video pointed by the url
  430. result = self.extract_info(ie_result['url'], download)[0]
  431. return result
  432. elif result_type == 'playlist':
  433. #We process each entry in the playlist
  434. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  435. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  436. playlist_results = []
  437. n_all_entries = len(ie_result['entries'])
  438. playliststart = self.params.get('playliststart', 1) - 1
  439. playlistend = self.params.get('playlistend', -1)
  440. if playlistend == -1:
  441. entries = ie_result['entries'][playliststart:]
  442. else:
  443. entries = ie_result['entries'][playliststart:playlistend]
  444. n_entries = len(entries)
  445. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  446. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  447. for i,entry in enumerate(entries,1):
  448. self.to_screen(u'[download] Downloading video #%s of %s' %(i, n_entries))
  449. entry_result = self.process_ie_result(entry, False)
  450. entry_result['playlist'] = playlist
  451. entry_result['playlist_index'] = i + playliststart
  452. #We must do the download here to correctly set the 'playlist' key
  453. if download:
  454. self.process_info(entry_result)
  455. playlist_results.append(entry_result)
  456. result = ie_result.copy()
  457. result['entries'] = playlist_results
  458. return result
  459. def process_info(self, info_dict):
  460. """Process a single dictionary returned by an InfoExtractor."""
  461. #We increment the download the download count here to match the previous behaviour.
  462. self.increment_downloads()
  463. info_dict['fulltitle'] = info_dict['title']
  464. if len(info_dict['title']) > 200:
  465. info_dict['title'] = info_dict['title'][:197] + u'...'
  466. # Keep for backwards compatibility
  467. info_dict['stitle'] = info_dict['title']
  468. if not 'format' in info_dict:
  469. info_dict['format'] = info_dict['ext']
  470. reason = self._match_entry(info_dict)
  471. if reason is not None:
  472. self.to_screen(u'[download] ' + reason)
  473. return
  474. max_downloads = self.params.get('max_downloads')
  475. if max_downloads is not None:
  476. if self._num_downloads > int(max_downloads):
  477. raise MaxDownloadsReached()
  478. filename = self.prepare_filename(info_dict)
  479. # Forced printings
  480. if self.params.get('forcetitle', False):
  481. compat_print(info_dict['title'])
  482. if self.params.get('forceurl', False):
  483. compat_print(info_dict['url'])
  484. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  485. compat_print(info_dict['thumbnail'])
  486. if self.params.get('forcedescription', False) and 'description' in info_dict:
  487. compat_print(info_dict['description'])
  488. if self.params.get('forcefilename', False) and filename is not None:
  489. compat_print(filename)
  490. if self.params.get('forceformat', False):
  491. compat_print(info_dict['format'])
  492. # Do nothing else if in simulate mode
  493. if self.params.get('simulate', False):
  494. return
  495. if filename is None:
  496. return
  497. try:
  498. dn = os.path.dirname(encodeFilename(filename))
  499. if dn != '' and not os.path.exists(dn): # dn is already encoded
  500. os.makedirs(dn)
  501. except (OSError, IOError) as err:
  502. self.report_error(u'unable to create directory ' + compat_str(err))
  503. return
  504. if self.params.get('writedescription', False):
  505. try:
  506. descfn = filename + u'.description'
  507. self.report_writedescription(descfn)
  508. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  509. descfile.write(info_dict['description'])
  510. except (OSError, IOError):
  511. self.report_error(u'Cannot write description file ' + descfn)
  512. return
  513. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  514. # subtitles download errors are already managed as troubles in relevant IE
  515. # that way it will silently go on when used with unsupporting IE
  516. subtitle = info_dict['subtitles'][0]
  517. (sub_error, sub_lang, sub) = subtitle
  518. sub_format = self.params.get('subtitlesformat')
  519. if sub_error:
  520. self.report_warning("Some error while getting the subtitles")
  521. else:
  522. try:
  523. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  524. self.report_writesubtitles(sub_filename)
  525. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  526. subfile.write(sub)
  527. except (OSError, IOError):
  528. self.report_error(u'Cannot write subtitles file ' + descfn)
  529. return
  530. if self.params.get('onlysubtitles', False):
  531. return
  532. if self.params.get('allsubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  533. subtitles = info_dict['subtitles']
  534. sub_format = self.params.get('subtitlesformat')
  535. for subtitle in subtitles:
  536. (sub_error, sub_lang, sub) = subtitle
  537. if sub_error:
  538. self.report_warning("Some error while getting the subtitles")
  539. else:
  540. try:
  541. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  542. self.report_writesubtitles(sub_filename)
  543. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  544. subfile.write(sub)
  545. except (OSError, IOError):
  546. self.trouble(u'ERROR: Cannot write subtitles file ' + descfn)
  547. return
  548. if self.params.get('onlysubtitles', False):
  549. return
  550. if self.params.get('writeinfojson', False):
  551. infofn = filename + u'.info.json'
  552. self.report_writeinfojson(infofn)
  553. try:
  554. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  555. write_json_file(json_info_dict, encodeFilename(infofn))
  556. except (OSError, IOError):
  557. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  558. return
  559. if not self.params.get('skip_download', False):
  560. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  561. success = True
  562. else:
  563. try:
  564. success = self._do_download(filename, info_dict)
  565. except (OSError, IOError) as err:
  566. raise UnavailableVideoError()
  567. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  568. self.report_error(u'unable to download video data: %s' % str(err))
  569. return
  570. except (ContentTooShortError, ) as err:
  571. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  572. return
  573. if success:
  574. try:
  575. self.post_process(filename, info_dict)
  576. except (PostProcessingError) as err:
  577. self.report_error(u'postprocessing: %s' % str(err))
  578. return
  579. def download(self, url_list):
  580. """Download a given list of URLs."""
  581. if len(url_list) > 1 and self.fixed_template():
  582. raise SameFileError(self.params['outtmpl'])
  583. for url in url_list:
  584. try:
  585. #It also downloads the videos
  586. videos = self.extract_info(url)
  587. except UnavailableVideoError:
  588. self.trouble(u'\nERROR: unable to download video')
  589. except MaxDownloadsReached:
  590. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  591. raise
  592. return self._download_retcode
  593. def post_process(self, filename, ie_info):
  594. """Run all the postprocessors on the given file."""
  595. info = dict(ie_info)
  596. info['filepath'] = filename
  597. keep_video = None
  598. for pp in self._pps:
  599. try:
  600. keep_video_wish,new_info = pp.run(info)
  601. if keep_video_wish is not None:
  602. if keep_video_wish:
  603. keep_video = keep_video_wish
  604. elif keep_video is None:
  605. # No clear decision yet, let IE decide
  606. keep_video = keep_video_wish
  607. except PostProcessingError as e:
  608. self.to_stderr(u'ERROR: ' + e.msg)
  609. if keep_video is False and not self.params.get('keepvideo', False):
  610. try:
  611. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  612. os.remove(encodeFilename(filename))
  613. except (IOError, OSError):
  614. self.report_warning(u'Unable to remove downloaded video file')
  615. def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path):
  616. self.report_destination(filename)
  617. tmpfilename = self.temp_name(filename)
  618. # Check for rtmpdump first
  619. try:
  620. subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  621. except (OSError, IOError):
  622. self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
  623. return False
  624. # Download using rtmpdump. rtmpdump returns exit code 2 when
  625. # the connection was interrumpted and resuming appears to be
  626. # possible. This is part of rtmpdump's normal usage, AFAIK.
  627. basic_args = ['rtmpdump', '-q', '-r', url, '-o', tmpfilename]
  628. if player_url is not None:
  629. basic_args += ['-W', player_url]
  630. if page_url is not None:
  631. basic_args += ['--pageUrl', page_url]
  632. if play_path is not None:
  633. basic_args += ['-y', play_path]
  634. args = basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)]
  635. if self.params.get('verbose', False):
  636. try:
  637. import pipes
  638. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  639. except ImportError:
  640. shell_quote = repr
  641. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  642. retval = subprocess.call(args)
  643. while retval == 2 or retval == 1:
  644. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  645. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  646. time.sleep(5.0) # This seems to be needed
  647. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  648. cursize = os.path.getsize(encodeFilename(tmpfilename))
  649. if prevsize == cursize and retval == 1:
  650. break
  651. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  652. if prevsize == cursize and retval == 2 and cursize > 1024:
  653. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  654. retval = 0
  655. break
  656. if retval == 0:
  657. fsize = os.path.getsize(encodeFilename(tmpfilename))
  658. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  659. self.try_rename(tmpfilename, filename)
  660. self._hook_progress({
  661. 'downloaded_bytes': fsize,
  662. 'total_bytes': fsize,
  663. 'filename': filename,
  664. 'status': 'finished',
  665. })
  666. return True
  667. else:
  668. self.to_stderr(u"\n")
  669. self.report_error(u'rtmpdump exited with code %d' % retval)
  670. return False
  671. def _do_download(self, filename, info_dict):
  672. url = info_dict['url']
  673. # Check file already present
  674. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  675. self.report_file_already_downloaded(filename)
  676. self._hook_progress({
  677. 'filename': filename,
  678. 'status': 'finished',
  679. })
  680. return True
  681. # Attempt to download using rtmpdump
  682. if url.startswith('rtmp'):
  683. return self._download_with_rtmpdump(filename, url,
  684. info_dict.get('player_url', None),
  685. info_dict.get('page_url', None),
  686. info_dict.get('play_path', None))
  687. tmpfilename = self.temp_name(filename)
  688. stream = None
  689. # Do not include the Accept-Encoding header
  690. headers = {'Youtubedl-no-compression': 'True'}
  691. if 'user_agent' in info_dict:
  692. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  693. basic_request = compat_urllib_request.Request(url, None, headers)
  694. request = compat_urllib_request.Request(url, None, headers)
  695. if self.params.get('test', False):
  696. request.add_header('Range','bytes=0-10240')
  697. # Establish possible resume length
  698. if os.path.isfile(encodeFilename(tmpfilename)):
  699. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  700. else:
  701. resume_len = 0
  702. open_mode = 'wb'
  703. if resume_len != 0:
  704. if self.params.get('continuedl', False):
  705. self.report_resuming_byte(resume_len)
  706. request.add_header('Range','bytes=%d-' % resume_len)
  707. open_mode = 'ab'
  708. else:
  709. resume_len = 0
  710. count = 0
  711. retries = self.params.get('retries', 0)
  712. while count <= retries:
  713. # Establish connection
  714. try:
  715. if count == 0 and 'urlhandle' in info_dict:
  716. data = info_dict['urlhandle']
  717. data = compat_urllib_request.urlopen(request)
  718. break
  719. except (compat_urllib_error.HTTPError, ) as err:
  720. if (err.code < 500 or err.code >= 600) and err.code != 416:
  721. # Unexpected HTTP error
  722. raise
  723. elif err.code == 416:
  724. # Unable to resume (requested range not satisfiable)
  725. try:
  726. # Open the connection again without the range header
  727. data = compat_urllib_request.urlopen(basic_request)
  728. content_length = data.info()['Content-Length']
  729. except (compat_urllib_error.HTTPError, ) as err:
  730. if err.code < 500 or err.code >= 600:
  731. raise
  732. else:
  733. # Examine the reported length
  734. if (content_length is not None and
  735. (resume_len - 100 < int(content_length) < resume_len + 100)):
  736. # The file had already been fully downloaded.
  737. # Explanation to the above condition: in issue #175 it was revealed that
  738. # YouTube sometimes adds or removes a few bytes from the end of the file,
  739. # changing the file size slightly and causing problems for some users. So
  740. # I decided to implement a suggested change and consider the file
  741. # completely downloaded if the file size differs less than 100 bytes from
  742. # the one in the hard drive.
  743. self.report_file_already_downloaded(filename)
  744. self.try_rename(tmpfilename, filename)
  745. self._hook_progress({
  746. 'filename': filename,
  747. 'status': 'finished',
  748. })
  749. return True
  750. else:
  751. # The length does not match, we start the download over
  752. self.report_unable_to_resume()
  753. open_mode = 'wb'
  754. break
  755. # Retry
  756. count += 1
  757. if count <= retries:
  758. self.report_retry(count, retries)
  759. if count > retries:
  760. self.report_error(u'giving up after %s retries' % retries)
  761. return False
  762. data_len = data.info().get('Content-length', None)
  763. if data_len is not None:
  764. data_len = int(data_len) + resume_len
  765. min_data_len = self.params.get("min_filesize", None)
  766. max_data_len = self.params.get("max_filesize", None)
  767. if min_data_len is not None and data_len < min_data_len:
  768. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  769. return False
  770. if max_data_len is not None and data_len > max_data_len:
  771. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  772. return False
  773. data_len_str = self.format_bytes(data_len)
  774. byte_counter = 0 + resume_len
  775. block_size = self.params.get('buffersize', 1024)
  776. start = time.time()
  777. while True:
  778. # Download and write
  779. before = time.time()
  780. data_block = data.read(block_size)
  781. after = time.time()
  782. if len(data_block) == 0:
  783. break
  784. byte_counter += len(data_block)
  785. # Open file just in time
  786. if stream is None:
  787. try:
  788. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  789. assert stream is not None
  790. filename = self.undo_temp_name(tmpfilename)
  791. self.report_destination(filename)
  792. except (OSError, IOError) as err:
  793. self.report_error(u'unable to open for writing: %s' % str(err))
  794. return False
  795. try:
  796. stream.write(data_block)
  797. except (IOError, OSError) as err:
  798. self.to_stderr(u"\n")
  799. self.report_error(u'unable to write data: %s' % str(err))
  800. return False
  801. if not self.params.get('noresizebuffer', False):
  802. block_size = self.best_block_size(after - before, len(data_block))
  803. # Progress message
  804. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  805. if data_len is None:
  806. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  807. else:
  808. percent_str = self.calc_percent(byte_counter, data_len)
  809. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  810. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  811. self._hook_progress({
  812. 'downloaded_bytes': byte_counter,
  813. 'total_bytes': data_len,
  814. 'tmpfilename': tmpfilename,
  815. 'filename': filename,
  816. 'status': 'downloading',
  817. })
  818. # Apply rate limit
  819. self.slow_down(start, byte_counter - resume_len)
  820. if stream is None:
  821. self.to_stderr(u"\n")
  822. self.report_error(u'Did not get any data blocks')
  823. return False
  824. stream.close()
  825. self.report_finish()
  826. if data_len is not None and byte_counter != data_len:
  827. raise ContentTooShortError(byte_counter, int(data_len))
  828. self.try_rename(tmpfilename, filename)
  829. # Update file modification time
  830. if self.params.get('updatetime', True):
  831. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  832. self._hook_progress({
  833. 'downloaded_bytes': byte_counter,
  834. 'total_bytes': byte_counter,
  835. 'filename': filename,
  836. 'status': 'finished',
  837. })
  838. return True
  839. def _hook_progress(self, status):
  840. for ph in self._progress_hooks:
  841. ph(status)
  842. def add_progress_hook(self, ph):
  843. """ ph gets called on download progress, with a dictionary with the entries
  844. * filename: The final filename
  845. * status: One of "downloading" and "finished"
  846. It can also have some of the following entries:
  847. * downloaded_bytes: Bytes on disks
  848. * total_bytes: Total bytes, None if unknown
  849. * tmpfilename: The filename we're currently writing to
  850. Hooks are guaranteed to be called at least once (with status "finished")
  851. if the download is successful.
  852. """
  853. self._progress_hooks.append(ph)