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.

1016 lines
44 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):
  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 player_url is not None:
  674. basic_args += ['-W', player_url]
  675. if page_url is not None:
  676. basic_args += ['--pageUrl', page_url]
  677. if play_path is not None:
  678. basic_args += ['-y', play_path]
  679. args = basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)]
  680. if self.params.get('verbose', False):
  681. try:
  682. import pipes
  683. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  684. except ImportError:
  685. shell_quote = repr
  686. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  687. retval = subprocess.call(args)
  688. while retval == 2 or retval == 1:
  689. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  690. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  691. time.sleep(5.0) # This seems to be needed
  692. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  693. cursize = os.path.getsize(encodeFilename(tmpfilename))
  694. if prevsize == cursize and retval == 1:
  695. break
  696. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  697. if prevsize == cursize and retval == 2 and cursize > 1024:
  698. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  699. retval = 0
  700. break
  701. if retval == 0:
  702. fsize = os.path.getsize(encodeFilename(tmpfilename))
  703. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  704. self.try_rename(tmpfilename, filename)
  705. self._hook_progress({
  706. 'downloaded_bytes': fsize,
  707. 'total_bytes': fsize,
  708. 'filename': filename,
  709. 'status': 'finished',
  710. })
  711. return True
  712. else:
  713. self.to_stderr(u"\n")
  714. self.report_error(u'rtmpdump exited with code %d' % retval)
  715. return False
  716. def _do_download(self, filename, info_dict):
  717. url = info_dict['url']
  718. # Check file already present
  719. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  720. self.report_file_already_downloaded(filename)
  721. self._hook_progress({
  722. 'filename': filename,
  723. 'status': 'finished',
  724. })
  725. return True
  726. # Attempt to download using rtmpdump
  727. if url.startswith('rtmp'):
  728. return self._download_with_rtmpdump(filename, url,
  729. info_dict.get('player_url', None),
  730. info_dict.get('page_url', None),
  731. info_dict.get('play_path', None))
  732. tmpfilename = self.temp_name(filename)
  733. stream = None
  734. # Do not include the Accept-Encoding header
  735. headers = {'Youtubedl-no-compression': 'True'}
  736. if 'user_agent' in info_dict:
  737. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  738. basic_request = compat_urllib_request.Request(url, None, headers)
  739. request = compat_urllib_request.Request(url, None, headers)
  740. if self.params.get('test', False):
  741. request.add_header('Range','bytes=0-10240')
  742. # Establish possible resume length
  743. if os.path.isfile(encodeFilename(tmpfilename)):
  744. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  745. else:
  746. resume_len = 0
  747. open_mode = 'wb'
  748. if resume_len != 0:
  749. if self.params.get('continuedl', False):
  750. self.report_resuming_byte(resume_len)
  751. request.add_header('Range','bytes=%d-' % resume_len)
  752. open_mode = 'ab'
  753. else:
  754. resume_len = 0
  755. count = 0
  756. retries = self.params.get('retries', 0)
  757. while count <= retries:
  758. # Establish connection
  759. try:
  760. if count == 0 and 'urlhandle' in info_dict:
  761. data = info_dict['urlhandle']
  762. data = compat_urllib_request.urlopen(request)
  763. break
  764. except (compat_urllib_error.HTTPError, ) as err:
  765. if (err.code < 500 or err.code >= 600) and err.code != 416:
  766. # Unexpected HTTP error
  767. raise
  768. elif err.code == 416:
  769. # Unable to resume (requested range not satisfiable)
  770. try:
  771. # Open the connection again without the range header
  772. data = compat_urllib_request.urlopen(basic_request)
  773. content_length = data.info()['Content-Length']
  774. except (compat_urllib_error.HTTPError, ) as err:
  775. if err.code < 500 or err.code >= 600:
  776. raise
  777. else:
  778. # Examine the reported length
  779. if (content_length is not None and
  780. (resume_len - 100 < int(content_length) < resume_len + 100)):
  781. # The file had already been fully downloaded.
  782. # Explanation to the above condition: in issue #175 it was revealed that
  783. # YouTube sometimes adds or removes a few bytes from the end of the file,
  784. # changing the file size slightly and causing problems for some users. So
  785. # I decided to implement a suggested change and consider the file
  786. # completely downloaded if the file size differs less than 100 bytes from
  787. # the one in the hard drive.
  788. self.report_file_already_downloaded(filename)
  789. self.try_rename(tmpfilename, filename)
  790. self._hook_progress({
  791. 'filename': filename,
  792. 'status': 'finished',
  793. })
  794. return True
  795. else:
  796. # The length does not match, we start the download over
  797. self.report_unable_to_resume()
  798. open_mode = 'wb'
  799. break
  800. # Retry
  801. count += 1
  802. if count <= retries:
  803. self.report_retry(count, retries)
  804. if count > retries:
  805. self.report_error(u'giving up after %s retries' % retries)
  806. return False
  807. data_len = data.info().get('Content-length', None)
  808. if data_len is not None:
  809. data_len = int(data_len) + resume_len
  810. min_data_len = self.params.get("min_filesize", None)
  811. max_data_len = self.params.get("max_filesize", None)
  812. if min_data_len is not None and data_len < min_data_len:
  813. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  814. return False
  815. if max_data_len is not None and data_len > max_data_len:
  816. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  817. return False
  818. data_len_str = self.format_bytes(data_len)
  819. byte_counter = 0 + resume_len
  820. block_size = self.params.get('buffersize', 1024)
  821. start = time.time()
  822. while True:
  823. # Download and write
  824. before = time.time()
  825. data_block = data.read(block_size)
  826. after = time.time()
  827. if len(data_block) == 0:
  828. break
  829. byte_counter += len(data_block)
  830. # Open file just in time
  831. if stream is None:
  832. try:
  833. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  834. assert stream is not None
  835. filename = self.undo_temp_name(tmpfilename)
  836. self.report_destination(filename)
  837. except (OSError, IOError) as err:
  838. self.report_error(u'unable to open for writing: %s' % str(err))
  839. return False
  840. try:
  841. stream.write(data_block)
  842. except (IOError, OSError) as err:
  843. self.to_stderr(u"\n")
  844. self.report_error(u'unable to write data: %s' % str(err))
  845. return False
  846. if not self.params.get('noresizebuffer', False):
  847. block_size = self.best_block_size(after - before, len(data_block))
  848. # Progress message
  849. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  850. if data_len is None:
  851. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  852. else:
  853. percent_str = self.calc_percent(byte_counter, data_len)
  854. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  855. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  856. self._hook_progress({
  857. 'downloaded_bytes': byte_counter,
  858. 'total_bytes': data_len,
  859. 'tmpfilename': tmpfilename,
  860. 'filename': filename,
  861. 'status': 'downloading',
  862. })
  863. # Apply rate limit
  864. self.slow_down(start, byte_counter - resume_len)
  865. if stream is None:
  866. self.to_stderr(u"\n")
  867. self.report_error(u'Did not get any data blocks')
  868. return False
  869. stream.close()
  870. self.report_finish()
  871. if data_len is not None and byte_counter != data_len:
  872. raise ContentTooShortError(byte_counter, int(data_len))
  873. self.try_rename(tmpfilename, filename)
  874. # Update file modification time
  875. if self.params.get('updatetime', True):
  876. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  877. self._hook_progress({
  878. 'downloaded_bytes': byte_counter,
  879. 'total_bytes': byte_counter,
  880. 'filename': filename,
  881. 'status': 'finished',
  882. })
  883. return True
  884. def _hook_progress(self, status):
  885. for ph in self._progress_hooks:
  886. ph(status)
  887. def add_progress_hook(self, ph):
  888. """ ph gets called on download progress, with a dictionary with the entries
  889. * filename: The final filename
  890. * status: One of "downloading" and "finished"
  891. It can also have some of the following entries:
  892. * downloaded_bytes: Bytes on disks
  893. * total_bytes: Total bytes, None if unknown
  894. * tmpfilename: The filename we're currently writing to
  895. Hooks are guaranteed to be called at least once (with status "finished")
  896. if the download is successful.
  897. """
  898. self._progress_hooks.append(ph)