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.

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