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.

987 lines
42 KiB

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