YoutubeDL.py 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import contextlib
  6. import copy
  7. import datetime
  8. import errno
  9. import fileinput
  10. import io
  11. import itertools
  12. import json
  13. import locale
  14. import operator
  15. import os
  16. import platform
  17. import re
  18. import shutil
  19. import subprocess
  20. import socket
  21. import sys
  22. import time
  23. import tokenize
  24. import traceback
  25. import random
  26. from string import ascii_letters
  27. from .compat import (
  28. compat_basestring,
  29. compat_cookiejar,
  30. compat_get_terminal_size,
  31. compat_http_client,
  32. compat_kwargs,
  33. compat_numeric_types,
  34. compat_os_name,
  35. compat_str,
  36. compat_tokenize_tokenize,
  37. compat_urllib_error,
  38. compat_urllib_request,
  39. compat_urllib_request_DataHandler,
  40. )
  41. from .utils import (
  42. age_restricted,
  43. args_to_str,
  44. ContentTooShortError,
  45. date_from_str,
  46. DateRange,
  47. DEFAULT_OUTTMPL,
  48. determine_ext,
  49. determine_protocol,
  50. DownloadError,
  51. encode_compat_str,
  52. encodeFilename,
  53. error_to_compat_str,
  54. expand_path,
  55. ExtractorError,
  56. format_bytes,
  57. formatSeconds,
  58. GeoRestrictedError,
  59. int_or_none,
  60. ISO3166Utils,
  61. locked_file,
  62. make_HTTPS_handler,
  63. MaxDownloadsReached,
  64. orderedSet,
  65. PagedList,
  66. parse_filesize,
  67. PerRequestProxyHandler,
  68. platform_name,
  69. PostProcessingError,
  70. preferredencoding,
  71. prepend_extension,
  72. process_communicate_or_kill,
  73. register_socks_protocols,
  74. render_table,
  75. replace_extension,
  76. SameFileError,
  77. sanitize_filename,
  78. sanitize_path,
  79. sanitize_url,
  80. sanitized_Request,
  81. std_headers,
  82. str_or_none,
  83. subtitles_filename,
  84. UnavailableVideoError,
  85. url_basename,
  86. variadic,
  87. version_tuple,
  88. write_json_file,
  89. write_string,
  90. YoutubeDLCookieJar,
  91. YoutubeDLCookieProcessor,
  92. YoutubeDLHandler,
  93. YoutubeDLRedirectHandler,
  94. )
  95. from .cache import Cache
  96. from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER
  97. from .extractor.openload import PhantomJSwrapper
  98. from .downloader import get_suitable_downloader
  99. from .downloader.rtmp import rtmpdump_version
  100. from .postprocessor import (
  101. FFmpegFixupM3u8PP,
  102. FFmpegFixupM4aPP,
  103. FFmpegFixupStretchedPP,
  104. FFmpegMergerPP,
  105. FFmpegPostProcessor,
  106. get_postprocessor,
  107. )
  108. from .version import __version__
  109. if compat_os_name == 'nt':
  110. import ctypes
  111. class YoutubeDL(object):
  112. """YoutubeDL class.
  113. YoutubeDL objects are the ones responsible of downloading the
  114. actual video file and writing it to disk if the user has requested
  115. it, among some other tasks. In most cases there should be one per
  116. program. As, given a video URL, the downloader doesn't know how to
  117. extract all the needed information, task that InfoExtractors do, it
  118. has to pass the URL to one of them.
  119. For this, YoutubeDL objects have a method that allows
  120. InfoExtractors to be registered in a given order. When it is passed
  121. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  122. finds that reports being able to handle it. The InfoExtractor extracts
  123. all the information about the video or videos the URL refers to, and
  124. YoutubeDL process the extracted information, possibly using a File
  125. Downloader to download the video.
  126. YoutubeDL objects accept a lot of parameters. In order not to saturate
  127. the object constructor with arguments, it receives a dictionary of
  128. options instead. These options are available through the params
  129. attribute for the InfoExtractors to use. The YoutubeDL also
  130. registers itself as the downloader in charge for the InfoExtractors
  131. that are added to it, so this is a "mutual registration".
  132. Available options:
  133. username: Username for authentication purposes.
  134. password: Password for authentication purposes.
  135. videopassword: Password for accessing a video.
  136. ap_mso: Adobe Pass multiple-system operator identifier.
  137. ap_username: Multiple-system operator account username.
  138. ap_password: Multiple-system operator account password.
  139. usenetrc: Use netrc for authentication instead.
  140. verbose: Print additional info to stdout.
  141. quiet: Do not print messages to stdout.
  142. no_warnings: Do not print out anything for warnings.
  143. forceurl: Force printing final URL.
  144. forcetitle: Force printing title.
  145. forceid: Force printing ID.
  146. forcethumbnail: Force printing thumbnail URL.
  147. forcedescription: Force printing description.
  148. forcefilename: Force printing final filename.
  149. forceduration: Force printing duration.
  150. forcejson: Force printing info_dict as JSON.
  151. dump_single_json: Force printing the info_dict of the whole playlist
  152. (or video) as a single JSON line.
  153. simulate: Do not download the video files.
  154. format: Video format code. See options.py for more information.
  155. outtmpl: Template for output names.
  156. outtmpl_na_placeholder: Placeholder for unavailable meta fields.
  157. restrictfilenames: Do not allow "&" and spaces in file names
  158. ignoreerrors: Do not stop on download errors.
  159. force_generic_extractor: Force downloader to use the generic extractor
  160. nooverwrites: Prevent overwriting files.
  161. playliststart: Playlist item to start at.
  162. playlistend: Playlist item to end at.
  163. playlist_items: Specific indices of playlist to download.
  164. playlistreverse: Download playlist items in reverse order.
  165. playlistrandom: Download playlist items in random order.
  166. matchtitle: Download only matching titles.
  167. rejecttitle: Reject downloads for matching titles.
  168. logger: Log messages to a logging.Logger instance.
  169. logtostderr: Log messages to stderr instead of stdout.
  170. writedescription: Write the video description to a .description file
  171. writeinfojson: Write the video description to a .info.json file
  172. writeannotations: Write the video annotations to a .annotations.xml file
  173. writethumbnail: Write the thumbnail image to a file
  174. write_all_thumbnails: Write all thumbnail formats to files
  175. writesubtitles: Write the video subtitles to a file
  176. writeautomaticsub: Write the automatically generated subtitles to a file
  177. allsubtitles: Downloads all the subtitles of the video
  178. (requires writesubtitles or writeautomaticsub)
  179. listsubtitles: Lists all available subtitles for the video
  180. subtitlesformat: The format code for subtitles
  181. subtitleslangs: List of languages of the subtitles to download
  182. keepvideo: Keep the video file after post-processing
  183. daterange: A DateRange object, download only if the upload_date is in the range.
  184. skip_download: Skip the actual download of the video file
  185. cachedir: Location of the cache files in the filesystem.
  186. False to disable filesystem cache.
  187. noplaylist: Download single video instead of a playlist if in doubt.
  188. age_limit: An integer representing the user's age in years.
  189. Unsuitable videos for the given age are skipped.
  190. min_views: An integer representing the minimum view count the video
  191. must have in order to not be skipped.
  192. Videos without view count information are always
  193. downloaded. None for no limit.
  194. max_views: An integer representing the maximum view count.
  195. Videos that are more popular than that are not
  196. downloaded.
  197. Videos without view count information are always
  198. downloaded. None for no limit.
  199. download_archive: File name of a file where all downloads are recorded.
  200. Videos already present in the file are not downloaded
  201. again.
  202. cookiefile: File name where cookies should be read from and dumped to.
  203. nocheckcertificate:Do not verify SSL certificates
  204. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  205. At the moment, this is only supported by YouTube.
  206. proxy: URL of the proxy server to use
  207. geo_verification_proxy: URL of the proxy to use for IP address verification
  208. on geo-restricted sites.
  209. socket_timeout: Time to wait for unresponsive hosts, in seconds
  210. bidi_workaround: Work around buggy terminals without bidirectional text
  211. support, using fridibi
  212. debug_printtraffic:Print out sent and received HTTP traffic
  213. include_ads: Download ads as well
  214. default_search: Prepend this string if an input url is not valid.
  215. 'auto' for elaborate guessing
  216. encoding: Use this encoding instead of the system-specified.
  217. extract_flat: Do not resolve URLs, return the immediate result.
  218. Pass in 'in_playlist' to only show this behavior for
  219. playlist items.
  220. postprocessors: A list of dictionaries, each with an entry
  221. * key: The name of the postprocessor. See
  222. youtube_dl/postprocessor/__init__.py for a list.
  223. as well as any further keyword arguments for the
  224. postprocessor.
  225. progress_hooks: A list of functions that get called on download
  226. progress, with a dictionary with the entries
  227. * status: One of "downloading", "error", or "finished".
  228. Check this first and ignore unknown values.
  229. If status is one of "downloading", or "finished", the
  230. following properties may also be present:
  231. * filename: The final filename (always present)
  232. * tmpfilename: The filename we're currently writing to
  233. * downloaded_bytes: Bytes on disk
  234. * total_bytes: Size of the whole file, None if unknown
  235. * total_bytes_estimate: Guess of the eventual file size,
  236. None if unavailable.
  237. * elapsed: The number of seconds since download started.
  238. * eta: The estimated time in seconds, None if unknown
  239. * speed: The download speed in bytes/second, None if
  240. unknown
  241. * fragment_index: The counter of the currently
  242. downloaded video fragment.
  243. * fragment_count: The number of fragments (= individual
  244. files that will be merged)
  245. Progress hooks are guaranteed to be called at least once
  246. (with status "finished") if the download is successful.
  247. merge_output_format: Extension to use when merging formats.
  248. fixup: Automatically correct known faults of the file.
  249. One of:
  250. - "never": do nothing
  251. - "warn": only emit a warning
  252. - "detect_or_warn": check whether we can do anything
  253. about it, warn otherwise (default)
  254. source_address: Client-side IP address to bind to.
  255. call_home: Boolean, true iff we are allowed to contact the
  256. youtube-dl servers for debugging.
  257. sleep_interval: Number of seconds to sleep before each download when
  258. used alone or a lower bound of a range for randomized
  259. sleep before each download (minimum possible number
  260. of seconds to sleep) when used along with
  261. max_sleep_interval.
  262. max_sleep_interval:Upper bound of a range for randomized sleep before each
  263. download (maximum possible number of seconds to sleep).
  264. Must only be used along with sleep_interval.
  265. Actual sleep time will be a random float from range
  266. [sleep_interval; max_sleep_interval].
  267. listformats: Print an overview of available video formats and exit.
  268. list_thumbnails: Print a table of all thumbnails and exit.
  269. match_filter: A function that gets called with the info_dict of
  270. every video.
  271. If it returns a message, the video is ignored.
  272. If it returns None, the video is downloaded.
  273. match_filter_func in utils.py is one example for this.
  274. no_color: Do not emit color codes in output.
  275. geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
  276. HTTP header
  277. geo_bypass_country:
  278. Two-letter ISO 3166-2 country code that will be used for
  279. explicit geographic restriction bypassing via faking
  280. X-Forwarded-For HTTP header
  281. geo_bypass_ip_block:
  282. IP range in CIDR notation that will be used similarly to
  283. geo_bypass_country
  284. The following options determine which downloader is picked:
  285. external_downloader: Executable of the external downloader to call.
  286. None or unset for standard (built-in) downloader.
  287. hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv
  288. if True, otherwise use ffmpeg/avconv if False, otherwise
  289. use downloader suggested by extractor if None.
  290. The following parameters are not used by YoutubeDL itself, they are used by
  291. the downloader (see youtube_dl/downloader/common.py):
  292. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  293. noresizebuffer, retries, continuedl, noprogress, consoletitle,
  294. xattr_set_filesize, external_downloader_args, hls_use_mpegts,
  295. http_chunk_size.
  296. The following options are used by the post processors:
  297. prefer_ffmpeg: If False, use avconv instead of ffmpeg if both are available,
  298. otherwise prefer ffmpeg.
  299. ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
  300. to the binary or its containing directory.
  301. postprocessor_args: A list of additional command-line arguments for the
  302. postprocessor.
  303. The following options are used by the Youtube extractor:
  304. youtube_include_dash_manifest: If True (default), DASH manifests and related
  305. data will be downloaded and processed by extractor.
  306. You can reduce network I/O by disabling it if you don't
  307. care about DASH.
  308. """
  309. _NUMERIC_FIELDS = set((
  310. 'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx',
  311. 'timestamp', 'upload_year', 'upload_month', 'upload_day',
  312. 'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
  313. 'average_rating', 'comment_count', 'age_limit',
  314. 'start_time', 'end_time',
  315. 'chapter_number', 'season_number', 'episode_number',
  316. 'track_number', 'disc_number', 'release_year',
  317. 'playlist_index',
  318. ))
  319. params = None
  320. _ies = []
  321. _pps = []
  322. _download_retcode = None
  323. _num_downloads = None
  324. _playlist_level = 0
  325. _playlist_urls = set()
  326. _screen_file = None
  327. def __init__(self, params=None, auto_init=True):
  328. """Create a FileDownloader object with the given options."""
  329. if params is None:
  330. params = {}
  331. self._ies = []
  332. self._ies_instances = {}
  333. self._pps = []
  334. self._progress_hooks = []
  335. self._download_retcode = 0
  336. self._num_downloads = 0
  337. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  338. self._err_file = sys.stderr
  339. self.params = {
  340. # Default parameters
  341. 'nocheckcertificate': False,
  342. }
  343. self.params.update(params)
  344. self.cache = Cache(self)
  345. def check_deprecated(param, option, suggestion):
  346. if self.params.get(param) is not None:
  347. self.report_warning(
  348. '%s is deprecated. Use %s instead.' % (option, suggestion))
  349. return True
  350. return False
  351. if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
  352. if self.params.get('geo_verification_proxy') is None:
  353. self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
  354. check_deprecated('autonumber_size', '--autonumber-size', 'output template with %(autonumber)0Nd, where N in the number of digits')
  355. check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
  356. check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
  357. if params.get('bidi_workaround', False):
  358. try:
  359. import pty
  360. master, slave = pty.openpty()
  361. width = compat_get_terminal_size().columns
  362. if width is None:
  363. width_args = []
  364. else:
  365. width_args = ['-w', str(width)]
  366. sp_kwargs = dict(
  367. stdin=subprocess.PIPE,
  368. stdout=slave,
  369. stderr=self._err_file)
  370. try:
  371. self._output_process = subprocess.Popen(
  372. ['bidiv'] + width_args, **sp_kwargs
  373. )
  374. except OSError:
  375. self._output_process = subprocess.Popen(
  376. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  377. self._output_channel = os.fdopen(master, 'rb')
  378. except OSError as ose:
  379. if ose.errno == errno.ENOENT:
  380. 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.')
  381. else:
  382. raise
  383. if (sys.platform != 'win32'
  384. and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  385. and not params.get('restrictfilenames', False)):
  386. # Unicode filesystem API will throw errors (#1474, #13027)
  387. self.report_warning(
  388. 'Assuming --restrict-filenames since file system encoding '
  389. 'cannot encode all characters. '
  390. 'Set the LC_ALL environment variable to fix this.')
  391. self.params['restrictfilenames'] = True
  392. if isinstance(params.get('outtmpl'), bytes):
  393. self.report_warning(
  394. 'Parameter outtmpl is bytes, but should be a unicode string. '
  395. 'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
  396. self._setup_opener()
  397. if auto_init:
  398. self.print_debug_header()
  399. self.add_default_info_extractors()
  400. for pp_def_raw in self.params.get('postprocessors', []):
  401. pp_class = get_postprocessor(pp_def_raw['key'])
  402. pp_def = dict(pp_def_raw)
  403. del pp_def['key']
  404. pp = pp_class(self, **compat_kwargs(pp_def))
  405. self.add_post_processor(pp)
  406. for ph in self.params.get('progress_hooks', []):
  407. self.add_progress_hook(ph)
  408. register_socks_protocols()
  409. def warn_if_short_id(self, argv):
  410. # short YouTube ID starting with dash?
  411. idxs = [
  412. i for i, a in enumerate(argv)
  413. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  414. if idxs:
  415. correct_argv = (
  416. ['youtube-dl']
  417. + [a for i, a in enumerate(argv) if i not in idxs]
  418. + ['--'] + [argv[i] for i in idxs]
  419. )
  420. self.report_warning(
  421. 'Long argument string detected. '
  422. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  423. args_to_str(correct_argv))
  424. def add_info_extractor(self, ie):
  425. """Add an InfoExtractor object to the end of the list."""
  426. self._ies.append(ie)
  427. if not isinstance(ie, type):
  428. self._ies_instances[ie.ie_key()] = ie
  429. ie.set_downloader(self)
  430. def get_info_extractor(self, ie_key):
  431. """
  432. Get an instance of an IE with name ie_key, it will try to get one from
  433. the _ies list, if there's no instance it will create a new one and add
  434. it to the extractor list.
  435. """
  436. ie = self._ies_instances.get(ie_key)
  437. if ie is None:
  438. ie = get_info_extractor(ie_key)()
  439. self.add_info_extractor(ie)
  440. return ie
  441. def add_default_info_extractors(self):
  442. """
  443. Add the InfoExtractors returned by gen_extractors to the end of the list
  444. """
  445. for ie in gen_extractor_classes():
  446. self.add_info_extractor(ie)
  447. def add_post_processor(self, pp):
  448. """Add a PostProcessor object to the end of the chain."""
  449. self._pps.append(pp)
  450. pp.set_downloader(self)
  451. def add_progress_hook(self, ph):
  452. """Add the progress hook (currently only for the file downloader)"""
  453. self._progress_hooks.append(ph)
  454. def _bidi_workaround(self, message):
  455. if not hasattr(self, '_output_channel'):
  456. return message
  457. assert hasattr(self, '_output_process')
  458. assert isinstance(message, compat_str)
  459. line_count = message.count('\n') + 1
  460. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  461. self._output_process.stdin.flush()
  462. res = ''.join(self._output_channel.readline().decode('utf-8')
  463. for _ in range(line_count))
  464. return res[:-len('\n')]
  465. def to_screen(self, message, skip_eol=False):
  466. """Print message to stdout if not in quiet mode."""
  467. return self.to_stdout(message, skip_eol, check_quiet=True)
  468. def _write_string(self, s, out=None):
  469. write_string(s, out=out, encoding=self.params.get('encoding'))
  470. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  471. """Print message to stdout if not in quiet mode."""
  472. if self.params.get('logger'):
  473. self.params['logger'].debug(message)
  474. elif not check_quiet or not self.params.get('quiet', False):
  475. message = self._bidi_workaround(message)
  476. terminator = ['\n', ''][skip_eol]
  477. output = message + terminator
  478. self._write_string(output, self._screen_file)
  479. def to_stderr(self, message):
  480. """Print message to stderr."""
  481. assert isinstance(message, compat_str)
  482. if self.params.get('logger'):
  483. self.params['logger'].error(message)
  484. else:
  485. message = self._bidi_workaround(message)
  486. output = message + '\n'
  487. self._write_string(output, self._err_file)
  488. def to_console_title(self, message):
  489. if not self.params.get('consoletitle', False):
  490. return
  491. if compat_os_name == 'nt':
  492. if ctypes.windll.kernel32.GetConsoleWindow():
  493. # c_wchar_p() might not be necessary if `message` is
  494. # already of type unicode()
  495. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  496. elif 'TERM' in os.environ:
  497. self._write_string('\033]0;%s\007' % message, self._screen_file)
  498. def save_console_title(self):
  499. if not self.params.get('consoletitle', False):
  500. return
  501. if self.params.get('simulate', False):
  502. return
  503. if compat_os_name != 'nt' and 'TERM' in os.environ:
  504. # Save the title on stack
  505. self._write_string('\033[22;0t', self._screen_file)
  506. def restore_console_title(self):
  507. if not self.params.get('consoletitle', False):
  508. return
  509. if self.params.get('simulate', False):
  510. return
  511. if compat_os_name != 'nt' and 'TERM' in os.environ:
  512. # Restore the title from stack
  513. self._write_string('\033[23;0t', self._screen_file)
  514. def __enter__(self):
  515. self.save_console_title()
  516. return self
  517. def __exit__(self, *args):
  518. self.restore_console_title()
  519. if self.params.get('cookiefile') is not None:
  520. self.cookiejar.save(ignore_discard=True, ignore_expires=True)
  521. def trouble(self, message=None, tb=None):
  522. """Determine action to take when a download problem appears.
  523. Depending on if the downloader has been configured to ignore
  524. download errors or not, this method may throw an exception or
  525. not when errors are found, after printing the message.
  526. tb, if given, is additional traceback information.
  527. """
  528. if message is not None:
  529. self.to_stderr(message)
  530. if self.params.get('verbose'):
  531. if tb is None:
  532. if sys.exc_info()[0]: # if .trouble has been called from an except block
  533. tb = ''
  534. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  535. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  536. tb += encode_compat_str(traceback.format_exc())
  537. else:
  538. tb_data = traceback.format_list(traceback.extract_stack())
  539. tb = ''.join(tb_data)
  540. self.to_stderr(tb)
  541. if not self.params.get('ignoreerrors', False):
  542. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  543. exc_info = sys.exc_info()[1].exc_info
  544. else:
  545. exc_info = sys.exc_info()
  546. raise DownloadError(message, exc_info)
  547. self._download_retcode = 1
  548. def report_warning(self, message):
  549. '''
  550. Print the message to stderr, it will be prefixed with 'WARNING:'
  551. If stderr is a tty file the 'WARNING:' will be colored
  552. '''
  553. if self.params.get('logger') is not None:
  554. self.params['logger'].warning(message)
  555. else:
  556. if self.params.get('no_warnings'):
  557. return
  558. if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
  559. _msg_header = '\033[0;33mWARNING:\033[0m'
  560. else:
  561. _msg_header = 'WARNING:'
  562. warning_message = '%s %s' % (_msg_header, message)
  563. self.to_stderr(warning_message)
  564. def report_error(self, message, tb=None):
  565. '''
  566. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  567. in red if stderr is a tty file.
  568. '''
  569. if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
  570. _msg_header = '\033[0;31mERROR:\033[0m'
  571. else:
  572. _msg_header = 'ERROR:'
  573. error_message = '%s %s' % (_msg_header, message)
  574. self.trouble(error_message, tb)
  575. def report_file_already_downloaded(self, file_name):
  576. """Report file has already been fully downloaded."""
  577. try:
  578. self.to_screen('[download] %s has already been downloaded' % file_name)
  579. except UnicodeEncodeError:
  580. self.to_screen('[download] The file has already been downloaded')
  581. def prepare_filename(self, info_dict):
  582. """Generate the output filename."""
  583. try:
  584. template_dict = dict(info_dict)
  585. template_dict['epoch'] = int(time.time())
  586. autonumber_size = self.params.get('autonumber_size')
  587. if autonumber_size is None:
  588. autonumber_size = 5
  589. template_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads
  590. if template_dict.get('resolution') is None:
  591. if template_dict.get('width') and template_dict.get('height'):
  592. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  593. elif template_dict.get('height'):
  594. template_dict['resolution'] = '%sp' % template_dict['height']
  595. elif template_dict.get('width'):
  596. template_dict['resolution'] = '%dx?' % template_dict['width']
  597. sanitize = lambda k, v: sanitize_filename(
  598. compat_str(v),
  599. restricted=self.params.get('restrictfilenames'),
  600. is_id=(k == 'id' or k.endswith('_id')))
  601. template_dict = dict((k, v if isinstance(v, compat_numeric_types) else sanitize(k, v))
  602. for k, v in template_dict.items()
  603. if v is not None and not isinstance(v, (list, tuple, dict)))
  604. template_dict = collections.defaultdict(lambda: self.params.get('outtmpl_na_placeholder', 'NA'), template_dict)
  605. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  606. # For fields playlist_index and autonumber convert all occurrences
  607. # of %(field)s to %(field)0Nd for backward compatibility
  608. field_size_compat_map = {
  609. 'playlist_index': len(str(template_dict['n_entries'])),
  610. 'autonumber': autonumber_size,
  611. }
  612. FIELD_SIZE_COMPAT_RE = r'(?<!%)%\((?P<field>autonumber|playlist_index)\)s'
  613. mobj = re.search(FIELD_SIZE_COMPAT_RE, outtmpl)
  614. if mobj:
  615. outtmpl = re.sub(
  616. FIELD_SIZE_COMPAT_RE,
  617. r'%%(\1)0%dd' % field_size_compat_map[mobj.group('field')],
  618. outtmpl)
  619. # Missing numeric fields used together with integer presentation types
  620. # in format specification will break the argument substitution since
  621. # string NA placeholder is returned for missing fields. We will patch
  622. # output template for missing fields to meet string presentation type.
  623. for numeric_field in self._NUMERIC_FIELDS:
  624. if numeric_field not in template_dict:
  625. # As of [1] format syntax is:
  626. # %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type
  627. # 1. https://docs.python.org/2/library/stdtypes.html#string-formatting
  628. FORMAT_RE = r'''(?x)
  629. (?<!%)
  630. %
  631. \({0}\) # mapping key
  632. (?:[#0\-+ ]+)? # conversion flags (optional)
  633. (?:\d+)? # minimum field width (optional)
  634. (?:\.\d+)? # precision (optional)
  635. [hlL]? # length modifier (optional)
  636. [diouxXeEfFgGcrs%] # conversion type
  637. '''
  638. outtmpl = re.sub(
  639. FORMAT_RE.format(numeric_field),
  640. r'%({0})s'.format(numeric_field), outtmpl)
  641. # expand_path translates '%%' into '%' and '$$' into '$'
  642. # correspondingly that is not what we want since we need to keep
  643. # '%%' intact for template dict substitution step. Working around
  644. # with boundary-alike separator hack.
  645. sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
  646. outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
  647. # outtmpl should be expand_path'ed before template dict substitution
  648. # because meta fields may contain env variables we don't want to
  649. # be expanded. For example, for outtmpl "%(title)s.%(ext)s" and
  650. # title "Hello $PATH", we don't want `$PATH` to be expanded.
  651. filename = expand_path(outtmpl).replace(sep, '') % template_dict
  652. # Temporary fix for #4787
  653. # 'Treat' all problem characters by passing filename through preferredencoding
  654. # to workaround encoding issues with subprocess on python2 @ Windows
  655. if sys.version_info < (3, 0) and sys.platform == 'win32':
  656. filename = encodeFilename(filename, True).decode(preferredencoding())
  657. return sanitize_path(filename)
  658. except ValueError as err:
  659. self.report_error('Error in output template: ' + error_to_compat_str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  660. return None
  661. def _match_entry(self, info_dict, incomplete):
  662. """ Returns None iff the file should be downloaded """
  663. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  664. if 'title' in info_dict:
  665. # This can happen when we're just evaluating the playlist
  666. title = info_dict['title']
  667. matchtitle = self.params.get('matchtitle', False)
  668. if matchtitle:
  669. if not re.search(matchtitle, title, re.IGNORECASE):
  670. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  671. rejecttitle = self.params.get('rejecttitle', False)
  672. if rejecttitle:
  673. if re.search(rejecttitle, title, re.IGNORECASE):
  674. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  675. date = info_dict.get('upload_date')
  676. if date is not None:
  677. dateRange = self.params.get('daterange', DateRange())
  678. if date not in dateRange:
  679. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  680. view_count = info_dict.get('view_count')
  681. if view_count is not None:
  682. min_views = self.params.get('min_views')
  683. if min_views is not None and view_count < min_views:
  684. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  685. max_views = self.params.get('max_views')
  686. if max_views is not None and view_count > max_views:
  687. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  688. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  689. return 'Skipping "%s" because it is age restricted' % video_title
  690. if self.in_download_archive(info_dict):
  691. return '%s has already been recorded in archive' % video_title
  692. if not incomplete:
  693. match_filter = self.params.get('match_filter')
  694. if match_filter is not None:
  695. ret = match_filter(info_dict)
  696. if ret is not None:
  697. return ret
  698. return None
  699. @staticmethod
  700. def add_extra_info(info_dict, extra_info):
  701. '''Set the keys from extra_info in info dict if they are missing'''
  702. for key, value in extra_info.items():
  703. info_dict.setdefault(key, value)
  704. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  705. process=True, force_generic_extractor=False):
  706. """
  707. Return a list with a dictionary for each video extracted.
  708. Arguments:
  709. url -- URL to extract
  710. Keyword arguments:
  711. download -- whether to download videos during extraction
  712. ie_key -- extractor key hint
  713. extra_info -- dictionary containing the extra values to add to each result
  714. process -- whether to resolve all unresolved references (URLs, playlist items),
  715. must be True for download to work.
  716. force_generic_extractor -- force using the generic extractor
  717. """
  718. if not ie_key and force_generic_extractor:
  719. ie_key = 'Generic'
  720. if ie_key:
  721. ies = [self.get_info_extractor(ie_key)]
  722. else:
  723. ies = self._ies
  724. for ie in ies:
  725. if not ie.suitable(url):
  726. continue
  727. ie = self.get_info_extractor(ie.ie_key())
  728. if not ie.working():
  729. self.report_warning('The program functionality for this site has been marked as broken, '
  730. 'and will probably not work.')
  731. return self.__extract_info(url, ie, download, extra_info, process)
  732. else:
  733. self.report_error('no suitable InfoExtractor for URL %s' % url)
  734. def __handle_extraction_exceptions(func):
  735. def wrapper(self, *args, **kwargs):
  736. try:
  737. return func(self, *args, **kwargs)
  738. except GeoRestrictedError as e:
  739. msg = e.msg
  740. if e.countries:
  741. msg += '\nThis video is available in %s.' % ', '.join(
  742. map(ISO3166Utils.short2full, e.countries))
  743. msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
  744. self.report_error(msg)
  745. except ExtractorError as e: # An error we somewhat expected
  746. self.report_error(compat_str(e), e.format_traceback())
  747. except MaxDownloadsReached:
  748. raise
  749. except Exception as e:
  750. if self.params.get('ignoreerrors', False):
  751. self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
  752. else:
  753. raise
  754. return wrapper
  755. @__handle_extraction_exceptions
  756. def __extract_info(self, url, ie, download, extra_info, process):
  757. ie_result = ie.extract(url)
  758. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  759. return
  760. if isinstance(ie_result, list):
  761. # Backwards compatibility: old IE result format
  762. ie_result = {
  763. '_type': 'compat_list',
  764. 'entries': ie_result,
  765. }
  766. self.add_default_extra_info(ie_result, ie, url)
  767. if process:
  768. return self.process_ie_result(ie_result, download, extra_info)
  769. else:
  770. return ie_result
  771. def add_default_extra_info(self, ie_result, ie, url):
  772. self.add_extra_info(ie_result, {
  773. 'extractor': ie.IE_NAME,
  774. 'webpage_url': url,
  775. 'webpage_url_basename': url_basename(url),
  776. 'extractor_key': ie.ie_key(),
  777. })
  778. def process_ie_result(self, ie_result, download=True, extra_info={}):
  779. """
  780. Take the result of the ie(may be modified) and resolve all unresolved
  781. references (URLs, playlist items).
  782. It will also download the videos if 'download'.
  783. Returns the resolved ie_result.
  784. """
  785. result_type = ie_result.get('_type', 'video')
  786. if result_type in ('url', 'url_transparent'):
  787. ie_result['url'] = sanitize_url(ie_result['url'])
  788. extract_flat = self.params.get('extract_flat', False)
  789. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
  790. or extract_flat is True):
  791. self.__forced_printings(
  792. ie_result, self.prepare_filename(ie_result),
  793. incomplete=True)
  794. return ie_result
  795. if result_type == 'video':
  796. self.add_extra_info(ie_result, extra_info)
  797. return self.process_video_result(ie_result, download=download)
  798. elif result_type == 'url':
  799. # We have to add extra_info to the results because it may be
  800. # contained in a playlist
  801. return self.extract_info(ie_result['url'],
  802. download,
  803. ie_key=ie_result.get('ie_key'),
  804. extra_info=extra_info)
  805. elif result_type == 'url_transparent':
  806. # Use the information from the embedding page
  807. info = self.extract_info(
  808. ie_result['url'], ie_key=ie_result.get('ie_key'),
  809. extra_info=extra_info, download=False, process=False)
  810. # extract_info may return None when ignoreerrors is enabled and
  811. # extraction failed with an error, don't crash and return early
  812. # in this case
  813. if not info:
  814. return info
  815. force_properties = dict(
  816. (k, v) for k, v in ie_result.items() if v is not None)
  817. for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
  818. if f in force_properties:
  819. del force_properties[f]
  820. new_result = info.copy()
  821. new_result.update(force_properties)
  822. # Extracted info may not be a video result (i.e.
  823. # info.get('_type', 'video') != video) but rather an url or
  824. # url_transparent. In such cases outer metadata (from ie_result)
  825. # should be propagated to inner one (info). For this to happen
  826. # _type of info should be overridden with url_transparent. This
  827. # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
  828. if new_result.get('_type') == 'url':
  829. new_result['_type'] = 'url_transparent'
  830. return self.process_ie_result(
  831. new_result, download=download, extra_info=extra_info)
  832. elif result_type in ('playlist', 'multi_video'):
  833. # Protect from infinite recursion due to recursively nested playlists
  834. # (see https://github.com/ytdl-org/youtube-dl/issues/27833)
  835. webpage_url = ie_result['webpage_url']
  836. if webpage_url in self._playlist_urls:
  837. self.to_screen(
  838. '[download] Skipping already downloaded playlist: %s'
  839. % ie_result.get('title') or ie_result.get('id'))
  840. return
  841. self._playlist_level += 1
  842. self._playlist_urls.add(webpage_url)
  843. try:
  844. return self.__process_playlist(ie_result, download)
  845. finally:
  846. self._playlist_level -= 1
  847. if not self._playlist_level:
  848. self._playlist_urls.clear()
  849. elif result_type == 'compat_list':
  850. self.report_warning(
  851. 'Extractor %s returned a compat_list result. '
  852. 'It needs to be updated.' % ie_result.get('extractor'))
  853. def _fixup(r):
  854. self.add_extra_info(
  855. r,
  856. {
  857. 'extractor': ie_result['extractor'],
  858. 'webpage_url': ie_result['webpage_url'],
  859. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  860. 'extractor_key': ie_result['extractor_key'],
  861. }
  862. )
  863. return r
  864. ie_result['entries'] = [
  865. self.process_ie_result(_fixup(r), download, extra_info)
  866. for r in ie_result['entries']
  867. ]
  868. return ie_result
  869. else:
  870. raise Exception('Invalid result type: %s' % result_type)
  871. def __process_playlist(self, ie_result, download):
  872. # We process each entry in the playlist
  873. playlist = ie_result.get('title') or ie_result.get('id')
  874. self.to_screen('[download] Downloading playlist: %s' % playlist)
  875. playlist_results = []
  876. playliststart = self.params.get('playliststart', 1) - 1
  877. playlistend = self.params.get('playlistend')
  878. # For backwards compatibility, interpret -1 as whole list
  879. if playlistend == -1:
  880. playlistend = None
  881. playlistitems_str = self.params.get('playlist_items')
  882. playlistitems = None
  883. if playlistitems_str is not None:
  884. def iter_playlistitems(format):
  885. for string_segment in format.split(','):
  886. if '-' in string_segment:
  887. start, end = string_segment.split('-')
  888. for item in range(int(start), int(end) + 1):
  889. yield int(item)
  890. else:
  891. yield int(string_segment)
  892. playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
  893. ie_entries = ie_result['entries']
  894. def make_playlistitems_entries(list_ie_entries):
  895. num_entries = len(list_ie_entries)
  896. return [
  897. list_ie_entries[i - 1] for i in playlistitems
  898. if -num_entries <= i - 1 < num_entries]
  899. def report_download(num_entries):
  900. self.to_screen(
  901. '[%s] playlist %s: Downloading %d videos' %
  902. (ie_result['extractor'], playlist, num_entries))
  903. if isinstance(ie_entries, list):
  904. n_all_entries = len(ie_entries)
  905. if playlistitems:
  906. entries = make_playlistitems_entries(ie_entries)
  907. else:
  908. entries = ie_entries[playliststart:playlistend]
  909. n_entries = len(entries)
  910. self.to_screen(
  911. '[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
  912. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  913. elif isinstance(ie_entries, PagedList):
  914. if playlistitems:
  915. entries = []
  916. for item in playlistitems:
  917. entries.extend(ie_entries.getslice(
  918. item - 1, item
  919. ))
  920. else:
  921. entries = ie_entries.getslice(
  922. playliststart, playlistend)
  923. n_entries = len(entries)
  924. report_download(n_entries)
  925. else: # iterable
  926. if playlistitems:
  927. entries = make_playlistitems_entries(list(itertools.islice(
  928. ie_entries, 0, max(playlistitems))))
  929. else:
  930. entries = list(itertools.islice(
  931. ie_entries, playliststart, playlistend))
  932. n_entries = len(entries)
  933. report_download(n_entries)
  934. if self.params.get('playlistreverse', False):
  935. entries = entries[::-1]
  936. if self.params.get('playlistrandom', False):
  937. random.shuffle(entries)
  938. x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
  939. for i, entry in enumerate(entries, 1):
  940. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  941. # This __x_forwarded_for_ip thing is a bit ugly but requires
  942. # minimal changes
  943. if x_forwarded_for:
  944. entry['__x_forwarded_for_ip'] = x_forwarded_for
  945. extra = {
  946. 'n_entries': n_entries,
  947. 'playlist': playlist,
  948. 'playlist_id': ie_result.get('id'),
  949. 'playlist_title': ie_result.get('title'),
  950. 'playlist_uploader': ie_result.get('uploader'),
  951. 'playlist_uploader_id': ie_result.get('uploader_id'),
  952. 'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart,
  953. 'extractor': ie_result['extractor'],
  954. 'webpage_url': ie_result['webpage_url'],
  955. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  956. 'extractor_key': ie_result['extractor_key'],
  957. }
  958. reason = self._match_entry(entry, incomplete=True)
  959. if reason is not None:
  960. self.to_screen('[download] ' + reason)
  961. continue
  962. entry_result = self.__process_iterable_entry(entry, download, extra)
  963. # TODO: skip failed (empty) entries?
  964. playlist_results.append(entry_result)
  965. ie_result['entries'] = playlist_results
  966. self.to_screen('[download] Finished downloading playlist: %s' % playlist)
  967. return ie_result
  968. @__handle_extraction_exceptions
  969. def __process_iterable_entry(self, entry, download, extra_info):
  970. return self.process_ie_result(
  971. entry, download=download, extra_info=extra_info)
  972. def _build_format_filter(self, filter_spec):
  973. " Returns a function to filter the formats according to the filter_spec "
  974. OPERATORS = {
  975. '<': operator.lt,
  976. '<=': operator.le,
  977. '>': operator.gt,
  978. '>=': operator.ge,
  979. '=': operator.eq,
  980. '!=': operator.ne,
  981. }
  982. operator_rex = re.compile(r'''(?x)\s*
  983. (?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)
  984. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  985. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  986. $
  987. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  988. m = operator_rex.search(filter_spec)
  989. if m:
  990. try:
  991. comparison_value = int(m.group('value'))
  992. except ValueError:
  993. comparison_value = parse_filesize(m.group('value'))
  994. if comparison_value is None:
  995. comparison_value = parse_filesize(m.group('value') + 'B')
  996. if comparison_value is None:
  997. raise ValueError(
  998. 'Invalid value %r in format specification %r' % (
  999. m.group('value'), filter_spec))
  1000. op = OPERATORS[m.group('op')]
  1001. if not m:
  1002. STR_OPERATORS = {
  1003. '=': operator.eq,
  1004. '^=': lambda attr, value: attr.startswith(value),
  1005. '$=': lambda attr, value: attr.endswith(value),
  1006. '*=': lambda attr, value: value in attr,
  1007. }
  1008. str_operator_rex = re.compile(r'''(?x)
  1009. \s*(?P<key>ext|acodec|vcodec|container|protocol|format_id|language)
  1010. \s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?
  1011. \s*(?P<value>[a-zA-Z0-9._-]+)
  1012. \s*$
  1013. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  1014. m = str_operator_rex.search(filter_spec)
  1015. if m:
  1016. comparison_value = m.group('value')
  1017. str_op = STR_OPERATORS[m.group('op')]
  1018. if m.group('negation'):
  1019. op = lambda attr, value: not str_op(attr, value)
  1020. else:
  1021. op = str_op
  1022. if not m:
  1023. raise ValueError('Invalid filter specification %r' % filter_spec)
  1024. def _filter(f):
  1025. actual_value = f.get(m.group('key'))
  1026. if actual_value is None:
  1027. return m.group('none_inclusive')
  1028. return op(actual_value, comparison_value)
  1029. return _filter
  1030. def _default_format_spec(self, info_dict, download=True):
  1031. def can_merge():
  1032. merger = FFmpegMergerPP(self)
  1033. return merger.available and merger.can_merge()
  1034. def prefer_best():
  1035. if self.params.get('simulate', False):
  1036. return False
  1037. if not download:
  1038. return False
  1039. if self.params.get('outtmpl', DEFAULT_OUTTMPL) == '-':
  1040. return True
  1041. if info_dict.get('is_live'):
  1042. return True
  1043. if not can_merge():
  1044. return True
  1045. return False
  1046. req_format_list = ['bestvideo+bestaudio', 'best']
  1047. if prefer_best():
  1048. req_format_list.reverse()
  1049. return '/'.join(req_format_list)
  1050. def build_format_selector(self, format_spec):
  1051. def syntax_error(note, start):
  1052. message = (
  1053. 'Invalid format specification: '
  1054. '{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
  1055. return SyntaxError(message)
  1056. PICKFIRST = 'PICKFIRST'
  1057. MERGE = 'MERGE'
  1058. SINGLE = 'SINGLE'
  1059. GROUP = 'GROUP'
  1060. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  1061. def _parse_filter(tokens):
  1062. filter_parts = []
  1063. for type, string, start, _, _ in tokens:
  1064. if type == tokenize.OP and string == ']':
  1065. return ''.join(filter_parts)
  1066. else:
  1067. filter_parts.append(string)
  1068. def _remove_unused_ops(tokens):
  1069. # Remove operators that we don't use and join them with the surrounding strings
  1070. # for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  1071. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  1072. last_string, last_start, last_end, last_line = None, None, None, None
  1073. for type, string, start, end, line in tokens:
  1074. if type == tokenize.OP and string == '[':
  1075. if last_string:
  1076. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1077. last_string = None
  1078. yield type, string, start, end, line
  1079. # everything inside brackets will be handled by _parse_filter
  1080. for type, string, start, end, line in tokens:
  1081. yield type, string, start, end, line
  1082. if type == tokenize.OP and string == ']':
  1083. break
  1084. elif type == tokenize.OP and string in ALLOWED_OPS:
  1085. if last_string:
  1086. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1087. last_string = None
  1088. yield type, string, start, end, line
  1089. elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  1090. if not last_string:
  1091. last_string = string
  1092. last_start = start
  1093. last_end = end
  1094. else:
  1095. last_string += string
  1096. if last_string:
  1097. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1098. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  1099. selectors = []
  1100. current_selector = None
  1101. for type, string, start, _, _ in tokens:
  1102. # ENCODING is only defined in python 3.x
  1103. if type == getattr(tokenize, 'ENCODING', None):
  1104. continue
  1105. elif type in [tokenize.NAME, tokenize.NUMBER]:
  1106. current_selector = FormatSelector(SINGLE, string, [])
  1107. elif type == tokenize.OP:
  1108. if string == ')':
  1109. if not inside_group:
  1110. # ')' will be handled by the parentheses group
  1111. tokens.restore_last_token()
  1112. break
  1113. elif inside_merge and string in ['/', ',']:
  1114. tokens.restore_last_token()
  1115. break
  1116. elif inside_choice and string == ',':
  1117. tokens.restore_last_token()
  1118. break
  1119. elif string == ',':
  1120. if not current_selector:
  1121. raise syntax_error('"," must follow a format selector', start)
  1122. selectors.append(current_selector)
  1123. current_selector = None
  1124. elif string == '/':
  1125. if not current_selector:
  1126. raise syntax_error('"/" must follow a format selector', start)
  1127. first_choice = current_selector
  1128. second_choice = _parse_format_selection(tokens, inside_choice=True)
  1129. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  1130. elif string == '[':
  1131. if not current_selector:
  1132. current_selector = FormatSelector(SINGLE, 'best', [])
  1133. format_filter = _parse_filter(tokens)
  1134. current_selector.filters.append(format_filter)
  1135. elif string == '(':
  1136. if current_selector:
  1137. raise syntax_error('Unexpected "("', start)
  1138. group = _parse_format_selection(tokens, inside_group=True)
  1139. current_selector = FormatSelector(GROUP, group, [])
  1140. elif string == '+':
  1141. if inside_merge:
  1142. raise syntax_error('Unexpected "+"', start)
  1143. video_selector = current_selector
  1144. audio_selector = _parse_format_selection(tokens, inside_merge=True)
  1145. if not video_selector or not audio_selector:
  1146. raise syntax_error('"+" must be between two format selectors', start)
  1147. current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
  1148. else:
  1149. raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
  1150. elif type == tokenize.ENDMARKER:
  1151. break
  1152. if current_selector:
  1153. selectors.append(current_selector)
  1154. return selectors
  1155. def _build_selector_function(selector):
  1156. if isinstance(selector, list):
  1157. fs = [_build_selector_function(s) for s in selector]
  1158. def selector_function(ctx):
  1159. for f in fs:
  1160. for format in f(ctx):
  1161. yield format
  1162. return selector_function
  1163. elif selector.type == GROUP:
  1164. selector_function = _build_selector_function(selector.selector)
  1165. elif selector.type == PICKFIRST:
  1166. fs = [_build_selector_function(s) for s in selector.selector]
  1167. def selector_function(ctx):
  1168. for f in fs:
  1169. picked_formats = list(f(ctx))
  1170. if picked_formats:
  1171. return picked_formats
  1172. return []
  1173. elif selector.type == SINGLE:
  1174. format_spec = selector.selector
  1175. def selector_function(ctx):
  1176. def best_worst(fmts, fmt_spec='best'):
  1177. format_idx = 0 if fmt_spec == 'worst' else -1
  1178. audiovideo_formats = [
  1179. f for f in fmts
  1180. if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
  1181. if audiovideo_formats:
  1182. return audiovideo_formats[format_idx]
  1183. # for extractors with incomplete formats (audio only (soundcloud)
  1184. # or video only (imgur)) we will fallback to best/worst
  1185. # {video,audio}-only format
  1186. elif ctx['incomplete_formats']:
  1187. return list(fmts)[format_idx]
  1188. formats = list(ctx['formats'])
  1189. if not formats:
  1190. return
  1191. if format_spec == 'all':
  1192. pass
  1193. elif format_spec in ('best', 'worst', None):
  1194. formats = best_worst(formats, format_spec)
  1195. elif format_spec in ('bestaudio', 'worstaudio'):
  1196. audio_formats = [
  1197. f for f in formats
  1198. if f.get('vcodec') == 'none']
  1199. formats = audio_formats[:1] if format_spec == 'worstaudio' else audio_formats[-1:]
  1200. elif format_spec in ('bestvideo', 'worstvideo'):
  1201. video_formats = [
  1202. f for f in formats
  1203. if f.get('acodec') == 'none']
  1204. formats = video_formats[:1] if format_spec == 'worstvideo' else video_formats[-1:]
  1205. else:
  1206. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  1207. if format_spec in extensions:
  1208. filter_f = lambda f: f['ext'] == format_spec
  1209. else:
  1210. filter_f = lambda f: f['format_id'] == format_spec
  1211. formats = best_worst(filter(filter_f, formats))
  1212. for f in variadic(formats or []):
  1213. yield f
  1214. elif selector.type == MERGE:
  1215. def _merge(formats_info):
  1216. format_1, format_2 = [f['format_id'] for f in formats_info]
  1217. # The first format must contain the video and the
  1218. # second the audio
  1219. if formats_info[0].get('vcodec') == 'none':
  1220. self.report_error('The first format must '
  1221. 'contain the video, try using '
  1222. '"-f %s+%s"' % (format_2, format_1))
  1223. return
  1224. # Formats must be opposite (video+audio)
  1225. if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
  1226. self.report_error(
  1227. 'Both formats %s and %s are video-only, you must specify "-f video+audio"'
  1228. % (format_1, format_2))
  1229. return
  1230. output_ext = (
  1231. formats_info[0]['ext']
  1232. if self.params.get('merge_output_format') is None
  1233. else self.params['merge_output_format'])
  1234. return {
  1235. 'requested_formats': formats_info,
  1236. 'format': '%s+%s' % (formats_info[0].get('format'),
  1237. formats_info[1].get('format')),
  1238. 'format_id': '%s+%s' % (formats_info[0].get('format_id'),
  1239. formats_info[1].get('format_id')),
  1240. 'width': formats_info[0].get('width'),
  1241. 'height': formats_info[0].get('height'),
  1242. 'resolution': formats_info[0].get('resolution'),
  1243. 'fps': formats_info[0].get('fps'),
  1244. 'vcodec': formats_info[0].get('vcodec'),
  1245. 'vbr': formats_info[0].get('vbr'),
  1246. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  1247. 'acodec': formats_info[1].get('acodec'),
  1248. 'abr': formats_info[1].get('abr'),
  1249. 'ext': output_ext,
  1250. }
  1251. video_selector, audio_selector = map(_build_selector_function, selector.selector)
  1252. def selector_function(ctx):
  1253. for pair in itertools.product(
  1254. video_selector(copy.deepcopy(ctx)), audio_selector(copy.deepcopy(ctx))):
  1255. yield _merge(pair)
  1256. filters = [self._build_format_filter(f) for f in selector.filters]
  1257. def final_selector(ctx):
  1258. ctx_copy = copy.deepcopy(ctx)
  1259. for _filter in filters:
  1260. ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
  1261. return selector_function(ctx_copy)
  1262. return final_selector
  1263. stream = io.BytesIO(format_spec.encode('utf-8'))
  1264. try:
  1265. tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
  1266. except tokenize.TokenError:
  1267. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  1268. class TokenIterator(object):
  1269. def __init__(self, tokens):
  1270. self.tokens = tokens
  1271. self.counter = 0
  1272. def __iter__(self):
  1273. return self
  1274. def __next__(self):
  1275. if self.counter >= len(self.tokens):
  1276. raise StopIteration()
  1277. value = self.tokens[self.counter]
  1278. self.counter += 1
  1279. return value
  1280. next = __next__
  1281. def restore_last_token(self):
  1282. self.counter -= 1
  1283. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  1284. return _build_selector_function(parsed_selector)
  1285. def _calc_headers(self, info_dict):
  1286. res = std_headers.copy()
  1287. add_headers = info_dict.get('http_headers')
  1288. if add_headers:
  1289. res.update(add_headers)
  1290. cookies = self._calc_cookies(info_dict)
  1291. if cookies:
  1292. res['Cookie'] = cookies
  1293. if 'X-Forwarded-For' not in res:
  1294. x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
  1295. if x_forwarded_for_ip:
  1296. res['X-Forwarded-For'] = x_forwarded_for_ip
  1297. return res
  1298. def _calc_cookies(self, info_dict):
  1299. pr = sanitized_Request(info_dict['url'])
  1300. self.cookiejar.add_cookie_header(pr)
  1301. return pr.get_header('Cookie')
  1302. def process_video_result(self, info_dict, download=True):
  1303. assert info_dict.get('_type', 'video') == 'video'
  1304. if 'id' not in info_dict:
  1305. raise ExtractorError('Missing "id" field in extractor result')
  1306. if 'title' not in info_dict:
  1307. raise ExtractorError('Missing "title" field in extractor result')
  1308. def report_force_conversion(field, field_not, conversion):
  1309. self.report_warning(
  1310. '"%s" field is not %s - forcing %s conversion, there is an error in extractor'
  1311. % (field, field_not, conversion))
  1312. def sanitize_string_field(info, string_field):
  1313. field = info.get(string_field)
  1314. if field is None or isinstance(field, compat_str):
  1315. return
  1316. report_force_conversion(string_field, 'a string', 'string')
  1317. info[string_field] = compat_str(field)
  1318. def sanitize_numeric_fields(info):
  1319. for numeric_field in self._NUMERIC_FIELDS:
  1320. field = info.get(numeric_field)
  1321. if field is None or isinstance(field, compat_numeric_types):
  1322. continue
  1323. report_force_conversion(numeric_field, 'numeric', 'int')
  1324. info[numeric_field] = int_or_none(field)
  1325. sanitize_string_field(info_dict, 'id')
  1326. sanitize_numeric_fields(info_dict)
  1327. if 'playlist' not in info_dict:
  1328. # It isn't part of a playlist
  1329. info_dict['playlist'] = None
  1330. info_dict['playlist_index'] = None
  1331. thumbnails = info_dict.get('thumbnails')
  1332. if thumbnails is None:
  1333. thumbnail = info_dict.get('thumbnail')
  1334. if thumbnail:
  1335. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  1336. if thumbnails:
  1337. thumbnails.sort(key=lambda t: (
  1338. t.get('preference') if t.get('preference') is not None else -1,
  1339. t.get('width') if t.get('width') is not None else -1,
  1340. t.get('height') if t.get('height') is not None else -1,
  1341. t.get('id') if t.get('id') is not None else '', t.get('url')))
  1342. for i, t in enumerate(thumbnails):
  1343. t['url'] = sanitize_url(t['url'])
  1344. if t.get('width') and t.get('height'):
  1345. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  1346. if t.get('id') is None:
  1347. t['id'] = '%d' % i
  1348. if self.params.get('list_thumbnails'):
  1349. self.list_thumbnails(info_dict)
  1350. return
  1351. thumbnail = info_dict.get('thumbnail')
  1352. if thumbnail:
  1353. info_dict['thumbnail'] = sanitize_url(thumbnail)
  1354. elif thumbnails:
  1355. info_dict['thumbnail'] = thumbnails[-1]['url']
  1356. if 'display_id' not in info_dict and 'id' in info_dict:
  1357. info_dict['display_id'] = info_dict['id']
  1358. for ts_key, date_key in (
  1359. ('timestamp', 'upload_date'),
  1360. ('release_timestamp', 'release_date'),
  1361. ):
  1362. if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
  1363. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  1364. # see http://bugs.python.org/issue1646728)
  1365. try:
  1366. upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
  1367. info_dict[date_key] = compat_str(upload_date.strftime('%Y%m%d'))
  1368. except (ValueError, OverflowError, OSError):
  1369. pass
  1370. # Auto generate title fields corresponding to the *_number fields when missing
  1371. # in order to always have clean titles. This is very common for TV series.
  1372. for field in ('chapter', 'season', 'episode'):
  1373. if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
  1374. info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
  1375. for cc_kind in ('subtitles', 'automatic_captions'):
  1376. cc = info_dict.get(cc_kind)
  1377. if cc:
  1378. for _, subtitle in cc.items():
  1379. for subtitle_format in subtitle:
  1380. if subtitle_format.get('url'):
  1381. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  1382. if subtitle_format.get('ext') is None:
  1383. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  1384. automatic_captions = info_dict.get('automatic_captions')
  1385. subtitles = info_dict.get('subtitles')
  1386. if self.params.get('listsubtitles', False):
  1387. if 'automatic_captions' in info_dict:
  1388. self.list_subtitles(
  1389. info_dict['id'], automatic_captions, 'automatic captions')
  1390. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  1391. return
  1392. info_dict['requested_subtitles'] = self.process_subtitles(
  1393. info_dict['id'], subtitles, automatic_captions)
  1394. # We now pick which formats have to be downloaded
  1395. if info_dict.get('formats') is None:
  1396. # There's only one format available
  1397. formats = [info_dict]
  1398. else:
  1399. formats = info_dict['formats']
  1400. def is_wellformed(f):
  1401. url = f.get('url')
  1402. if not url:
  1403. self.report_warning(
  1404. '"url" field is missing or empty - skipping format, '
  1405. 'there is an error in extractor')
  1406. return False
  1407. if isinstance(url, bytes):
  1408. sanitize_string_field(f, 'url')
  1409. return True
  1410. # Filter out malformed formats for better extraction robustness
  1411. formats = list(filter(is_wellformed, formats or []))
  1412. if not formats:
  1413. raise ExtractorError('No video formats found!')
  1414. formats_dict = {}
  1415. # We check that all the formats have the format and format_id fields
  1416. for i, format in enumerate(formats):
  1417. sanitize_string_field(format, 'format_id')
  1418. sanitize_numeric_fields(format)
  1419. format['url'] = sanitize_url(format['url'])
  1420. if not format.get('format_id'):
  1421. format['format_id'] = compat_str(i)
  1422. else:
  1423. # Sanitize format_id from characters used in format selector expression
  1424. format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
  1425. format_id = format['format_id']
  1426. if format_id not in formats_dict:
  1427. formats_dict[format_id] = []
  1428. formats_dict[format_id].append(format)
  1429. # Make sure all formats have unique format_id
  1430. for format_id, ambiguous_formats in formats_dict.items():
  1431. if len(ambiguous_formats) > 1:
  1432. for i, format in enumerate(ambiguous_formats):
  1433. format['format_id'] = '%s-%d' % (format_id, i)
  1434. for i, format in enumerate(formats):
  1435. if format.get('format') is None:
  1436. format['format'] = '{id} - {res}{note}'.format(
  1437. id=format['format_id'],
  1438. res=self.format_resolution(format),
  1439. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  1440. )
  1441. # Automatically determine file extension if missing
  1442. if format.get('ext') is None:
  1443. format['ext'] = determine_ext(format['url']).lower()
  1444. # Automatically determine protocol if missing (useful for format
  1445. # selection purposes)
  1446. if format.get('protocol') is None:
  1447. format['protocol'] = determine_protocol(format)
  1448. # Add HTTP headers, so that external programs can use them from the
  1449. # json output
  1450. full_format_info = info_dict.copy()
  1451. full_format_info.update(format)
  1452. format['http_headers'] = self._calc_headers(full_format_info)
  1453. # Remove private housekeeping stuff
  1454. if '__x_forwarded_for_ip' in info_dict:
  1455. del info_dict['__x_forwarded_for_ip']
  1456. # TODO Central sorting goes here
  1457. if formats[0] is not info_dict:
  1458. # only set the 'formats' fields if the original info_dict list them
  1459. # otherwise we end up with a circular reference, the first (and unique)
  1460. # element in the 'formats' field in info_dict is info_dict itself,
  1461. # which can't be exported to json
  1462. info_dict['formats'] = formats
  1463. if self.params.get('listformats'):
  1464. self.list_formats(info_dict)
  1465. return
  1466. req_format = self.params.get('format')
  1467. if req_format is None:
  1468. req_format = self._default_format_spec(info_dict, download=download)
  1469. if self.params.get('verbose'):
  1470. self._write_string('[debug] Default format spec: %s\n' % req_format)
  1471. format_selector = self.build_format_selector(req_format)
  1472. # While in format selection we may need to have an access to the original
  1473. # format set in order to calculate some metrics or do some processing.
  1474. # For now we need to be able to guess whether original formats provided
  1475. # by extractor are incomplete or not (i.e. whether extractor provides only
  1476. # video-only or audio-only formats) for proper formats selection for
  1477. # extractors with such incomplete formats (see
  1478. # https://github.com/ytdl-org/youtube-dl/pull/5556).
  1479. # Since formats may be filtered during format selection and may not match
  1480. # the original formats the results may be incorrect. Thus original formats
  1481. # or pre-calculated metrics should be passed to format selection routines
  1482. # as well.
  1483. # We will pass a context object containing all necessary additional data
  1484. # instead of just formats.
  1485. # This fixes incorrect format selection issue (see
  1486. # https://github.com/ytdl-org/youtube-dl/issues/10083).
  1487. incomplete_formats = (
  1488. # All formats are video-only or
  1489. all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
  1490. # all formats are audio-only
  1491. or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
  1492. ctx = {
  1493. 'formats': formats,
  1494. 'incomplete_formats': incomplete_formats,
  1495. }
  1496. formats_to_download = list(format_selector(ctx))
  1497. if not formats_to_download:
  1498. raise ExtractorError('requested format not available',
  1499. expected=True)
  1500. if download:
  1501. if len(formats_to_download) > 1:
  1502. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1503. for format in formats_to_download:
  1504. new_info = dict(info_dict)
  1505. new_info.update(format)
  1506. self.process_info(new_info)
  1507. # We update the info dict with the best quality format (backwards compatibility)
  1508. info_dict.update(formats_to_download[-1])
  1509. return info_dict
  1510. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  1511. """Select the requested subtitles and their format"""
  1512. available_subs = {}
  1513. if normal_subtitles and self.params.get('writesubtitles'):
  1514. available_subs.update(normal_subtitles)
  1515. if automatic_captions and self.params.get('writeautomaticsub'):
  1516. for lang, cap_info in automatic_captions.items():
  1517. if lang not in available_subs:
  1518. available_subs[lang] = cap_info
  1519. if (not self.params.get('writesubtitles') and not
  1520. self.params.get('writeautomaticsub') or not
  1521. available_subs):
  1522. return None
  1523. if self.params.get('allsubtitles', False):
  1524. requested_langs = available_subs.keys()
  1525. else:
  1526. if self.params.get('subtitleslangs', False):
  1527. requested_langs = self.params.get('subtitleslangs')
  1528. elif 'en' in available_subs:
  1529. requested_langs = ['en']
  1530. else:
  1531. requested_langs = [list(available_subs.keys())[0]]
  1532. formats_query = self.params.get('subtitlesformat', 'best')
  1533. formats_preference = formats_query.split('/') if formats_query else []
  1534. subs = {}
  1535. for lang in requested_langs:
  1536. formats = available_subs.get(lang)
  1537. if formats is None:
  1538. self.report_warning('%s subtitles not available for %s' % (lang, video_id))
  1539. continue
  1540. for ext in formats_preference:
  1541. if ext == 'best':
  1542. f = formats[-1]
  1543. break
  1544. matches = list(filter(lambda f: f['ext'] == ext, formats))
  1545. if matches:
  1546. f = matches[-1]
  1547. break
  1548. else:
  1549. f = formats[-1]
  1550. self.report_warning(
  1551. 'No subtitle format found matching "%s" for language %s, '
  1552. 'using %s' % (formats_query, lang, f['ext']))
  1553. subs[lang] = f
  1554. return subs
  1555. def __forced_printings(self, info_dict, filename, incomplete):
  1556. def print_mandatory(field):
  1557. if (self.params.get('force%s' % field, False)
  1558. and (not incomplete or info_dict.get(field) is not None)):
  1559. self.to_stdout(info_dict[field])
  1560. def print_optional(field):
  1561. if (self.params.get('force%s' % field, False)
  1562. and info_dict.get(field) is not None):
  1563. self.to_stdout(info_dict[field])
  1564. print_mandatory('title')
  1565. print_mandatory('id')
  1566. if self.params.get('forceurl', False) and not incomplete:
  1567. if info_dict.get('requested_formats') is not None:
  1568. for f in info_dict['requested_formats']:
  1569. self.to_stdout(f['url'] + f.get('play_path', ''))
  1570. else:
  1571. # For RTMP URLs, also include the playpath
  1572. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1573. print_optional('thumbnail')
  1574. print_optional('description')
  1575. if self.params.get('forcefilename', False) and filename is not None:
  1576. self.to_stdout(filename)
  1577. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1578. self.to_stdout(formatSeconds(info_dict['duration']))
  1579. print_mandatory('format')
  1580. if self.params.get('forcejson', False):
  1581. self.to_stdout(json.dumps(info_dict))
  1582. def process_info(self, info_dict):
  1583. """Process a single resolved IE result."""
  1584. assert info_dict.get('_type', 'video') == 'video'
  1585. max_downloads = int_or_none(self.params.get('max_downloads')) or float('inf')
  1586. if self._num_downloads >= max_downloads:
  1587. raise MaxDownloadsReached()
  1588. # TODO: backward compatibility, to be removed
  1589. info_dict['fulltitle'] = info_dict['title']
  1590. if 'format' not in info_dict:
  1591. info_dict['format'] = info_dict['ext']
  1592. reason = self._match_entry(info_dict, incomplete=False)
  1593. if reason is not None:
  1594. self.to_screen('[download] ' + reason)
  1595. return
  1596. self._num_downloads += 1
  1597. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1598. # Forced printings
  1599. self.__forced_printings(info_dict, filename, incomplete=False)
  1600. # Do nothing else if in simulate mode
  1601. if self.params.get('simulate', False):
  1602. return
  1603. if filename is None:
  1604. return
  1605. def ensure_dir_exists(path):
  1606. try:
  1607. dn = os.path.dirname(path)
  1608. if dn and not os.path.exists(dn):
  1609. os.makedirs(dn)
  1610. return True
  1611. except (OSError, IOError) as err:
  1612. if isinstance(err, OSError) and err.errno == errno.EEXIST:
  1613. return True
  1614. self.report_error('unable to create directory ' + error_to_compat_str(err))
  1615. return False
  1616. if not ensure_dir_exists(sanitize_path(encodeFilename(filename))):
  1617. return
  1618. if self.params.get('writedescription', False):
  1619. descfn = replace_extension(filename, 'description', info_dict.get('ext'))
  1620. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1621. self.to_screen('[info] Video description is already present')
  1622. elif info_dict.get('description') is None:
  1623. self.report_warning('There\'s no description to write.')
  1624. else:
  1625. try:
  1626. self.to_screen('[info] Writing video description to: ' + descfn)
  1627. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1628. descfile.write(info_dict['description'])
  1629. except (OSError, IOError):
  1630. self.report_error('Cannot write description file ' + descfn)
  1631. return
  1632. if self.params.get('writeannotations', False):
  1633. annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
  1634. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1635. self.to_screen('[info] Video annotations are already present')
  1636. elif not info_dict.get('annotations'):
  1637. self.report_warning('There are no annotations to write.')
  1638. else:
  1639. try:
  1640. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1641. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1642. annofile.write(info_dict['annotations'])
  1643. except (KeyError, TypeError):
  1644. self.report_warning('There are no annotations to write.')
  1645. except (OSError, IOError):
  1646. self.report_error('Cannot write annotations file: ' + annofn)
  1647. return
  1648. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1649. self.params.get('writeautomaticsub')])
  1650. if subtitles_are_requested and info_dict.get('requested_subtitles'):
  1651. # subtitles download errors are already managed as troubles in relevant IE
  1652. # that way it will silently go on when used with unsupporting IE
  1653. subtitles = info_dict['requested_subtitles']
  1654. ie = self.get_info_extractor(info_dict['extractor_key'])
  1655. for sub_lang, sub_info in subtitles.items():
  1656. sub_format = sub_info['ext']
  1657. sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
  1658. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1659. self.to_screen('[info] Video subtitle %s.%s is already present' % (sub_lang, sub_format))
  1660. else:
  1661. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1662. if sub_info.get('data') is not None:
  1663. try:
  1664. # Use newline='' to prevent conversion of newline characters
  1665. # See https://github.com/ytdl-org/youtube-dl/issues/10268
  1666. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
  1667. subfile.write(sub_info['data'])
  1668. except (OSError, IOError):
  1669. self.report_error('Cannot write subtitles file ' + sub_filename)
  1670. return
  1671. else:
  1672. try:
  1673. sub_data = ie._request_webpage(
  1674. sub_info['url'], info_dict['id'], note=False).read()
  1675. with io.open(encodeFilename(sub_filename), 'wb') as subfile:
  1676. subfile.write(sub_data)
  1677. except (ExtractorError, IOError, OSError, ValueError) as err:
  1678. self.report_warning('Unable to download subtitle for "%s": %s' %
  1679. (sub_lang, error_to_compat_str(err)))
  1680. continue
  1681. if self.params.get('writeinfojson', False):
  1682. infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
  1683. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1684. self.to_screen('[info] Video description metadata is already present')
  1685. else:
  1686. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1687. try:
  1688. write_json_file(self.filter_requested_info(info_dict), infofn)
  1689. except (OSError, IOError):
  1690. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1691. return
  1692. self._write_thumbnails(info_dict, filename)
  1693. if not self.params.get('skip_download', False):
  1694. try:
  1695. def checked_get_suitable_downloader(info_dict, params):
  1696. ed_args = params.get('external_downloader_args')
  1697. dler = get_suitable_downloader(info_dict, params)
  1698. if ed_args and not params.get('external_downloader_args'):
  1699. # external_downloader_args was cleared because external_downloader was rejected
  1700. self.report_warning('Requested external downloader cannot be used: '
  1701. 'ignoring --external-downloader-args.')
  1702. return dler
  1703. def dl(name, info):
  1704. fd = checked_get_suitable_downloader(info, self.params)(self, self.params)
  1705. for ph in self._progress_hooks:
  1706. fd.add_progress_hook(ph)
  1707. if self.params.get('verbose'):
  1708. self.to_screen('[debug] Invoking downloader on %r' % info.get('url'))
  1709. return fd.download(name, info)
  1710. if info_dict.get('requested_formats') is not None:
  1711. downloaded = []
  1712. success = True
  1713. merger = FFmpegMergerPP(self)
  1714. if not merger.available:
  1715. postprocessors = []
  1716. self.report_warning('You have requested multiple '
  1717. 'formats but ffmpeg or avconv are not installed.'
  1718. ' The formats won\'t be merged.')
  1719. else:
  1720. postprocessors = [merger]
  1721. def compatible_formats(formats):
  1722. video, audio = formats
  1723. # Check extension
  1724. video_ext, audio_ext = video.get('ext'), audio.get('ext')
  1725. if video_ext and audio_ext:
  1726. COMPATIBLE_EXTS = (
  1727. ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma'),
  1728. ('webm')
  1729. )
  1730. for exts in COMPATIBLE_EXTS:
  1731. if video_ext in exts and audio_ext in exts:
  1732. return True
  1733. # TODO: Check acodec/vcodec
  1734. return False
  1735. filename_real_ext = os.path.splitext(filename)[1][1:]
  1736. filename_wo_ext = (
  1737. os.path.splitext(filename)[0]
  1738. if filename_real_ext == info_dict['ext']
  1739. else filename)
  1740. requested_formats = info_dict['requested_formats']
  1741. if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
  1742. info_dict['ext'] = 'mkv'
  1743. self.report_warning(
  1744. 'Requested formats are incompatible for merge and will be merged into mkv.')
  1745. # Ensure filename always has a correct extension for successful merge
  1746. filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
  1747. if os.path.exists(encodeFilename(filename)):
  1748. self.to_screen(
  1749. '[download] %s has already been downloaded and '
  1750. 'merged' % filename)
  1751. else:
  1752. for f in requested_formats:
  1753. new_info = dict(info_dict)
  1754. new_info.update(f)
  1755. fname = prepend_extension(
  1756. self.prepare_filename(new_info),
  1757. 'f%s' % f['format_id'], new_info['ext'])
  1758. if not ensure_dir_exists(fname):
  1759. return
  1760. downloaded.append(fname)
  1761. partial_success = dl(fname, new_info)
  1762. success = success and partial_success
  1763. info_dict['__postprocessors'] = postprocessors
  1764. info_dict['__files_to_merge'] = downloaded
  1765. else:
  1766. # Just a single file
  1767. success = dl(filename, info_dict)
  1768. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1769. self.report_error('unable to download video data: %s' % error_to_compat_str(err))
  1770. return
  1771. except (OSError, IOError) as err:
  1772. raise UnavailableVideoError(err)
  1773. except (ContentTooShortError, ) as err:
  1774. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1775. return
  1776. if success and filename != '-':
  1777. # Fixup content
  1778. fixup_policy = self.params.get('fixup')
  1779. if fixup_policy is None:
  1780. fixup_policy = 'detect_or_warn'
  1781. INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
  1782. stretched_ratio = info_dict.get('stretched_ratio')
  1783. if stretched_ratio is not None and stretched_ratio != 1:
  1784. if fixup_policy == 'warn':
  1785. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1786. info_dict['id'], stretched_ratio))
  1787. elif fixup_policy == 'detect_or_warn':
  1788. stretched_pp = FFmpegFixupStretchedPP(self)
  1789. if stretched_pp.available:
  1790. info_dict.setdefault('__postprocessors', [])
  1791. info_dict['__postprocessors'].append(stretched_pp)
  1792. else:
  1793. self.report_warning(
  1794. '%s: Non-uniform pixel ratio (%s). %s'
  1795. % (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
  1796. else:
  1797. assert fixup_policy in ('ignore', 'never')
  1798. if (info_dict.get('requested_formats') is None
  1799. and info_dict.get('container') == 'm4a_dash'):
  1800. if fixup_policy == 'warn':
  1801. self.report_warning(
  1802. '%s: writing DASH m4a. '
  1803. 'Only some players support this container.'
  1804. % info_dict['id'])
  1805. elif fixup_policy == 'detect_or_warn':
  1806. fixup_pp = FFmpegFixupM4aPP(self)
  1807. if fixup_pp.available:
  1808. info_dict.setdefault('__postprocessors', [])
  1809. info_dict['__postprocessors'].append(fixup_pp)
  1810. else:
  1811. self.report_warning(
  1812. '%s: writing DASH m4a. '
  1813. 'Only some players support this container. %s'
  1814. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1815. else:
  1816. assert fixup_policy in ('ignore', 'never')
  1817. if (info_dict.get('protocol') == 'm3u8_native'
  1818. or info_dict.get('protocol') == 'm3u8'
  1819. and self.params.get('hls_prefer_native')):
  1820. if fixup_policy == 'warn':
  1821. self.report_warning('%s: malformed AAC bitstream detected.' % (
  1822. info_dict['id']))
  1823. elif fixup_policy == 'detect_or_warn':
  1824. fixup_pp = FFmpegFixupM3u8PP(self)
  1825. if fixup_pp.available:
  1826. info_dict.setdefault('__postprocessors', [])
  1827. info_dict['__postprocessors'].append(fixup_pp)
  1828. else:
  1829. self.report_warning(
  1830. '%s: malformed AAC bitstream detected. %s'
  1831. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1832. else:
  1833. assert fixup_policy in ('ignore', 'never')
  1834. try:
  1835. self.post_process(filename, info_dict)
  1836. except (PostProcessingError) as err:
  1837. self.report_error('postprocessing: %s' % error_to_compat_str(err))
  1838. return
  1839. self.record_download_archive(info_dict)
  1840. # avoid possible nugatory search for further items (PR #26638)
  1841. if self._num_downloads >= max_downloads:
  1842. raise MaxDownloadsReached()
  1843. def download(self, url_list):
  1844. """Download a given list of URLs."""
  1845. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1846. if (len(url_list) > 1
  1847. and outtmpl != '-'
  1848. and '%' not in outtmpl
  1849. and self.params.get('max_downloads') != 1):
  1850. raise SameFileError(outtmpl)
  1851. for url in url_list:
  1852. try:
  1853. # It also downloads the videos
  1854. res = self.extract_info(
  1855. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  1856. except UnavailableVideoError:
  1857. self.report_error('unable to download video')
  1858. except MaxDownloadsReached:
  1859. self.to_screen('[info] Maximum number of downloaded files reached.')
  1860. raise
  1861. else:
  1862. if self.params.get('dump_single_json', False):
  1863. self.to_stdout(json.dumps(res))
  1864. return self._download_retcode
  1865. def download_with_info_file(self, info_filename):
  1866. with contextlib.closing(fileinput.FileInput(
  1867. [info_filename], mode='r',
  1868. openhook=fileinput.hook_encoded('utf-8'))) as f:
  1869. # FileInput doesn't have a read method, we can't call json.load
  1870. info = self.filter_requested_info(json.loads('\n'.join(f)))
  1871. try:
  1872. self.process_ie_result(info, download=True)
  1873. except DownloadError:
  1874. webpage_url = info.get('webpage_url')
  1875. if webpage_url is not None:
  1876. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1877. return self.download([webpage_url])
  1878. else:
  1879. raise
  1880. return self._download_retcode
  1881. @staticmethod
  1882. def filter_requested_info(info_dict):
  1883. return dict(
  1884. (k, v) for k, v in info_dict.items()
  1885. if k not in ['requested_formats', 'requested_subtitles'])
  1886. def post_process(self, filename, ie_info):
  1887. """Run all the postprocessors on the given file."""
  1888. info = dict(ie_info)
  1889. info['filepath'] = filename
  1890. pps_chain = []
  1891. if ie_info.get('__postprocessors') is not None:
  1892. pps_chain.extend(ie_info['__postprocessors'])
  1893. pps_chain.extend(self._pps)
  1894. for pp in pps_chain:
  1895. files_to_delete = []
  1896. try:
  1897. files_to_delete, info = pp.run(info)
  1898. except PostProcessingError as e:
  1899. self.report_error(e.msg)
  1900. if files_to_delete and not self.params.get('keepvideo', False):
  1901. for old_filename in files_to_delete:
  1902. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1903. try:
  1904. os.remove(encodeFilename(old_filename))
  1905. except (IOError, OSError):
  1906. self.report_warning('Unable to remove downloaded original file')
  1907. def _make_archive_id(self, info_dict):
  1908. video_id = info_dict.get('id')
  1909. if not video_id:
  1910. return
  1911. # Future-proof against any change in case
  1912. # and backwards compatibility with prior versions
  1913. extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
  1914. if extractor is None:
  1915. url = str_or_none(info_dict.get('url'))
  1916. if not url:
  1917. return
  1918. # Try to find matching extractor for the URL and take its ie_key
  1919. for ie in self._ies:
  1920. if ie.suitable(url):
  1921. extractor = ie.ie_key()
  1922. break
  1923. else:
  1924. return
  1925. return extractor.lower() + ' ' + video_id
  1926. def in_download_archive(self, info_dict):
  1927. fn = self.params.get('download_archive')
  1928. if fn is None:
  1929. return False
  1930. vid_id = self._make_archive_id(info_dict)
  1931. if not vid_id:
  1932. return False # Incomplete video information
  1933. try:
  1934. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1935. for line in archive_file:
  1936. if line.strip() == vid_id:
  1937. return True
  1938. except IOError as ioe:
  1939. if ioe.errno != errno.ENOENT:
  1940. raise
  1941. return False
  1942. def record_download_archive(self, info_dict):
  1943. fn = self.params.get('download_archive')
  1944. if fn is None:
  1945. return
  1946. vid_id = self._make_archive_id(info_dict)
  1947. assert vid_id
  1948. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1949. archive_file.write(vid_id + '\n')
  1950. @staticmethod
  1951. def format_resolution(format, default='unknown'):
  1952. if format.get('vcodec') == 'none':
  1953. return 'audio only'
  1954. if format.get('resolution') is not None:
  1955. return format['resolution']
  1956. if format.get('height') is not None:
  1957. if format.get('width') is not None:
  1958. res = '%sx%s' % (format['width'], format['height'])
  1959. else:
  1960. res = '%sp' % format['height']
  1961. elif format.get('width') is not None:
  1962. res = '%dx?' % format['width']
  1963. else:
  1964. res = default
  1965. return res
  1966. def _format_note(self, fdict):
  1967. res = ''
  1968. if fdict.get('ext') in ['f4f', 'f4m']:
  1969. res += '(unsupported) '
  1970. if fdict.get('language'):
  1971. if res:
  1972. res += ' '
  1973. res += '[%s] ' % fdict['language']
  1974. if fdict.get('format_note') is not None:
  1975. res += fdict['format_note'] + ' '
  1976. if fdict.get('tbr') is not None:
  1977. res += '%4dk ' % fdict['tbr']
  1978. if fdict.get('container') is not None:
  1979. if res:
  1980. res += ', '
  1981. res += '%s container' % fdict['container']
  1982. if (fdict.get('vcodec') is not None
  1983. and fdict.get('vcodec') != 'none'):
  1984. if res:
  1985. res += ', '
  1986. res += fdict['vcodec']
  1987. if fdict.get('vbr') is not None:
  1988. res += '@'
  1989. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1990. res += 'video@'
  1991. if fdict.get('vbr') is not None:
  1992. res += '%4dk' % fdict['vbr']
  1993. if fdict.get('fps') is not None:
  1994. if res:
  1995. res += ', '
  1996. res += '%sfps' % fdict['fps']
  1997. if fdict.get('acodec') is not None:
  1998. if res:
  1999. res += ', '
  2000. if fdict['acodec'] == 'none':
  2001. res += 'video only'
  2002. else:
  2003. res += '%-5s' % fdict['acodec']
  2004. elif fdict.get('abr') is not None:
  2005. if res:
  2006. res += ', '
  2007. res += 'audio'
  2008. if fdict.get('abr') is not None:
  2009. res += '@%3dk' % fdict['abr']
  2010. if fdict.get('asr') is not None:
  2011. res += ' (%5dHz)' % fdict['asr']
  2012. if fdict.get('filesize') is not None:
  2013. if res:
  2014. res += ', '
  2015. res += format_bytes(fdict['filesize'])
  2016. elif fdict.get('filesize_approx') is not None:
  2017. if res:
  2018. res += ', '
  2019. res += '~' + format_bytes(fdict['filesize_approx'])
  2020. return res
  2021. def list_formats(self, info_dict):
  2022. formats = info_dict.get('formats', [info_dict])
  2023. table = [
  2024. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  2025. for f in formats
  2026. if f.get('preference') is None or f['preference'] >= -1000]
  2027. if len(formats) > 1:
  2028. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  2029. header_line = ['format code', 'extension', 'resolution', 'note']
  2030. self.to_screen(
  2031. '[info] Available formats for %s:\n%s' %
  2032. (info_dict['id'], render_table(header_line, table)))
  2033. def list_thumbnails(self, info_dict):
  2034. thumbnails = info_dict.get('thumbnails')
  2035. if not thumbnails:
  2036. self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
  2037. return
  2038. self.to_screen(
  2039. '[info] Thumbnails for %s:' % info_dict['id'])
  2040. self.to_screen(render_table(
  2041. ['ID', 'width', 'height', 'URL'],
  2042. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  2043. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  2044. if not subtitles:
  2045. self.to_screen('%s has no %s' % (video_id, name))
  2046. return
  2047. self.to_screen(
  2048. 'Available %s for %s:' % (name, video_id))
  2049. self.to_screen(render_table(
  2050. ['Language', 'formats'],
  2051. [[lang, ', '.join(f['ext'] for f in reversed(formats))]
  2052. for lang, formats in subtitles.items()]))
  2053. def urlopen(self, req):
  2054. """ Start an HTTP download """
  2055. if isinstance(req, compat_basestring):
  2056. req = sanitized_Request(req)
  2057. return self._opener.open(req, timeout=self._socket_timeout)
  2058. def print_debug_header(self):
  2059. if not self.params.get('verbose'):
  2060. return
  2061. if type('') is not compat_str:
  2062. # Python 2.6 on SLES11 SP1 (https://github.com/ytdl-org/youtube-dl/issues/3326)
  2063. self.report_warning(
  2064. 'Your Python is broken! Update to a newer and supported version')
  2065. stdout_encoding = getattr(
  2066. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  2067. encoding_str = (
  2068. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  2069. locale.getpreferredencoding(),
  2070. sys.getfilesystemencoding(),
  2071. stdout_encoding,
  2072. self.get_encoding()))
  2073. write_string(encoding_str, encoding=None)
  2074. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  2075. if _LAZY_LOADER:
  2076. self._write_string('[debug] Lazy loading extractors enabled' + '\n')
  2077. try:
  2078. sp = subprocess.Popen(
  2079. ['git', 'rev-parse', '--short', 'HEAD'],
  2080. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  2081. cwd=os.path.dirname(os.path.abspath(__file__)))
  2082. out, err = process_communicate_or_kill(sp)
  2083. out = out.decode().strip()
  2084. if re.match('[0-9a-f]+', out):
  2085. self._write_string('[debug] Git HEAD: ' + out + '\n')
  2086. except Exception:
  2087. try:
  2088. sys.exc_clear()
  2089. except Exception:
  2090. pass
  2091. def python_implementation():
  2092. impl_name = platform.python_implementation()
  2093. if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
  2094. return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
  2095. return impl_name
  2096. self._write_string('[debug] Python version %s (%s) - %s\n' % (
  2097. platform.python_version(), python_implementation(),
  2098. platform_name()))
  2099. exe_versions = FFmpegPostProcessor.get_versions(self)
  2100. exe_versions['rtmpdump'] = rtmpdump_version()
  2101. exe_versions['phantomjs'] = PhantomJSwrapper._version()
  2102. exe_str = ', '.join(
  2103. '%s %s' % (exe, v)
  2104. for exe, v in sorted(exe_versions.items())
  2105. if v
  2106. )
  2107. if not exe_str:
  2108. exe_str = 'none'
  2109. self._write_string('[debug] exe versions: %s\n' % exe_str)
  2110. proxy_map = {}
  2111. for handler in self._opener.handlers:
  2112. if hasattr(handler, 'proxies'):
  2113. proxy_map.update(handler.proxies)
  2114. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  2115. if self.params.get('call_home', False):
  2116. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  2117. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  2118. latest_version = self.urlopen(
  2119. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  2120. if version_tuple(latest_version) > version_tuple(__version__):
  2121. self.report_warning(
  2122. 'You are using an outdated version (newest version: %s)! '
  2123. 'See https://yt-dl.org/update if you need help updating.' %
  2124. latest_version)
  2125. def _setup_opener(self):
  2126. timeout_val = self.params.get('socket_timeout')
  2127. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  2128. opts_cookiefile = self.params.get('cookiefile')
  2129. opts_proxy = self.params.get('proxy')
  2130. if opts_cookiefile is None:
  2131. self.cookiejar = compat_cookiejar.CookieJar()
  2132. else:
  2133. opts_cookiefile = expand_path(opts_cookiefile)
  2134. self.cookiejar = YoutubeDLCookieJar(opts_cookiefile)
  2135. if os.access(opts_cookiefile, os.R_OK):
  2136. self.cookiejar.load(ignore_discard=True, ignore_expires=True)
  2137. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  2138. if opts_proxy is not None:
  2139. if opts_proxy == '':
  2140. proxies = {}
  2141. else:
  2142. proxies = {'http': opts_proxy, 'https': opts_proxy}
  2143. else:
  2144. proxies = compat_urllib_request.getproxies()
  2145. # Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
  2146. if 'http' in proxies and 'https' not in proxies:
  2147. proxies['https'] = proxies['http']
  2148. proxy_handler = PerRequestProxyHandler(proxies)
  2149. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  2150. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  2151. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  2152. redirect_handler = YoutubeDLRedirectHandler()
  2153. data_handler = compat_urllib_request_DataHandler()
  2154. # When passing our own FileHandler instance, build_opener won't add the
  2155. # default FileHandler and allows us to disable the file protocol, which
  2156. # can be used for malicious purposes (see
  2157. # https://github.com/ytdl-org/youtube-dl/issues/8227)
  2158. file_handler = compat_urllib_request.FileHandler()
  2159. def file_open(*args, **kwargs):
  2160. raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
  2161. file_handler.file_open = file_open
  2162. opener = compat_urllib_request.build_opener(
  2163. proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
  2164. # Delete the default user-agent header, which would otherwise apply in
  2165. # cases where our custom HTTP handler doesn't come into play
  2166. # (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
  2167. opener.addheaders = []
  2168. self._opener = opener
  2169. def encode(self, s):
  2170. if isinstance(s, bytes):
  2171. return s # Already encoded
  2172. try:
  2173. return s.encode(self.get_encoding())
  2174. except UnicodeEncodeError as err:
  2175. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  2176. raise
  2177. def get_encoding(self):
  2178. encoding = self.params.get('encoding')
  2179. if encoding is None:
  2180. encoding = preferredencoding()
  2181. return encoding
  2182. def _write_thumbnails(self, info_dict, filename):
  2183. if self.params.get('writethumbnail', False):
  2184. thumbnails = info_dict.get('thumbnails')
  2185. if thumbnails:
  2186. thumbnails = [thumbnails[-1]]
  2187. elif self.params.get('write_all_thumbnails', False):
  2188. thumbnails = info_dict.get('thumbnails')
  2189. else:
  2190. return
  2191. if not thumbnails:
  2192. # No thumbnails present, so return immediately
  2193. return
  2194. for t in thumbnails:
  2195. thumb_ext = determine_ext(t['url'], 'jpg')
  2196. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  2197. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  2198. t['filename'] = thumb_filename = replace_extension(filename + suffix, thumb_ext, info_dict.get('ext'))
  2199. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  2200. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  2201. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  2202. else:
  2203. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  2204. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  2205. try:
  2206. uf = self.urlopen(t['url'])
  2207. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  2208. shutil.copyfileobj(uf, thumbf)
  2209. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  2210. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  2211. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2212. self.report_warning('Unable to download thumbnail "%s": %s' %
  2213. (t['url'], error_to_compat_str(err)))