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.

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