YoutubeDL.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import datetime
  6. import errno
  7. import io
  8. import itertools
  9. import json
  10. import locale
  11. import operator
  12. import os
  13. import platform
  14. import re
  15. import shutil
  16. import subprocess
  17. import socket
  18. import sys
  19. import time
  20. import traceback
  21. if os.name == 'nt':
  22. import ctypes
  23. from .compat import (
  24. compat_cookiejar,
  25. compat_expanduser,
  26. compat_http_client,
  27. compat_kwargs,
  28. compat_str,
  29. compat_urllib_error,
  30. compat_urllib_request,
  31. )
  32. from .utils import (
  33. escape_url,
  34. ContentTooShortError,
  35. date_from_str,
  36. DateRange,
  37. DEFAULT_OUTTMPL,
  38. determine_ext,
  39. DownloadError,
  40. encodeFilename,
  41. ExtractorError,
  42. format_bytes,
  43. formatSeconds,
  44. get_term_width,
  45. locked_file,
  46. make_HTTPS_handler,
  47. MaxDownloadsReached,
  48. PagedList,
  49. parse_filesize,
  50. PostProcessingError,
  51. platform_name,
  52. preferredencoding,
  53. SameFileError,
  54. sanitize_filename,
  55. std_headers,
  56. subtitles_filename,
  57. takewhile_inclusive,
  58. UnavailableVideoError,
  59. url_basename,
  60. version_tuple,
  61. write_json_file,
  62. write_string,
  63. YoutubeDLHandler,
  64. prepend_extension,
  65. args_to_str,
  66. age_restricted,
  67. )
  68. from .cache import Cache
  69. from .extractor import get_info_extractor, gen_extractors
  70. from .downloader import get_suitable_downloader
  71. from .downloader.rtmp import rtmpdump_version
  72. from .postprocessor import (
  73. FFmpegFixupM4aPP,
  74. FFmpegFixupStretchedPP,
  75. FFmpegMergerPP,
  76. FFmpegPostProcessor,
  77. get_postprocessor,
  78. )
  79. from .version import __version__
  80. class YoutubeDL(object):
  81. """YoutubeDL class.
  82. YoutubeDL objects are the ones responsible of downloading the
  83. actual video file and writing it to disk if the user has requested
  84. it, among some other tasks. In most cases there should be one per
  85. program. As, given a video URL, the downloader doesn't know how to
  86. extract all the needed information, task that InfoExtractors do, it
  87. has to pass the URL to one of them.
  88. For this, YoutubeDL objects have a method that allows
  89. InfoExtractors to be registered in a given order. When it is passed
  90. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  91. finds that reports being able to handle it. The InfoExtractor extracts
  92. all the information about the video or videos the URL refers to, and
  93. YoutubeDL process the extracted information, possibly using a File
  94. Downloader to download the video.
  95. YoutubeDL objects accept a lot of parameters. In order not to saturate
  96. the object constructor with arguments, it receives a dictionary of
  97. options instead. These options are available through the params
  98. attribute for the InfoExtractors to use. The YoutubeDL also
  99. registers itself as the downloader in charge for the InfoExtractors
  100. that are added to it, so this is a "mutual registration".
  101. Available options:
  102. username: Username for authentication purposes.
  103. password: Password for authentication purposes.
  104. videopassword: Password for acces a video.
  105. usenetrc: Use netrc for authentication instead.
  106. verbose: Print additional info to stdout.
  107. quiet: Do not print messages to stdout.
  108. no_warnings: Do not print out anything for warnings.
  109. forceurl: Force printing final URL.
  110. forcetitle: Force printing title.
  111. forceid: Force printing ID.
  112. forcethumbnail: Force printing thumbnail URL.
  113. forcedescription: Force printing description.
  114. forcefilename: Force printing final filename.
  115. forceduration: Force printing duration.
  116. forcejson: Force printing info_dict as JSON.
  117. dump_single_json: Force printing the info_dict of the whole playlist
  118. (or video) as a single JSON line.
  119. simulate: Do not download the video files.
  120. format: Video format code. See options.py for more information.
  121. format_limit: Highest quality format to try.
  122. outtmpl: Template for output names.
  123. restrictfilenames: Do not allow "&" and spaces in file names
  124. ignoreerrors: Do not stop on download errors.
  125. nooverwrites: Prevent overwriting files.
  126. playliststart: Playlist item to start at.
  127. playlistend: Playlist item to end at.
  128. playlistreverse: Download playlist items in reverse order.
  129. matchtitle: Download only matching titles.
  130. rejecttitle: Reject downloads for matching titles.
  131. logger: Log messages to a logging.Logger instance.
  132. logtostderr: Log messages to stderr instead of stdout.
  133. writedescription: Write the video description to a .description file
  134. writeinfojson: Write the video description to a .info.json file
  135. writeannotations: Write the video annotations to a .annotations.xml file
  136. writethumbnail: Write the thumbnail image to a file
  137. writesubtitles: Write the video subtitles to a file
  138. writeautomaticsub: Write the automatic subtitles to a file
  139. allsubtitles: Downloads all the subtitles of the video
  140. (requires writesubtitles or writeautomaticsub)
  141. listsubtitles: Lists all available subtitles for the video
  142. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  143. subtitleslangs: List of languages of the subtitles to download
  144. keepvideo: Keep the video file after post-processing
  145. daterange: A DateRange object, download only if the upload_date is in the range.
  146. skip_download: Skip the actual download of the video file
  147. cachedir: Location of the cache files in the filesystem.
  148. False to disable filesystem cache.
  149. noplaylist: Download single video instead of a playlist if in doubt.
  150. age_limit: An integer representing the user's age in years.
  151. Unsuitable videos for the given age are skipped.
  152. min_views: An integer representing the minimum view count the video
  153. must have in order to not be skipped.
  154. Videos without view count information are always
  155. downloaded. None for no limit.
  156. max_views: An integer representing the maximum view count.
  157. Videos that are more popular than that are not
  158. downloaded.
  159. Videos without view count information are always
  160. downloaded. None for no limit.
  161. download_archive: File name of a file where all downloads are recorded.
  162. Videos already present in the file are not downloaded
  163. again.
  164. cookiefile: File name where cookies should be read from and dumped to.
  165. nocheckcertificate:Do not verify SSL certificates
  166. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  167. At the moment, this is only supported by YouTube.
  168. proxy: URL of the proxy server to use
  169. socket_timeout: Time to wait for unresponsive hosts, in seconds
  170. bidi_workaround: Work around buggy terminals without bidirectional text
  171. support, using fridibi
  172. debug_printtraffic:Print out sent and received HTTP traffic
  173. include_ads: Download ads as well
  174. default_search: Prepend this string if an input url is not valid.
  175. 'auto' for elaborate guessing
  176. encoding: Use this encoding instead of the system-specified.
  177. extract_flat: Do not resolve URLs, return the immediate result.
  178. Pass in 'in_playlist' to only show this behavior for
  179. playlist items.
  180. postprocessors: A list of dictionaries, each with an entry
  181. * key: The name of the postprocessor. See
  182. youtube_dl/postprocessor/__init__.py for a list.
  183. as well as any further keyword arguments for the
  184. postprocessor.
  185. progress_hooks: A list of functions that get called on download
  186. progress, with a dictionary with the entries
  187. * filename: The final filename
  188. * status: One of "downloading" and "finished"
  189. The dict may also have some of the following entries:
  190. * downloaded_bytes: Bytes on disk
  191. * total_bytes: Size of the whole file, None if unknown
  192. * tmpfilename: The filename we're currently writing to
  193. * eta: The estimated time in seconds, None if unknown
  194. * speed: The download speed in bytes/second, None if
  195. unknown
  196. Progress hooks are guaranteed to be called at least once
  197. (with status "finished") if the download is successful.
  198. merge_output_format: Extension to use when merging formats.
  199. fixup: Automatically correct known faults of the file.
  200. One of:
  201. - "never": do nothing
  202. - "warn": only emit a warning
  203. - "detect_or_warn": check whether we can do anything
  204. about it, warn otherwise (default)
  205. source_address: (Experimental) Client-side IP address to bind to.
  206. call_home: Boolean, true iff we are allowed to contact the
  207. youtube-dl servers for debugging.
  208. sleep_interval: Number of seconds to sleep before each download.
  209. external_downloader: Executable of the external downloader to call.
  210. The following parameters are not used by YoutubeDL itself, they are used by
  211. the FileDownloader:
  212. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  213. noresizebuffer, retries, continuedl, noprogress, consoletitle
  214. The following options are used by the post processors:
  215. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  216. otherwise prefer avconv.
  217. exec_cmd: Arbitrary command to run after downloading
  218. """
  219. params = None
  220. _ies = []
  221. _pps = []
  222. _download_retcode = None
  223. _num_downloads = None
  224. _screen_file = None
  225. def __init__(self, params=None, auto_init=True):
  226. """Create a FileDownloader object with the given options."""
  227. if params is None:
  228. params = {}
  229. self._ies = []
  230. self._ies_instances = {}
  231. self._pps = []
  232. self._progress_hooks = []
  233. self._download_retcode = 0
  234. self._num_downloads = 0
  235. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  236. self._err_file = sys.stderr
  237. self.params = params
  238. self.cache = Cache(self)
  239. if params.get('bidi_workaround', False):
  240. try:
  241. import pty
  242. master, slave = pty.openpty()
  243. width = get_term_width()
  244. if width is None:
  245. width_args = []
  246. else:
  247. width_args = ['-w', str(width)]
  248. sp_kwargs = dict(
  249. stdin=subprocess.PIPE,
  250. stdout=slave,
  251. stderr=self._err_file)
  252. try:
  253. self._output_process = subprocess.Popen(
  254. ['bidiv'] + width_args, **sp_kwargs
  255. )
  256. except OSError:
  257. self._output_process = subprocess.Popen(
  258. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  259. self._output_channel = os.fdopen(master, 'rb')
  260. except OSError as ose:
  261. if ose.errno == 2:
  262. self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  263. else:
  264. raise
  265. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  266. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  267. and not params.get('restrictfilenames', False)):
  268. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  269. self.report_warning(
  270. 'Assuming --restrict-filenames since file system encoding '
  271. 'cannot encode all characters. '
  272. 'Set the LC_ALL environment variable to fix this.')
  273. self.params['restrictfilenames'] = True
  274. if '%(stitle)s' in self.params.get('outtmpl', ''):
  275. self.report_warning('%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  276. self._setup_opener()
  277. if auto_init:
  278. self.print_debug_header()
  279. self.add_default_info_extractors()
  280. for pp_def_raw in self.params.get('postprocessors', []):
  281. pp_class = get_postprocessor(pp_def_raw['key'])
  282. pp_def = dict(pp_def_raw)
  283. del pp_def['key']
  284. pp = pp_class(self, **compat_kwargs(pp_def))
  285. self.add_post_processor(pp)
  286. for ph in self.params.get('progress_hooks', []):
  287. self.add_progress_hook(ph)
  288. def warn_if_short_id(self, argv):
  289. # short YouTube ID starting with dash?
  290. idxs = [
  291. i for i, a in enumerate(argv)
  292. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  293. if idxs:
  294. correct_argv = (
  295. ['youtube-dl'] +
  296. [a for i, a in enumerate(argv) if i not in idxs] +
  297. ['--'] + [argv[i] for i in idxs]
  298. )
  299. self.report_warning(
  300. 'Long argument string detected. '
  301. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  302. args_to_str(correct_argv))
  303. def add_info_extractor(self, ie):
  304. """Add an InfoExtractor object to the end of the list."""
  305. self._ies.append(ie)
  306. self._ies_instances[ie.ie_key()] = ie
  307. ie.set_downloader(self)
  308. def get_info_extractor(self, ie_key):
  309. """
  310. Get an instance of an IE with name ie_key, it will try to get one from
  311. the _ies list, if there's no instance it will create a new one and add
  312. it to the extractor list.
  313. """
  314. ie = self._ies_instances.get(ie_key)
  315. if ie is None:
  316. ie = get_info_extractor(ie_key)()
  317. self.add_info_extractor(ie)
  318. return ie
  319. def add_default_info_extractors(self):
  320. """
  321. Add the InfoExtractors returned by gen_extractors to the end of the list
  322. """
  323. for ie in gen_extractors():
  324. self.add_info_extractor(ie)
  325. def add_post_processor(self, pp):
  326. """Add a PostProcessor object to the end of the chain."""
  327. self._pps.append(pp)
  328. pp.set_downloader(self)
  329. def add_progress_hook(self, ph):
  330. """Add the progress hook (currently only for the file downloader)"""
  331. self._progress_hooks.append(ph)
  332. def _bidi_workaround(self, message):
  333. if not hasattr(self, '_output_channel'):
  334. return message
  335. assert hasattr(self, '_output_process')
  336. assert isinstance(message, compat_str)
  337. line_count = message.count('\n') + 1
  338. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  339. self._output_process.stdin.flush()
  340. res = ''.join(self._output_channel.readline().decode('utf-8')
  341. for _ in range(line_count))
  342. return res[:-len('\n')]
  343. def to_screen(self, message, skip_eol=False):
  344. """Print message to stdout if not in quiet mode."""
  345. return self.to_stdout(message, skip_eol, check_quiet=True)
  346. def _write_string(self, s, out=None):
  347. write_string(s, out=out, encoding=self.params.get('encoding'))
  348. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  349. """Print message to stdout if not in quiet mode."""
  350. if self.params.get('logger'):
  351. self.params['logger'].debug(message)
  352. elif not check_quiet or not self.params.get('quiet', False):
  353. message = self._bidi_workaround(message)
  354. terminator = ['\n', ''][skip_eol]
  355. output = message + terminator
  356. self._write_string(output, self._screen_file)
  357. def to_stderr(self, message):
  358. """Print message to stderr."""
  359. assert isinstance(message, compat_str)
  360. if self.params.get('logger'):
  361. self.params['logger'].error(message)
  362. else:
  363. message = self._bidi_workaround(message)
  364. output = message + '\n'
  365. self._write_string(output, self._err_file)
  366. def to_console_title(self, message):
  367. if not self.params.get('consoletitle', False):
  368. return
  369. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  370. # c_wchar_p() might not be necessary if `message` is
  371. # already of type unicode()
  372. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  373. elif 'TERM' in os.environ:
  374. self._write_string('\033]0;%s\007' % message, self._screen_file)
  375. def save_console_title(self):
  376. if not self.params.get('consoletitle', False):
  377. return
  378. if 'TERM' in os.environ:
  379. # Save the title on stack
  380. self._write_string('\033[22;0t', self._screen_file)
  381. def restore_console_title(self):
  382. if not self.params.get('consoletitle', False):
  383. return
  384. if 'TERM' in os.environ:
  385. # Restore the title from stack
  386. self._write_string('\033[23;0t', self._screen_file)
  387. def __enter__(self):
  388. self.save_console_title()
  389. return self
  390. def __exit__(self, *args):
  391. self.restore_console_title()
  392. if self.params.get('cookiefile') is not None:
  393. self.cookiejar.save()
  394. def trouble(self, message=None, tb=None):
  395. """Determine action to take when a download problem appears.
  396. Depending on if the downloader has been configured to ignore
  397. download errors or not, this method may throw an exception or
  398. not when errors are found, after printing the message.
  399. tb, if given, is additional traceback information.
  400. """
  401. if message is not None:
  402. self.to_stderr(message)
  403. if self.params.get('verbose'):
  404. if tb is None:
  405. if sys.exc_info()[0]: # if .trouble has been called from an except block
  406. tb = ''
  407. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  408. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  409. tb += compat_str(traceback.format_exc())
  410. else:
  411. tb_data = traceback.format_list(traceback.extract_stack())
  412. tb = ''.join(tb_data)
  413. self.to_stderr(tb)
  414. if not self.params.get('ignoreerrors', False):
  415. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  416. exc_info = sys.exc_info()[1].exc_info
  417. else:
  418. exc_info = sys.exc_info()
  419. raise DownloadError(message, exc_info)
  420. self._download_retcode = 1
  421. def report_warning(self, message):
  422. '''
  423. Print the message to stderr, it will be prefixed with 'WARNING:'
  424. If stderr is a tty file the 'WARNING:' will be colored
  425. '''
  426. if self.params.get('logger') is not None:
  427. self.params['logger'].warning(message)
  428. else:
  429. if self.params.get('no_warnings'):
  430. return
  431. if self._err_file.isatty() and os.name != 'nt':
  432. _msg_header = '\033[0;33mWARNING:\033[0m'
  433. else:
  434. _msg_header = 'WARNING:'
  435. warning_message = '%s %s' % (_msg_header, message)
  436. self.to_stderr(warning_message)
  437. def report_error(self, message, tb=None):
  438. '''
  439. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  440. in red if stderr is a tty file.
  441. '''
  442. if self._err_file.isatty() and os.name != 'nt':
  443. _msg_header = '\033[0;31mERROR:\033[0m'
  444. else:
  445. _msg_header = 'ERROR:'
  446. error_message = '%s %s' % (_msg_header, message)
  447. self.trouble(error_message, tb)
  448. def report_file_already_downloaded(self, file_name):
  449. """Report file has already been fully downloaded."""
  450. try:
  451. self.to_screen('[download] %s has already been downloaded' % file_name)
  452. except UnicodeEncodeError:
  453. self.to_screen('[download] The file has already been downloaded')
  454. def prepare_filename(self, info_dict):
  455. """Generate the output filename."""
  456. try:
  457. template_dict = dict(info_dict)
  458. template_dict['epoch'] = int(time.time())
  459. autonumber_size = self.params.get('autonumber_size')
  460. if autonumber_size is None:
  461. autonumber_size = 5
  462. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  463. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  464. if template_dict.get('playlist_index') is not None:
  465. template_dict['playlist_index'] = '%0*d' % (len(str(template_dict['n_entries'])), template_dict['playlist_index'])
  466. if template_dict.get('resolution') is None:
  467. if template_dict.get('width') and template_dict.get('height'):
  468. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  469. elif template_dict.get('height'):
  470. template_dict['resolution'] = '%sp' % template_dict['height']
  471. elif template_dict.get('width'):
  472. template_dict['resolution'] = '?x%d' % template_dict['width']
  473. sanitize = lambda k, v: sanitize_filename(
  474. compat_str(v),
  475. restricted=self.params.get('restrictfilenames'),
  476. is_id=(k == 'id'))
  477. template_dict = dict((k, sanitize(k, v))
  478. for k, v in template_dict.items()
  479. if v is not None)
  480. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  481. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  482. tmpl = compat_expanduser(outtmpl)
  483. filename = tmpl % template_dict
  484. return filename
  485. except ValueError as err:
  486. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  487. return None
  488. def _match_entry(self, info_dict):
  489. """ Returns None iff the file should be downloaded """
  490. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  491. if 'title' in info_dict:
  492. # This can happen when we're just evaluating the playlist
  493. title = info_dict['title']
  494. matchtitle = self.params.get('matchtitle', False)
  495. if matchtitle:
  496. if not re.search(matchtitle, title, re.IGNORECASE):
  497. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  498. rejecttitle = self.params.get('rejecttitle', False)
  499. if rejecttitle:
  500. if re.search(rejecttitle, title, re.IGNORECASE):
  501. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  502. date = info_dict.get('upload_date', None)
  503. if date is not None:
  504. dateRange = self.params.get('daterange', DateRange())
  505. if date not in dateRange:
  506. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  507. view_count = info_dict.get('view_count', None)
  508. if view_count is not None:
  509. min_views = self.params.get('min_views')
  510. if min_views is not None and view_count < min_views:
  511. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  512. max_views = self.params.get('max_views')
  513. if max_views is not None and view_count > max_views:
  514. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  515. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  516. return 'Skipping "%s" because it is age restricted' % title
  517. if self.in_download_archive(info_dict):
  518. return '%s has already been recorded in archive' % video_title
  519. return None
  520. @staticmethod
  521. def add_extra_info(info_dict, extra_info):
  522. '''Set the keys from extra_info in info dict if they are missing'''
  523. for key, value in extra_info.items():
  524. info_dict.setdefault(key, value)
  525. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  526. process=True):
  527. '''
  528. Returns a list with a dictionary for each video we find.
  529. If 'download', also downloads the videos.
  530. extra_info is a dict containing the extra values to add to each result
  531. '''
  532. if ie_key:
  533. ies = [self.get_info_extractor(ie_key)]
  534. else:
  535. ies = self._ies
  536. for ie in ies:
  537. if not ie.suitable(url):
  538. continue
  539. if not ie.working():
  540. self.report_warning('The program functionality for this site has been marked as broken, '
  541. 'and will probably not work.')
  542. try:
  543. ie_result = ie.extract(url)
  544. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  545. break
  546. if isinstance(ie_result, list):
  547. # Backwards compatibility: old IE result format
  548. ie_result = {
  549. '_type': 'compat_list',
  550. 'entries': ie_result,
  551. }
  552. self.add_default_extra_info(ie_result, ie, url)
  553. if process:
  554. return self.process_ie_result(ie_result, download, extra_info)
  555. else:
  556. return ie_result
  557. except ExtractorError as de: # An error we somewhat expected
  558. self.report_error(compat_str(de), de.format_traceback())
  559. break
  560. except MaxDownloadsReached:
  561. raise
  562. except Exception as e:
  563. if self.params.get('ignoreerrors', False):
  564. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  565. break
  566. else:
  567. raise
  568. else:
  569. self.report_error('no suitable InfoExtractor for URL %s' % url)
  570. def add_default_extra_info(self, ie_result, ie, url):
  571. self.add_extra_info(ie_result, {
  572. 'extractor': ie.IE_NAME,
  573. 'webpage_url': url,
  574. 'webpage_url_basename': url_basename(url),
  575. 'extractor_key': ie.ie_key(),
  576. })
  577. def process_ie_result(self, ie_result, download=True, extra_info={}):
  578. """
  579. Take the result of the ie(may be modified) and resolve all unresolved
  580. references (URLs, playlist items).
  581. It will also download the videos if 'download'.
  582. Returns the resolved ie_result.
  583. """
  584. result_type = ie_result.get('_type', 'video')
  585. if result_type in ('url', 'url_transparent'):
  586. extract_flat = self.params.get('extract_flat', False)
  587. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or
  588. extract_flat is True):
  589. if self.params.get('forcejson', False):
  590. self.to_stdout(json.dumps(ie_result))
  591. return ie_result
  592. if result_type == 'video':
  593. self.add_extra_info(ie_result, extra_info)
  594. return self.process_video_result(ie_result, download=download)
  595. elif result_type == 'url':
  596. # We have to add extra_info to the results because it may be
  597. # contained in a playlist
  598. return self.extract_info(ie_result['url'],
  599. download,
  600. ie_key=ie_result.get('ie_key'),
  601. extra_info=extra_info)
  602. elif result_type == 'url_transparent':
  603. # Use the information from the embedding page
  604. info = self.extract_info(
  605. ie_result['url'], ie_key=ie_result.get('ie_key'),
  606. extra_info=extra_info, download=False, process=False)
  607. force_properties = dict(
  608. (k, v) for k, v in ie_result.items() if v is not None)
  609. for f in ('_type', 'url'):
  610. if f in force_properties:
  611. del force_properties[f]
  612. new_result = info.copy()
  613. new_result.update(force_properties)
  614. assert new_result.get('_type') != 'url_transparent'
  615. return self.process_ie_result(
  616. new_result, download=download, extra_info=extra_info)
  617. elif result_type == 'playlist' or result_type == 'multi_video':
  618. # We process each entry in the playlist
  619. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  620. self.to_screen('[download] Downloading playlist: %s' % playlist)
  621. playlist_results = []
  622. playliststart = self.params.get('playliststart', 1) - 1
  623. playlistend = self.params.get('playlistend', None)
  624. # For backwards compatibility, interpret -1 as whole list
  625. if playlistend == -1:
  626. playlistend = None
  627. ie_entries = ie_result['entries']
  628. if isinstance(ie_entries, list):
  629. n_all_entries = len(ie_entries)
  630. entries = ie_entries[playliststart:playlistend]
  631. n_entries = len(entries)
  632. self.to_screen(
  633. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  634. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  635. elif isinstance(ie_entries, PagedList):
  636. entries = ie_entries.getslice(
  637. playliststart, playlistend)
  638. n_entries = len(entries)
  639. self.to_screen(
  640. "[%s] playlist %s: Downloading %d videos" %
  641. (ie_result['extractor'], playlist, n_entries))
  642. else: # iterable
  643. entries = list(itertools.islice(
  644. ie_entries, playliststart, playlistend))
  645. n_entries = len(entries)
  646. self.to_screen(
  647. "[%s] playlist %s: Downloading %d videos" %
  648. (ie_result['extractor'], playlist, n_entries))
  649. if self.params.get('playlistreverse', False):
  650. entries = entries[::-1]
  651. for i, entry in enumerate(entries, 1):
  652. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  653. extra = {
  654. 'n_entries': n_entries,
  655. 'playlist': playlist,
  656. 'playlist_id': ie_result.get('id'),
  657. 'playlist_title': ie_result.get('title'),
  658. 'playlist_index': i + playliststart,
  659. 'extractor': ie_result['extractor'],
  660. 'webpage_url': ie_result['webpage_url'],
  661. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  662. 'extractor_key': ie_result['extractor_key'],
  663. }
  664. reason = self._match_entry(entry)
  665. if reason is not None:
  666. self.to_screen('[download] ' + reason)
  667. continue
  668. entry_result = self.process_ie_result(entry,
  669. download=download,
  670. extra_info=extra)
  671. playlist_results.append(entry_result)
  672. ie_result['entries'] = playlist_results
  673. return ie_result
  674. elif result_type == 'compat_list':
  675. self.report_warning(
  676. 'Extractor %s returned a compat_list result. '
  677. 'It needs to be updated.' % ie_result.get('extractor'))
  678. def _fixup(r):
  679. self.add_extra_info(
  680. r,
  681. {
  682. 'extractor': ie_result['extractor'],
  683. 'webpage_url': ie_result['webpage_url'],
  684. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  685. 'extractor_key': ie_result['extractor_key'],
  686. }
  687. )
  688. return r
  689. ie_result['entries'] = [
  690. self.process_ie_result(_fixup(r), download, extra_info)
  691. for r in ie_result['entries']
  692. ]
  693. return ie_result
  694. else:
  695. raise Exception('Invalid result type: %s' % result_type)
  696. def _apply_format_filter(self, format_spec, available_formats):
  697. " Returns a tuple of the remaining format_spec and filtered formats "
  698. OPERATORS = {
  699. '<': operator.lt,
  700. '<=': operator.le,
  701. '>': operator.gt,
  702. '>=': operator.ge,
  703. '=': operator.eq,
  704. '!=': operator.ne,
  705. }
  706. operator_rex = re.compile(r'''(?x)\s*\[
  707. (?P<key>width|height|tbr|abr|vbr|filesize)
  708. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  709. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  710. \]$
  711. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  712. m = operator_rex.search(format_spec)
  713. if not m:
  714. raise ValueError('Invalid format specification %r' % format_spec)
  715. try:
  716. comparison_value = int(m.group('value'))
  717. except ValueError:
  718. comparison_value = parse_filesize(m.group('value'))
  719. if comparison_value is None:
  720. comparison_value = parse_filesize(m.group('value') + 'B')
  721. if comparison_value is None:
  722. raise ValueError(
  723. 'Invalid value %r in format specification %r' % (
  724. m.group('value'), format_spec))
  725. op = OPERATORS[m.group('op')]
  726. def _filter(f):
  727. actual_value = f.get(m.group('key'))
  728. if actual_value is None:
  729. return m.group('none_inclusive')
  730. return op(actual_value, comparison_value)
  731. new_formats = [f for f in available_formats if _filter(f)]
  732. new_format_spec = format_spec[:-len(m.group(0))]
  733. if not new_format_spec:
  734. new_format_spec = 'best'
  735. return (new_format_spec, new_formats)
  736. def select_format(self, format_spec, available_formats):
  737. while format_spec.endswith(']'):
  738. format_spec, available_formats = self._apply_format_filter(
  739. format_spec, available_formats)
  740. if not available_formats:
  741. return None
  742. if format_spec == 'best' or format_spec is None:
  743. return available_formats[-1]
  744. elif format_spec == 'worst':
  745. return available_formats[0]
  746. elif format_spec == 'bestaudio':
  747. audio_formats = [
  748. f for f in available_formats
  749. if f.get('vcodec') == 'none']
  750. if audio_formats:
  751. return audio_formats[-1]
  752. elif format_spec == 'worstaudio':
  753. audio_formats = [
  754. f for f in available_formats
  755. if f.get('vcodec') == 'none']
  756. if audio_formats:
  757. return audio_formats[0]
  758. elif format_spec == 'bestvideo':
  759. video_formats = [
  760. f for f in available_formats
  761. if f.get('acodec') == 'none']
  762. if video_formats:
  763. return video_formats[-1]
  764. elif format_spec == 'worstvideo':
  765. video_formats = [
  766. f for f in available_formats
  767. if f.get('acodec') == 'none']
  768. if video_formats:
  769. return video_formats[0]
  770. else:
  771. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  772. if format_spec in extensions:
  773. filter_f = lambda f: f['ext'] == format_spec
  774. else:
  775. filter_f = lambda f: f['format_id'] == format_spec
  776. matches = list(filter(filter_f, available_formats))
  777. if matches:
  778. return matches[-1]
  779. return None
  780. def _calc_headers(self, info_dict):
  781. res = std_headers.copy()
  782. add_headers = info_dict.get('http_headers')
  783. if add_headers:
  784. res.update(add_headers)
  785. cookies = self._calc_cookies(info_dict)
  786. if cookies:
  787. res['Cookie'] = cookies
  788. return res
  789. def _calc_cookies(self, info_dict):
  790. class _PseudoRequest(object):
  791. def __init__(self, url):
  792. self.url = url
  793. self.headers = {}
  794. self.unverifiable = False
  795. def add_unredirected_header(self, k, v):
  796. self.headers[k] = v
  797. def get_full_url(self):
  798. return self.url
  799. def has_header(self, h):
  800. return h in self.headers
  801. pr = _PseudoRequest(info_dict['url'])
  802. self.cookiejar.add_cookie_header(pr)
  803. return pr.headers.get('Cookie')
  804. def process_video_result(self, info_dict, download=True):
  805. assert info_dict.get('_type', 'video') == 'video'
  806. if 'id' not in info_dict:
  807. raise ExtractorError('Missing "id" field in extractor result')
  808. if 'title' not in info_dict:
  809. raise ExtractorError('Missing "title" field in extractor result')
  810. if 'playlist' not in info_dict:
  811. # It isn't part of a playlist
  812. info_dict['playlist'] = None
  813. info_dict['playlist_index'] = None
  814. thumbnails = info_dict.get('thumbnails')
  815. if thumbnails:
  816. thumbnails.sort(key=lambda t: (
  817. t.get('width'), t.get('height'), t.get('url')))
  818. for t in thumbnails:
  819. if 'width' in t and 'height' in t:
  820. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  821. if thumbnails and 'thumbnail' not in info_dict:
  822. info_dict['thumbnail'] = thumbnails[-1]['url']
  823. if 'display_id' not in info_dict and 'id' in info_dict:
  824. info_dict['display_id'] = info_dict['id']
  825. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  826. # Working around negative timestamps in Windows
  827. # (see http://bugs.python.org/issue1646728)
  828. if info_dict['timestamp'] < 0 and os.name == 'nt':
  829. info_dict['timestamp'] = 0
  830. upload_date = datetime.datetime.utcfromtimestamp(
  831. info_dict['timestamp'])
  832. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  833. # This extractors handle format selection themselves
  834. if info_dict['extractor'] in ['Youku']:
  835. if download:
  836. self.process_info(info_dict)
  837. return info_dict
  838. # We now pick which formats have to be downloaded
  839. if info_dict.get('formats') is None:
  840. # There's only one format available
  841. formats = [info_dict]
  842. else:
  843. formats = info_dict['formats']
  844. if not formats:
  845. raise ExtractorError('No video formats found!')
  846. # We check that all the formats have the format and format_id fields
  847. for i, format in enumerate(formats):
  848. if 'url' not in format:
  849. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  850. if format.get('format_id') is None:
  851. format['format_id'] = compat_str(i)
  852. if format.get('format') is None:
  853. format['format'] = '{id} - {res}{note}'.format(
  854. id=format['format_id'],
  855. res=self.format_resolution(format),
  856. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  857. )
  858. # Automatically determine file extension if missing
  859. if 'ext' not in format:
  860. format['ext'] = determine_ext(format['url']).lower()
  861. # Add HTTP headers, so that external programs can use them from the
  862. # json output
  863. full_format_info = info_dict.copy()
  864. full_format_info.update(format)
  865. format['http_headers'] = self._calc_headers(full_format_info)
  866. format_limit = self.params.get('format_limit', None)
  867. if format_limit:
  868. formats = list(takewhile_inclusive(
  869. lambda f: f['format_id'] != format_limit, formats
  870. ))
  871. # TODO Central sorting goes here
  872. if formats[0] is not info_dict:
  873. # only set the 'formats' fields if the original info_dict list them
  874. # otherwise we end up with a circular reference, the first (and unique)
  875. # element in the 'formats' field in info_dict is info_dict itself,
  876. # wich can't be exported to json
  877. info_dict['formats'] = formats
  878. if self.params.get('listformats', None):
  879. self.list_formats(info_dict)
  880. return
  881. req_format = self.params.get('format')
  882. if req_format is None:
  883. req_format = 'best'
  884. formats_to_download = []
  885. # The -1 is for supporting YoutubeIE
  886. if req_format in ('-1', 'all'):
  887. formats_to_download = formats
  888. else:
  889. for rfstr in req_format.split(','):
  890. # We can accept formats requested in the format: 34/5/best, we pick
  891. # the first that is available, starting from left
  892. req_formats = rfstr.split('/')
  893. for rf in req_formats:
  894. if re.match(r'.+?\+.+?', rf) is not None:
  895. # Two formats have been requested like '137+139'
  896. format_1, format_2 = rf.split('+')
  897. formats_info = (self.select_format(format_1, formats),
  898. self.select_format(format_2, formats))
  899. if all(formats_info):
  900. # The first format must contain the video and the
  901. # second the audio
  902. if formats_info[0].get('vcodec') == 'none':
  903. self.report_error('The first format must '
  904. 'contain the video, try using '
  905. '"-f %s+%s"' % (format_2, format_1))
  906. return
  907. output_ext = (
  908. formats_info[0]['ext']
  909. if self.params.get('merge_output_format') is None
  910. else self.params['merge_output_format'])
  911. selected_format = {
  912. 'requested_formats': formats_info,
  913. 'format': rf,
  914. 'ext': formats_info[0]['ext'],
  915. 'width': formats_info[0].get('width'),
  916. 'height': formats_info[0].get('height'),
  917. 'resolution': formats_info[0].get('resolution'),
  918. 'fps': formats_info[0].get('fps'),
  919. 'vcodec': formats_info[0].get('vcodec'),
  920. 'vbr': formats_info[0].get('vbr'),
  921. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  922. 'acodec': formats_info[1].get('acodec'),
  923. 'abr': formats_info[1].get('abr'),
  924. 'ext': output_ext,
  925. }
  926. else:
  927. selected_format = None
  928. else:
  929. selected_format = self.select_format(rf, formats)
  930. if selected_format is not None:
  931. formats_to_download.append(selected_format)
  932. break
  933. if not formats_to_download:
  934. raise ExtractorError('requested format not available',
  935. expected=True)
  936. if download:
  937. if len(formats_to_download) > 1:
  938. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  939. for format in formats_to_download:
  940. new_info = dict(info_dict)
  941. new_info.update(format)
  942. self.process_info(new_info)
  943. # We update the info dict with the best quality format (backwards compatibility)
  944. info_dict.update(formats_to_download[-1])
  945. return info_dict
  946. def process_info(self, info_dict):
  947. """Process a single resolved IE result."""
  948. assert info_dict.get('_type', 'video') == 'video'
  949. max_downloads = self.params.get('max_downloads')
  950. if max_downloads is not None:
  951. if self._num_downloads >= int(max_downloads):
  952. raise MaxDownloadsReached()
  953. info_dict['fulltitle'] = info_dict['title']
  954. if len(info_dict['title']) > 200:
  955. info_dict['title'] = info_dict['title'][:197] + '...'
  956. # Keep for backwards compatibility
  957. info_dict['stitle'] = info_dict['title']
  958. if 'format' not in info_dict:
  959. info_dict['format'] = info_dict['ext']
  960. reason = self._match_entry(info_dict)
  961. if reason is not None:
  962. self.to_screen('[download] ' + reason)
  963. return
  964. self._num_downloads += 1
  965. filename = self.prepare_filename(info_dict)
  966. # Forced printings
  967. if self.params.get('forcetitle', False):
  968. self.to_stdout(info_dict['fulltitle'])
  969. if self.params.get('forceid', False):
  970. self.to_stdout(info_dict['id'])
  971. if self.params.get('forceurl', False):
  972. if info_dict.get('requested_formats') is not None:
  973. for f in info_dict['requested_formats']:
  974. self.to_stdout(f['url'] + f.get('play_path', ''))
  975. else:
  976. # For RTMP URLs, also include the playpath
  977. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  978. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  979. self.to_stdout(info_dict['thumbnail'])
  980. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  981. self.to_stdout(info_dict['description'])
  982. if self.params.get('forcefilename', False) and filename is not None:
  983. self.to_stdout(filename)
  984. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  985. self.to_stdout(formatSeconds(info_dict['duration']))
  986. if self.params.get('forceformat', False):
  987. self.to_stdout(info_dict['format'])
  988. if self.params.get('forcejson', False):
  989. info_dict['_filename'] = filename
  990. self.to_stdout(json.dumps(info_dict))
  991. if self.params.get('dump_single_json', False):
  992. info_dict['_filename'] = filename
  993. # Do nothing else if in simulate mode
  994. if self.params.get('simulate', False):
  995. return
  996. if filename is None:
  997. return
  998. try:
  999. dn = os.path.dirname(encodeFilename(filename))
  1000. if dn and not os.path.exists(dn):
  1001. os.makedirs(dn)
  1002. except (OSError, IOError) as err:
  1003. self.report_error('unable to create directory ' + compat_str(err))
  1004. return
  1005. if self.params.get('writedescription', False):
  1006. descfn = filename + '.description'
  1007. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1008. self.to_screen('[info] Video description is already present')
  1009. elif info_dict.get('description') is None:
  1010. self.report_warning('There\'s no description to write.')
  1011. else:
  1012. try:
  1013. self.to_screen('[info] Writing video description to: ' + descfn)
  1014. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1015. descfile.write(info_dict['description'])
  1016. except (OSError, IOError):
  1017. self.report_error('Cannot write description file ' + descfn)
  1018. return
  1019. if self.params.get('writeannotations', False):
  1020. annofn = filename + '.annotations.xml'
  1021. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1022. self.to_screen('[info] Video annotations are already present')
  1023. else:
  1024. try:
  1025. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1026. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1027. annofile.write(info_dict['annotations'])
  1028. except (KeyError, TypeError):
  1029. self.report_warning('There are no annotations to write.')
  1030. except (OSError, IOError):
  1031. self.report_error('Cannot write annotations file: ' + annofn)
  1032. return
  1033. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1034. self.params.get('writeautomaticsub')])
  1035. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  1036. # subtitles download errors are already managed as troubles in relevant IE
  1037. # that way it will silently go on when used with unsupporting IE
  1038. subtitles = info_dict['subtitles']
  1039. sub_format = self.params.get('subtitlesformat', 'srt')
  1040. for sub_lang in subtitles.keys():
  1041. sub = subtitles[sub_lang]
  1042. if sub is None:
  1043. continue
  1044. try:
  1045. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  1046. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1047. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  1048. else:
  1049. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1050. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  1051. subfile.write(sub)
  1052. except (OSError, IOError):
  1053. self.report_error('Cannot write subtitles file ' + sub_filename)
  1054. return
  1055. if self.params.get('writeinfojson', False):
  1056. infofn = os.path.splitext(filename)[0] + '.info.json'
  1057. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1058. self.to_screen('[info] Video description metadata is already present')
  1059. else:
  1060. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1061. try:
  1062. write_json_file(info_dict, infofn)
  1063. except (OSError, IOError):
  1064. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1065. return
  1066. if self.params.get('writethumbnail', False):
  1067. if info_dict.get('thumbnail') is not None:
  1068. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  1069. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  1070. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  1071. self.to_screen('[%s] %s: Thumbnail is already present' %
  1072. (info_dict['extractor'], info_dict['id']))
  1073. else:
  1074. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  1075. (info_dict['extractor'], info_dict['id']))
  1076. try:
  1077. uf = self.urlopen(info_dict['thumbnail'])
  1078. with open(thumb_filename, 'wb') as thumbf:
  1079. shutil.copyfileobj(uf, thumbf)
  1080. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  1081. (info_dict['extractor'], info_dict['id'], thumb_filename))
  1082. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1083. self.report_warning('Unable to download thumbnail "%s": %s' %
  1084. (info_dict['thumbnail'], compat_str(err)))
  1085. if not self.params.get('skip_download', False):
  1086. try:
  1087. def dl(name, info):
  1088. fd = get_suitable_downloader(info, self.params)(self, self.params)
  1089. for ph in self._progress_hooks:
  1090. fd.add_progress_hook(ph)
  1091. if self.params.get('verbose'):
  1092. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  1093. return fd.download(name, info)
  1094. if info_dict.get('requested_formats') is not None:
  1095. downloaded = []
  1096. success = True
  1097. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  1098. if not merger._executable:
  1099. postprocessors = []
  1100. self.report_warning('You have requested multiple '
  1101. 'formats but ffmpeg or avconv are not installed.'
  1102. ' The formats won\'t be merged')
  1103. else:
  1104. postprocessors = [merger]
  1105. for f in info_dict['requested_formats']:
  1106. new_info = dict(info_dict)
  1107. new_info.update(f)
  1108. fname = self.prepare_filename(new_info)
  1109. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  1110. downloaded.append(fname)
  1111. partial_success = dl(fname, new_info)
  1112. success = success and partial_success
  1113. info_dict['__postprocessors'] = postprocessors
  1114. info_dict['__files_to_merge'] = downloaded
  1115. else:
  1116. # Just a single file
  1117. success = dl(filename, info_dict)
  1118. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1119. self.report_error('unable to download video data: %s' % str(err))
  1120. return
  1121. except (OSError, IOError) as err:
  1122. raise UnavailableVideoError(err)
  1123. except (ContentTooShortError, ) as err:
  1124. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1125. return
  1126. if success:
  1127. # Fixup content
  1128. fixup_policy = self.params.get('fixup')
  1129. if fixup_policy is None:
  1130. fixup_policy = 'detect_or_warn'
  1131. stretched_ratio = info_dict.get('stretched_ratio')
  1132. if stretched_ratio is not None and stretched_ratio != 1:
  1133. if fixup_policy == 'warn':
  1134. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1135. info_dict['id'], stretched_ratio))
  1136. elif fixup_policy == 'detect_or_warn':
  1137. stretched_pp = FFmpegFixupStretchedPP(self)
  1138. if stretched_pp.available:
  1139. info_dict.setdefault('__postprocessors', [])
  1140. info_dict['__postprocessors'].append(stretched_pp)
  1141. else:
  1142. self.report_warning(
  1143. '%s: Non-uniform pixel ratio (%s). Install ffmpeg or avconv to fix this automatically.' % (
  1144. info_dict['id'], stretched_ratio))
  1145. else:
  1146. assert fixup_policy in ('ignore', 'never')
  1147. if info_dict.get('requested_formats') is None and info_dict.get('container') == 'm4a_dash':
  1148. if fixup_policy == 'warn':
  1149. self.report_warning('%s: writing DASH m4a. Only some players support this container.' % (
  1150. info_dict['id']))
  1151. elif fixup_policy == 'detect_or_warn':
  1152. fixup_pp = FFmpegFixupM4aPP(self)
  1153. if fixup_pp.available:
  1154. info_dict.setdefault('__postprocessors', [])
  1155. info_dict['__postprocessors'].append(fixup_pp)
  1156. else:
  1157. self.report_warning(
  1158. '%s: writing DASH m4a. Only some players support this container. Install ffmpeg or avconv to fix this automatically.' % (
  1159. info_dict['id']))
  1160. else:
  1161. assert fixup_policy in ('ignore', 'never')
  1162. try:
  1163. self.post_process(filename, info_dict)
  1164. except (PostProcessingError) as err:
  1165. self.report_error('postprocessing: %s' % str(err))
  1166. return
  1167. self.record_download_archive(info_dict)
  1168. def download(self, url_list):
  1169. """Download a given list of URLs."""
  1170. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1171. if (len(url_list) > 1 and
  1172. '%' not in outtmpl
  1173. and self.params.get('max_downloads') != 1):
  1174. raise SameFileError(outtmpl)
  1175. for url in url_list:
  1176. try:
  1177. # It also downloads the videos
  1178. res = self.extract_info(url)
  1179. except UnavailableVideoError:
  1180. self.report_error('unable to download video')
  1181. except MaxDownloadsReached:
  1182. self.to_screen('[info] Maximum number of downloaded files reached.')
  1183. raise
  1184. else:
  1185. if self.params.get('dump_single_json', False):
  1186. self.to_stdout(json.dumps(res))
  1187. return self._download_retcode
  1188. def download_with_info_file(self, info_filename):
  1189. with io.open(info_filename, 'r', encoding='utf-8') as f:
  1190. info = json.load(f)
  1191. try:
  1192. self.process_ie_result(info, download=True)
  1193. except DownloadError:
  1194. webpage_url = info.get('webpage_url')
  1195. if webpage_url is not None:
  1196. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1197. return self.download([webpage_url])
  1198. else:
  1199. raise
  1200. return self._download_retcode
  1201. def post_process(self, filename, ie_info):
  1202. """Run all the postprocessors on the given file."""
  1203. info = dict(ie_info)
  1204. info['filepath'] = filename
  1205. pps_chain = []
  1206. if ie_info.get('__postprocessors') is not None:
  1207. pps_chain.extend(ie_info['__postprocessors'])
  1208. pps_chain.extend(self._pps)
  1209. for pp in pps_chain:
  1210. keep_video = None
  1211. old_filename = info['filepath']
  1212. try:
  1213. keep_video_wish, info = pp.run(info)
  1214. if keep_video_wish is not None:
  1215. if keep_video_wish:
  1216. keep_video = keep_video_wish
  1217. elif keep_video is None:
  1218. # No clear decision yet, let IE decide
  1219. keep_video = keep_video_wish
  1220. except PostProcessingError as e:
  1221. self.report_error(e.msg)
  1222. if keep_video is False and not self.params.get('keepvideo', False):
  1223. try:
  1224. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1225. os.remove(encodeFilename(old_filename))
  1226. except (IOError, OSError):
  1227. self.report_warning('Unable to remove downloaded video file')
  1228. def _make_archive_id(self, info_dict):
  1229. # Future-proof against any change in case
  1230. # and backwards compatibility with prior versions
  1231. extractor = info_dict.get('extractor_key')
  1232. if extractor is None:
  1233. if 'id' in info_dict:
  1234. extractor = info_dict.get('ie_key') # key in a playlist
  1235. if extractor is None:
  1236. return None # Incomplete video information
  1237. return extractor.lower() + ' ' + info_dict['id']
  1238. def in_download_archive(self, info_dict):
  1239. fn = self.params.get('download_archive')
  1240. if fn is None:
  1241. return False
  1242. vid_id = self._make_archive_id(info_dict)
  1243. if vid_id is None:
  1244. return False # Incomplete video information
  1245. try:
  1246. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1247. for line in archive_file:
  1248. if line.strip() == vid_id:
  1249. return True
  1250. except IOError as ioe:
  1251. if ioe.errno != errno.ENOENT:
  1252. raise
  1253. return False
  1254. def record_download_archive(self, info_dict):
  1255. fn = self.params.get('download_archive')
  1256. if fn is None:
  1257. return
  1258. vid_id = self._make_archive_id(info_dict)
  1259. assert vid_id
  1260. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1261. archive_file.write(vid_id + '\n')
  1262. @staticmethod
  1263. def format_resolution(format, default='unknown'):
  1264. if format.get('vcodec') == 'none':
  1265. return 'audio only'
  1266. if format.get('resolution') is not None:
  1267. return format['resolution']
  1268. if format.get('height') is not None:
  1269. if format.get('width') is not None:
  1270. res = '%sx%s' % (format['width'], format['height'])
  1271. else:
  1272. res = '%sp' % format['height']
  1273. elif format.get('width') is not None:
  1274. res = '?x%d' % format['width']
  1275. else:
  1276. res = default
  1277. return res
  1278. def _format_note(self, fdict):
  1279. res = ''
  1280. if fdict.get('ext') in ['f4f', 'f4m']:
  1281. res += '(unsupported) '
  1282. if fdict.get('format_note') is not None:
  1283. res += fdict['format_note'] + ' '
  1284. if fdict.get('tbr') is not None:
  1285. res += '%4dk ' % fdict['tbr']
  1286. if fdict.get('container') is not None:
  1287. if res:
  1288. res += ', '
  1289. res += '%s container' % fdict['container']
  1290. if (fdict.get('vcodec') is not None and
  1291. fdict.get('vcodec') != 'none'):
  1292. if res:
  1293. res += ', '
  1294. res += fdict['vcodec']
  1295. if fdict.get('vbr') is not None:
  1296. res += '@'
  1297. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1298. res += 'video@'
  1299. if fdict.get('vbr') is not None:
  1300. res += '%4dk' % fdict['vbr']
  1301. if fdict.get('fps') is not None:
  1302. res += ', %sfps' % fdict['fps']
  1303. if fdict.get('acodec') is not None:
  1304. if res:
  1305. res += ', '
  1306. if fdict['acodec'] == 'none':
  1307. res += 'video only'
  1308. else:
  1309. res += '%-5s' % fdict['acodec']
  1310. elif fdict.get('abr') is not None:
  1311. if res:
  1312. res += ', '
  1313. res += 'audio'
  1314. if fdict.get('abr') is not None:
  1315. res += '@%3dk' % fdict['abr']
  1316. if fdict.get('asr') is not None:
  1317. res += ' (%5dHz)' % fdict['asr']
  1318. if fdict.get('filesize') is not None:
  1319. if res:
  1320. res += ', '
  1321. res += format_bytes(fdict['filesize'])
  1322. elif fdict.get('filesize_approx') is not None:
  1323. if res:
  1324. res += ', '
  1325. res += '~' + format_bytes(fdict['filesize_approx'])
  1326. return res
  1327. def list_formats(self, info_dict):
  1328. def line(format, idlen=20):
  1329. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1330. format['format_id'],
  1331. format['ext'],
  1332. self.format_resolution(format),
  1333. self._format_note(format),
  1334. ))
  1335. formats = info_dict.get('formats', [info_dict])
  1336. idlen = max(len('format code'),
  1337. max(len(f['format_id']) for f in formats))
  1338. formats_s = [
  1339. line(f, idlen) for f in formats
  1340. if f.get('preference') is None or f['preference'] >= -1000]
  1341. if len(formats) > 1:
  1342. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1343. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1344. header_line = line({
  1345. 'format_id': 'format code', 'ext': 'extension',
  1346. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1347. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1348. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1349. def urlopen(self, req):
  1350. """ Start an HTTP download """
  1351. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1352. # always respected by websites, some tend to give out URLs with non percent-encoded
  1353. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1354. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1355. # To work around aforementioned issue we will replace request's original URL with
  1356. # percent-encoded one
  1357. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1358. url = req if req_is_string else req.get_full_url()
  1359. url_escaped = escape_url(url)
  1360. # Substitute URL if any change after escaping
  1361. if url != url_escaped:
  1362. if req_is_string:
  1363. req = url_escaped
  1364. else:
  1365. req = compat_urllib_request.Request(
  1366. url_escaped, data=req.data, headers=req.headers,
  1367. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1368. return self._opener.open(req, timeout=self._socket_timeout)
  1369. def print_debug_header(self):
  1370. if not self.params.get('verbose'):
  1371. return
  1372. if type('') is not compat_str:
  1373. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1374. self.report_warning(
  1375. 'Your Python is broken! Update to a newer and supported version')
  1376. stdout_encoding = getattr(
  1377. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1378. encoding_str = (
  1379. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1380. locale.getpreferredencoding(),
  1381. sys.getfilesystemencoding(),
  1382. stdout_encoding,
  1383. self.get_encoding()))
  1384. write_string(encoding_str, encoding=None)
  1385. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1386. try:
  1387. sp = subprocess.Popen(
  1388. ['git', 'rev-parse', '--short', 'HEAD'],
  1389. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1390. cwd=os.path.dirname(os.path.abspath(__file__)))
  1391. out, err = sp.communicate()
  1392. out = out.decode().strip()
  1393. if re.match('[0-9a-f]+', out):
  1394. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1395. except:
  1396. try:
  1397. sys.exc_clear()
  1398. except:
  1399. pass
  1400. self._write_string('[debug] Python version %s - %s\n' % (
  1401. platform.python_version(), platform_name()))
  1402. exe_versions = FFmpegPostProcessor.get_versions()
  1403. exe_versions['rtmpdump'] = rtmpdump_version()
  1404. exe_str = ', '.join(
  1405. '%s %s' % (exe, v)
  1406. for exe, v in sorted(exe_versions.items())
  1407. if v
  1408. )
  1409. if not exe_str:
  1410. exe_str = 'none'
  1411. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1412. proxy_map = {}
  1413. for handler in self._opener.handlers:
  1414. if hasattr(handler, 'proxies'):
  1415. proxy_map.update(handler.proxies)
  1416. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1417. if self.params.get('call_home', False):
  1418. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  1419. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  1420. latest_version = self.urlopen(
  1421. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  1422. if version_tuple(latest_version) > version_tuple(__version__):
  1423. self.report_warning(
  1424. 'You are using an outdated version (newest version: %s)! '
  1425. 'See https://yt-dl.org/update if you need help updating.' %
  1426. latest_version)
  1427. def _setup_opener(self):
  1428. timeout_val = self.params.get('socket_timeout')
  1429. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1430. opts_cookiefile = self.params.get('cookiefile')
  1431. opts_proxy = self.params.get('proxy')
  1432. if opts_cookiefile is None:
  1433. self.cookiejar = compat_cookiejar.CookieJar()
  1434. else:
  1435. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1436. opts_cookiefile)
  1437. if os.access(opts_cookiefile, os.R_OK):
  1438. self.cookiejar.load()
  1439. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1440. self.cookiejar)
  1441. if opts_proxy is not None:
  1442. if opts_proxy == '':
  1443. proxies = {}
  1444. else:
  1445. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1446. else:
  1447. proxies = compat_urllib_request.getproxies()
  1448. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1449. if 'http' in proxies and 'https' not in proxies:
  1450. proxies['https'] = proxies['http']
  1451. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1452. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1453. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  1454. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  1455. opener = compat_urllib_request.build_opener(
  1456. https_handler, proxy_handler, cookie_processor, ydlh)
  1457. # Delete the default user-agent header, which would otherwise apply in
  1458. # cases where our custom HTTP handler doesn't come into play
  1459. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1460. opener.addheaders = []
  1461. self._opener = opener
  1462. def encode(self, s):
  1463. if isinstance(s, bytes):
  1464. return s # Already encoded
  1465. try:
  1466. return s.encode(self.get_encoding())
  1467. except UnicodeEncodeError as err:
  1468. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1469. raise
  1470. def get_encoding(self):
  1471. encoding = self.params.get('encoding')
  1472. if encoding is None:
  1473. encoding = preferredencoding()
  1474. return encoding