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.

1006 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. 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. onlysubtitles: Downloads only the subtitles of the video
  76. allsubtitles: Downloads all the subtitles of the video
  77. listsubtitles: Lists all available subtitles for the video
  78. subtitlesformat: Subtitle format [sbv/srt] (default=srt)
  79. subtitleslang: Language of the subtitles to download
  80. test: Download only first bytes to test the downloader.
  81. keepvideo: Keep the video file after post-processing
  82. min_filesize: Skip files smaller than this size
  83. max_filesize: Skip files larger than this size
  84. daterange: A DateRange object, download only if the upload_date is in the range.
  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):
  386. '''
  387. Returns a list with a dictionary for each video we find.
  388. If 'download', also downloads the videos.
  389. '''
  390. if ie_key:
  391. ie = get_info_extractor(ie_key)()
  392. ie.set_downloader(self)
  393. ies = [ie]
  394. else:
  395. ies = self._ies
  396. for ie in ies:
  397. if not ie.suitable(url):
  398. continue
  399. if not ie.working():
  400. self.report_warning(u'The program functionality for this site has been marked as broken, '
  401. u'and will probably not work.')
  402. try:
  403. ie_result = ie.extract(url)
  404. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  405. break
  406. if isinstance(ie_result, list):
  407. # Backwards compatibility: old IE result format
  408. ie_result = {
  409. '_type': 'compat_list',
  410. 'entries': ie_result,
  411. }
  412. if 'extractor' not in ie_result:
  413. ie_result['extractor'] = ie.IE_NAME
  414. return self.process_ie_result(ie_result, download=download)
  415. except ExtractorError as de: # An error we somewhat expected
  416. self.report_error(compat_str(de), de.format_traceback())
  417. break
  418. except Exception as e:
  419. if self.params.get('ignoreerrors', False):
  420. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  421. break
  422. else:
  423. raise
  424. else:
  425. self.report_error(u'no suitable InfoExtractor: %s' % url)
  426. def process_ie_result(self, ie_result, download=True):
  427. """
  428. Take the result of the ie(may be modified) and resolve all unresolved
  429. references (URLs, playlist items).
  430. It will also download the videos if 'download'.
  431. Returns the resolved ie_result.
  432. """
  433. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  434. if result_type == 'video':
  435. if 'playlist' not in ie_result:
  436. # It isn't part of a playlist
  437. ie_result['playlist'] = None
  438. ie_result['playlist_index'] = None
  439. if download:
  440. self.process_info(ie_result)
  441. return ie_result
  442. elif result_type == 'url':
  443. return self.extract_info(ie_result['url'], download, ie_key=ie_result.get('ie_key'))
  444. elif result_type == 'playlist':
  445. # We process each entry in the playlist
  446. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  447. self.to_screen(u'[download] Downloading playlist: %s' % playlist)
  448. playlist_results = []
  449. n_all_entries = len(ie_result['entries'])
  450. playliststart = self.params.get('playliststart', 1) - 1
  451. playlistend = self.params.get('playlistend', -1)
  452. if playlistend == -1:
  453. entries = ie_result['entries'][playliststart:]
  454. else:
  455. entries = ie_result['entries'][playliststart:playlistend]
  456. n_entries = len(entries)
  457. self.to_screen(u"[%s] playlist '%s': Collected %d video ids (downloading %d of them)" %
  458. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  459. for i,entry in enumerate(entries,1):
  460. self.to_screen(u'[download] Downloading video #%s of %s' %(i, n_entries))
  461. entry['playlist'] = playlist
  462. entry['playlist_index'] = i + playliststart
  463. entry_result = self.process_ie_result(entry, download=download)
  464. playlist_results.append(entry_result)
  465. ie_result['entries'] = playlist_results
  466. return ie_result
  467. elif result_type == 'compat_list':
  468. def _fixup(r):
  469. r.setdefault('extractor', ie_result['extractor'])
  470. return r
  471. ie_result['entries'] = [
  472. self.process_ie_result(_fixup(r), download=download)
  473. for r in ie_result['entries']
  474. ]
  475. return ie_result
  476. else:
  477. raise Exception('Invalid result type: %s' % result_type)
  478. def process_info(self, info_dict):
  479. """Process a single resolved IE result."""
  480. assert info_dict.get('_type', 'video') == 'video'
  481. #We increment the download the download count here to match the previous behaviour.
  482. self.increment_downloads()
  483. info_dict['fulltitle'] = info_dict['title']
  484. if len(info_dict['title']) > 200:
  485. info_dict['title'] = info_dict['title'][:197] + u'...'
  486. # Keep for backwards compatibility
  487. info_dict['stitle'] = info_dict['title']
  488. if not 'format' in info_dict:
  489. info_dict['format'] = info_dict['ext']
  490. reason = self._match_entry(info_dict)
  491. if reason is not None:
  492. self.to_screen(u'[download] ' + reason)
  493. return
  494. max_downloads = self.params.get('max_downloads')
  495. if max_downloads is not None:
  496. if self._num_downloads > int(max_downloads):
  497. raise MaxDownloadsReached()
  498. filename = self.prepare_filename(info_dict)
  499. # Forced printings
  500. if self.params.get('forcetitle', False):
  501. compat_print(info_dict['title'])
  502. if self.params.get('forceid', False):
  503. compat_print(info_dict['id'])
  504. if self.params.get('forceurl', False):
  505. compat_print(info_dict['url'])
  506. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  507. compat_print(info_dict['thumbnail'])
  508. if self.params.get('forcedescription', False) and 'description' in info_dict:
  509. compat_print(info_dict['description'])
  510. if self.params.get('forcefilename', False) and filename is not None:
  511. compat_print(filename)
  512. if self.params.get('forceformat', False):
  513. compat_print(info_dict['format'])
  514. # Do nothing else if in simulate mode
  515. if self.params.get('simulate', False):
  516. return
  517. if filename is None:
  518. return
  519. try:
  520. dn = os.path.dirname(encodeFilename(filename))
  521. if dn != '' and not os.path.exists(dn): # dn is already encoded
  522. os.makedirs(dn)
  523. except (OSError, IOError) as err:
  524. self.report_error(u'unable to create directory ' + compat_str(err))
  525. return
  526. if self.params.get('writedescription', False):
  527. try:
  528. descfn = filename + u'.description'
  529. self.report_writedescription(descfn)
  530. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  531. descfile.write(info_dict['description'])
  532. except (OSError, IOError):
  533. self.report_error(u'Cannot write description file ' + descfn)
  534. return
  535. if self.params.get('writesubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  536. # subtitles download errors are already managed as troubles in relevant IE
  537. # that way it will silently go on when used with unsupporting IE
  538. subtitle = info_dict['subtitles'][0]
  539. (sub_error, sub_lang, sub) = subtitle
  540. sub_format = self.params.get('subtitlesformat')
  541. if sub_error:
  542. self.report_warning("Some error while getting the subtitles")
  543. else:
  544. try:
  545. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  546. self.report_writesubtitles(sub_filename)
  547. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  548. subfile.write(sub)
  549. except (OSError, IOError):
  550. self.report_error(u'Cannot write subtitles file ' + descfn)
  551. return
  552. if self.params.get('onlysubtitles', False):
  553. return
  554. if self.params.get('allsubtitles', False) and 'subtitles' in info_dict and info_dict['subtitles']:
  555. subtitles = info_dict['subtitles']
  556. sub_format = self.params.get('subtitlesformat')
  557. for subtitle in subtitles:
  558. (sub_error, sub_lang, sub) = subtitle
  559. if sub_error:
  560. self.report_warning("Some error while getting the subtitles")
  561. else:
  562. try:
  563. sub_filename = filename.rsplit('.', 1)[0] + u'.' + sub_lang + u'.' + sub_format
  564. self.report_writesubtitles(sub_filename)
  565. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  566. subfile.write(sub)
  567. except (OSError, IOError):
  568. self.report_error(u'Cannot write subtitles file ' + descfn)
  569. return
  570. if self.params.get('onlysubtitles', False):
  571. return
  572. if self.params.get('writeinfojson', False):
  573. infofn = filename + u'.info.json'
  574. self.report_writeinfojson(infofn)
  575. try:
  576. json_info_dict = dict((k, v) for k,v in info_dict.items() if not k in ['urlhandle'])
  577. write_json_file(json_info_dict, encodeFilename(infofn))
  578. except (OSError, IOError):
  579. self.report_error(u'Cannot write metadata to JSON file ' + infofn)
  580. return
  581. if self.params.get('writethumbnail', False):
  582. if 'thumbnail' in info_dict:
  583. thumb_format = info_dict['thumbnail'].rpartition(u'/')[2].rpartition(u'.')[2]
  584. if not thumb_format:
  585. thumb_format = 'jpg'
  586. thumb_filename = filename.rpartition('.')[0] + u'.' + thumb_format
  587. self.to_screen(u'[%s] %s: Downloading thumbnail ...' %
  588. (info_dict['extractor'], info_dict['id']))
  589. uf = compat_urllib_request.urlopen(info_dict['thumbnail'])
  590. with open(thumb_filename, 'wb') as thumbf:
  591. shutil.copyfileobj(uf, thumbf)
  592. self.to_screen(u'[%s] %s: Writing thumbnail to: %s' %
  593. (info_dict['extractor'], info_dict['id'], thumb_filename))
  594. if not self.params.get('skip_download', False):
  595. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  596. success = True
  597. else:
  598. try:
  599. success = self._do_download(filename, info_dict)
  600. except (OSError, IOError) as err:
  601. raise UnavailableVideoError()
  602. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  603. self.report_error(u'unable to download video data: %s' % str(err))
  604. return
  605. except (ContentTooShortError, ) as err:
  606. self.report_error(u'content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  607. return
  608. if success:
  609. try:
  610. self.post_process(filename, info_dict)
  611. except (PostProcessingError) as err:
  612. self.report_error(u'postprocessing: %s' % str(err))
  613. return
  614. def download(self, url_list):
  615. """Download a given list of URLs."""
  616. if len(url_list) > 1 and self.fixed_template():
  617. raise SameFileError(self.params['outtmpl'])
  618. for url in url_list:
  619. try:
  620. #It also downloads the videos
  621. videos = self.extract_info(url)
  622. except UnavailableVideoError:
  623. self.report_error(u'unable to download video')
  624. except MaxDownloadsReached:
  625. self.to_screen(u'[info] Maximum number of downloaded files reached.')
  626. raise
  627. return self._download_retcode
  628. def post_process(self, filename, ie_info):
  629. """Run all the postprocessors on the given file."""
  630. info = dict(ie_info)
  631. info['filepath'] = filename
  632. keep_video = None
  633. for pp in self._pps:
  634. try:
  635. keep_video_wish,new_info = pp.run(info)
  636. if keep_video_wish is not None:
  637. if keep_video_wish:
  638. keep_video = keep_video_wish
  639. elif keep_video is None:
  640. # No clear decision yet, let IE decide
  641. keep_video = keep_video_wish
  642. except PostProcessingError as e:
  643. self.to_stderr(u'ERROR: ' + e.msg)
  644. if keep_video is False and not self.params.get('keepvideo', False):
  645. try:
  646. self.to_screen(u'Deleting original file %s (pass -k to keep)' % filename)
  647. os.remove(encodeFilename(filename))
  648. except (IOError, OSError):
  649. self.report_warning(u'Unable to remove downloaded video file')
  650. def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path):
  651. self.report_destination(filename)
  652. tmpfilename = self.temp_name(filename)
  653. # Check for rtmpdump first
  654. try:
  655. subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  656. except (OSError, IOError):
  657. self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
  658. return False
  659. # Download using rtmpdump. rtmpdump returns exit code 2 when
  660. # the connection was interrumpted and resuming appears to be
  661. # possible. This is part of rtmpdump's normal usage, AFAIK.
  662. basic_args = ['rtmpdump', '-q', '-r', url, '-o', tmpfilename]
  663. if player_url is not None:
  664. basic_args += ['-W', player_url]
  665. if page_url is not None:
  666. basic_args += ['--pageUrl', page_url]
  667. if play_path is not None:
  668. basic_args += ['-y', play_path]
  669. args = basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)]
  670. if self.params.get('verbose', False):
  671. try:
  672. import pipes
  673. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  674. except ImportError:
  675. shell_quote = repr
  676. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  677. retval = subprocess.call(args)
  678. while retval == 2 or retval == 1:
  679. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  680. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  681. time.sleep(5.0) # This seems to be needed
  682. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  683. cursize = os.path.getsize(encodeFilename(tmpfilename))
  684. if prevsize == cursize and retval == 1:
  685. break
  686. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  687. if prevsize == cursize and retval == 2 and cursize > 1024:
  688. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  689. retval = 0
  690. break
  691. if retval == 0:
  692. fsize = os.path.getsize(encodeFilename(tmpfilename))
  693. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  694. self.try_rename(tmpfilename, filename)
  695. self._hook_progress({
  696. 'downloaded_bytes': fsize,
  697. 'total_bytes': fsize,
  698. 'filename': filename,
  699. 'status': 'finished',
  700. })
  701. return True
  702. else:
  703. self.to_stderr(u"\n")
  704. self.report_error(u'rtmpdump exited with code %d' % retval)
  705. return False
  706. def _do_download(self, filename, info_dict):
  707. url = info_dict['url']
  708. # Check file already present
  709. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  710. self.report_file_already_downloaded(filename)
  711. self._hook_progress({
  712. 'filename': filename,
  713. 'status': 'finished',
  714. })
  715. return True
  716. # Attempt to download using rtmpdump
  717. if url.startswith('rtmp'):
  718. return self._download_with_rtmpdump(filename, url,
  719. info_dict.get('player_url', None),
  720. info_dict.get('page_url', None),
  721. info_dict.get('play_path', None))
  722. tmpfilename = self.temp_name(filename)
  723. stream = None
  724. # Do not include the Accept-Encoding header
  725. headers = {'Youtubedl-no-compression': 'True'}
  726. if 'user_agent' in info_dict:
  727. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  728. basic_request = compat_urllib_request.Request(url, None, headers)
  729. request = compat_urllib_request.Request(url, None, headers)
  730. if self.params.get('test', False):
  731. request.add_header('Range','bytes=0-10240')
  732. # Establish possible resume length
  733. if os.path.isfile(encodeFilename(tmpfilename)):
  734. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  735. else:
  736. resume_len = 0
  737. open_mode = 'wb'
  738. if resume_len != 0:
  739. if self.params.get('continuedl', False):
  740. self.report_resuming_byte(resume_len)
  741. request.add_header('Range','bytes=%d-' % resume_len)
  742. open_mode = 'ab'
  743. else:
  744. resume_len = 0
  745. count = 0
  746. retries = self.params.get('retries', 0)
  747. while count <= retries:
  748. # Establish connection
  749. try:
  750. if count == 0 and 'urlhandle' in info_dict:
  751. data = info_dict['urlhandle']
  752. data = compat_urllib_request.urlopen(request)
  753. break
  754. except (compat_urllib_error.HTTPError, ) as err:
  755. if (err.code < 500 or err.code >= 600) and err.code != 416:
  756. # Unexpected HTTP error
  757. raise
  758. elif err.code == 416:
  759. # Unable to resume (requested range not satisfiable)
  760. try:
  761. # Open the connection again without the range header
  762. data = compat_urllib_request.urlopen(basic_request)
  763. content_length = data.info()['Content-Length']
  764. except (compat_urllib_error.HTTPError, ) as err:
  765. if err.code < 500 or err.code >= 600:
  766. raise
  767. else:
  768. # Examine the reported length
  769. if (content_length is not None and
  770. (resume_len - 100 < int(content_length) < resume_len + 100)):
  771. # The file had already been fully downloaded.
  772. # Explanation to the above condition: in issue #175 it was revealed that
  773. # YouTube sometimes adds or removes a few bytes from the end of the file,
  774. # changing the file size slightly and causing problems for some users. So
  775. # I decided to implement a suggested change and consider the file
  776. # completely downloaded if the file size differs less than 100 bytes from
  777. # the one in the hard drive.
  778. self.report_file_already_downloaded(filename)
  779. self.try_rename(tmpfilename, filename)
  780. self._hook_progress({
  781. 'filename': filename,
  782. 'status': 'finished',
  783. })
  784. return True
  785. else:
  786. # The length does not match, we start the download over
  787. self.report_unable_to_resume()
  788. open_mode = 'wb'
  789. break
  790. # Retry
  791. count += 1
  792. if count <= retries:
  793. self.report_retry(count, retries)
  794. if count > retries:
  795. self.report_error(u'giving up after %s retries' % retries)
  796. return False
  797. data_len = data.info().get('Content-length', None)
  798. if data_len is not None:
  799. data_len = int(data_len) + resume_len
  800. min_data_len = self.params.get("min_filesize", None)
  801. max_data_len = self.params.get("max_filesize", None)
  802. if min_data_len is not None and data_len < min_data_len:
  803. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  804. return False
  805. if max_data_len is not None and data_len > max_data_len:
  806. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  807. return False
  808. data_len_str = self.format_bytes(data_len)
  809. byte_counter = 0 + resume_len
  810. block_size = self.params.get('buffersize', 1024)
  811. start = time.time()
  812. while True:
  813. # Download and write
  814. before = time.time()
  815. data_block = data.read(block_size)
  816. after = time.time()
  817. if len(data_block) == 0:
  818. break
  819. byte_counter += len(data_block)
  820. # Open file just in time
  821. if stream is None:
  822. try:
  823. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  824. assert stream is not None
  825. filename = self.undo_temp_name(tmpfilename)
  826. self.report_destination(filename)
  827. except (OSError, IOError) as err:
  828. self.report_error(u'unable to open for writing: %s' % str(err))
  829. return False
  830. try:
  831. stream.write(data_block)
  832. except (IOError, OSError) as err:
  833. self.to_stderr(u"\n")
  834. self.report_error(u'unable to write data: %s' % str(err))
  835. return False
  836. if not self.params.get('noresizebuffer', False):
  837. block_size = self.best_block_size(after - before, len(data_block))
  838. # Progress message
  839. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  840. if data_len is None:
  841. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  842. else:
  843. percent_str = self.calc_percent(byte_counter, data_len)
  844. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  845. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  846. self._hook_progress({
  847. 'downloaded_bytes': byte_counter,
  848. 'total_bytes': data_len,
  849. 'tmpfilename': tmpfilename,
  850. 'filename': filename,
  851. 'status': 'downloading',
  852. })
  853. # Apply rate limit
  854. self.slow_down(start, byte_counter - resume_len)
  855. if stream is None:
  856. self.to_stderr(u"\n")
  857. self.report_error(u'Did not get any data blocks')
  858. return False
  859. stream.close()
  860. self.report_finish()
  861. if data_len is not None and byte_counter != data_len:
  862. raise ContentTooShortError(byte_counter, int(data_len))
  863. self.try_rename(tmpfilename, filename)
  864. # Update file modification time
  865. if self.params.get('updatetime', True):
  866. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  867. self._hook_progress({
  868. 'downloaded_bytes': byte_counter,
  869. 'total_bytes': byte_counter,
  870. 'filename': filename,
  871. 'status': 'finished',
  872. })
  873. return True
  874. def _hook_progress(self, status):
  875. for ph in self._progress_hooks:
  876. ph(status)
  877. def add_progress_hook(self, ph):
  878. """ ph gets called on download progress, with a dictionary with the entries
  879. * filename: The final filename
  880. * status: One of "downloading" and "finished"
  881. It can also have some of the following entries:
  882. * downloaded_bytes: Bytes on disks
  883. * total_bytes: Total bytes, None if unknown
  884. * tmpfilename: The filename we're currently writing to
  885. Hooks are guaranteed to be called at least once (with status "finished")
  886. if the download is successful.
  887. """
  888. self._progress_hooks.append(ph)