2
0

YoutubeDL.py 121 KB

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