YoutubeDL.py 121 KB

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