YoutubeDL.py 201 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276
  1. import collections
  2. import contextlib
  3. import copy
  4. import datetime
  5. import errno
  6. import fileinput
  7. import http.cookiejar
  8. import io
  9. import itertools
  10. import json
  11. import locale
  12. import operator
  13. import os
  14. import random
  15. import re
  16. import shutil
  17. import string
  18. import subprocess
  19. import sys
  20. import tempfile
  21. import time
  22. import tokenize
  23. import traceback
  24. import unicodedata
  25. from .cache import Cache
  26. from .compat import functools, urllib # isort: split
  27. from .compat import compat_os_name, compat_shlex_quote, urllib_req_to_req
  28. from .cookies import LenientSimpleCookie, load_cookies
  29. from .downloader import FFmpegFD, get_suitable_downloader, shorten_protocol_name
  30. from .downloader.rtmp import rtmpdump_version
  31. from .extractor import gen_extractor_classes, get_info_extractor
  32. from .extractor.common import UnsupportedURLIE
  33. from .extractor.openload import PhantomJSwrapper
  34. from .minicurses import format_text
  35. from .networking import HEADRequest, Request, RequestDirector
  36. from .networking.common import _REQUEST_HANDLERS
  37. from .networking.exceptions import (
  38. HTTPError,
  39. NoSupportingHandlers,
  40. RequestError,
  41. SSLError,
  42. _CompatHTTPError,
  43. network_exceptions,
  44. )
  45. from .plugins import directories as plugin_directories
  46. from .postprocessor import _PLUGIN_CLASSES as plugin_pps
  47. from .postprocessor import (
  48. EmbedThumbnailPP,
  49. FFmpegFixupDuplicateMoovPP,
  50. FFmpegFixupDurationPP,
  51. FFmpegFixupM3u8PP,
  52. FFmpegFixupM4aPP,
  53. FFmpegFixupStretchedPP,
  54. FFmpegFixupTimestampPP,
  55. FFmpegMergerPP,
  56. FFmpegPostProcessor,
  57. FFmpegVideoConvertorPP,
  58. MoveFilesAfterDownloadPP,
  59. get_postprocessor,
  60. )
  61. from .postprocessor.ffmpeg import resolve_mapping as resolve_recode_mapping
  62. from .update import REPOSITORY, current_git_head, detect_variant
  63. from .utils import (
  64. DEFAULT_OUTTMPL,
  65. IDENTITY,
  66. LINK_TEMPLATES,
  67. MEDIA_EXTENSIONS,
  68. NO_DEFAULT,
  69. NUMBER_RE,
  70. OUTTMPL_TYPES,
  71. POSTPROCESS_WHEN,
  72. STR_FORMAT_RE_TMPL,
  73. STR_FORMAT_TYPES,
  74. ContentTooShortError,
  75. DateRange,
  76. DownloadCancelled,
  77. DownloadError,
  78. EntryNotInPlaylist,
  79. ExistingVideoReached,
  80. ExtractorError,
  81. FormatSorter,
  82. GeoRestrictedError,
  83. ISO3166Utils,
  84. LazyList,
  85. MaxDownloadsReached,
  86. Namespace,
  87. PagedList,
  88. PlaylistEntries,
  89. Popen,
  90. PostProcessingError,
  91. ReExtractInfo,
  92. RejectedVideoReached,
  93. SameFileError,
  94. UnavailableVideoError,
  95. UserNotLive,
  96. age_restricted,
  97. args_to_str,
  98. bug_reports_message,
  99. date_from_str,
  100. deprecation_warning,
  101. determine_ext,
  102. determine_protocol,
  103. encode_compat_str,
  104. encodeFilename,
  105. error_to_compat_str,
  106. escapeHTML,
  107. expand_path,
  108. extract_basic_auth,
  109. filter_dict,
  110. float_or_none,
  111. format_bytes,
  112. format_decimal_suffix,
  113. format_field,
  114. formatSeconds,
  115. get_compatible_ext,
  116. get_domain,
  117. int_or_none,
  118. iri_to_uri,
  119. is_path_like,
  120. join_nonempty,
  121. locked_file,
  122. make_archive_id,
  123. make_dir,
  124. number_of_digits,
  125. orderedSet,
  126. orderedSet_from_options,
  127. parse_filesize,
  128. preferredencoding,
  129. prepend_extension,
  130. remove_terminal_sequences,
  131. render_table,
  132. replace_extension,
  133. sanitize_filename,
  134. sanitize_path,
  135. sanitize_url,
  136. str_or_none,
  137. strftime_or_none,
  138. subtitles_filename,
  139. supports_terminal_sequences,
  140. system_identifier,
  141. timetuple_from_msec,
  142. to_high_limit_path,
  143. traverse_obj,
  144. try_call,
  145. try_get,
  146. url_basename,
  147. variadic,
  148. version_tuple,
  149. windows_enable_vt_mode,
  150. write_json_file,
  151. write_string,
  152. )
  153. from .utils._utils import _YDLLogger
  154. from .utils.networking import (
  155. HTTPHeaderDict,
  156. clean_headers,
  157. clean_proxies,
  158. std_headers,
  159. )
  160. from .version import CHANNEL, RELEASE_GIT_HEAD, VARIANT, __version__
  161. if compat_os_name == 'nt':
  162. import ctypes
  163. class YoutubeDL:
  164. """YoutubeDL class.
  165. YoutubeDL objects are the ones responsible of downloading the
  166. actual video file and writing it to disk if the user has requested
  167. it, among some other tasks. In most cases there should be one per
  168. program. As, given a video URL, the downloader doesn't know how to
  169. extract all the needed information, task that InfoExtractors do, it
  170. has to pass the URL to one of them.
  171. For this, YoutubeDL objects have a method that allows
  172. InfoExtractors to be registered in a given order. When it is passed
  173. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  174. finds that reports being able to handle it. The InfoExtractor extracts
  175. all the information about the video or videos the URL refers to, and
  176. YoutubeDL process the extracted information, possibly using a File
  177. Downloader to download the video.
  178. YoutubeDL objects accept a lot of parameters. In order not to saturate
  179. the object constructor with arguments, it receives a dictionary of
  180. options instead. These options are available through the params
  181. attribute for the InfoExtractors to use. The YoutubeDL also
  182. registers itself as the downloader in charge for the InfoExtractors
  183. that are added to it, so this is a "mutual registration".
  184. Available options:
  185. username: Username for authentication purposes.
  186. password: Password for authentication purposes.
  187. videopassword: Password for accessing a video.
  188. ap_mso: Adobe Pass multiple-system operator identifier.
  189. ap_username: Multiple-system operator account username.
  190. ap_password: Multiple-system operator account password.
  191. usenetrc: Use netrc for authentication instead.
  192. netrc_location: Location of the netrc file. Defaults to ~/.netrc.
  193. netrc_cmd: Use a shell command to get credentials
  194. verbose: Print additional info to stdout.
  195. quiet: Do not print messages to stdout.
  196. no_warnings: Do not print out anything for warnings.
  197. forceprint: A dict with keys WHEN mapped to a list of templates to
  198. print to stdout. The allowed keys are video or any of the
  199. items in utils.POSTPROCESS_WHEN.
  200. For compatibility, a single list is also accepted
  201. print_to_file: A dict with keys WHEN (same as forceprint) mapped to
  202. a list of tuples with (template, filename)
  203. forcejson: Force printing info_dict as JSON.
  204. dump_single_json: Force printing the info_dict of the whole playlist
  205. (or video) as a single JSON line.
  206. force_write_download_archive: Force writing download archive regardless
  207. of 'skip_download' or 'simulate'.
  208. simulate: Do not download the video files. If unset (or None),
  209. simulate only if listsubtitles, listformats or list_thumbnails is used
  210. format: Video format code. see "FORMAT SELECTION" for more details.
  211. You can also pass a function. The function takes 'ctx' as
  212. argument and returns the formats to download.
  213. See "build_format_selector" for an implementation
  214. allow_unplayable_formats: Allow unplayable formats to be extracted and downloaded.
  215. ignore_no_formats_error: Ignore "No video formats" error. Usefull for
  216. extracting metadata even if the video is not actually
  217. available for download (experimental)
  218. format_sort: A list of fields by which to sort the video formats.
  219. See "Sorting Formats" for more details.
  220. format_sort_force: Force the given format_sort. see "Sorting Formats"
  221. for more details.
  222. prefer_free_formats: Whether to prefer video formats with free containers
  223. over non-free ones of same quality.
  224. allow_multiple_video_streams: Allow multiple video streams to be merged
  225. into a single file
  226. allow_multiple_audio_streams: Allow multiple audio streams to be merged
  227. into a single file
  228. check_formats Whether to test if the formats are downloadable.
  229. Can be True (check all), False (check none),
  230. 'selected' (check selected formats),
  231. or None (check only if requested by extractor)
  232. paths: Dictionary of output paths. The allowed keys are 'home'
  233. 'temp' and the keys of OUTTMPL_TYPES (in utils.py)
  234. outtmpl: Dictionary of templates for output names. Allowed keys
  235. are 'default' and the keys of OUTTMPL_TYPES (in utils.py).
  236. For compatibility with youtube-dl, a single string can also be used
  237. outtmpl_na_placeholder: Placeholder for unavailable meta fields.
  238. restrictfilenames: Do not allow "&" and spaces in file names
  239. trim_file_name: Limit length of filename (extension excluded)
  240. windowsfilenames: Force the filenames to be windows compatible
  241. ignoreerrors: Do not stop on download/postprocessing errors.
  242. Can be 'only_download' to ignore only download errors.
  243. Default is 'only_download' for CLI, but False for API
  244. skip_playlist_after_errors: Number of allowed failures until the rest of
  245. the playlist is skipped
  246. allowed_extractors: List of regexes to match against extractor names that are allowed
  247. overwrites: Overwrite all video and metadata files if True,
  248. overwrite only non-video files if None
  249. and don't overwrite any file if False
  250. For compatibility with youtube-dl,
  251. "nooverwrites" may also be used instead
  252. playlist_items: Specific indices of playlist to download.
  253. playlistrandom: Download playlist items in random order.
  254. lazy_playlist: Process playlist entries as they are received.
  255. matchtitle: Download only matching titles.
  256. rejecttitle: Reject downloads for matching titles.
  257. logger: Log messages to a logging.Logger instance.
  258. logtostderr: Print everything to stderr instead of stdout.
  259. consoletitle: Display progress in console window's titlebar.
  260. writedescription: Write the video description to a .description file
  261. writeinfojson: Write the video description to a .info.json file
  262. clean_infojson: Remove internal metadata from the infojson
  263. getcomments: Extract video comments. This will not be written to disk
  264. unless writeinfojson is also given
  265. writeannotations: Write the video annotations to a .annotations.xml file
  266. writethumbnail: Write the thumbnail image to a file
  267. allow_playlist_files: Whether to write playlists' description, infojson etc
  268. also to disk when using the 'write*' options
  269. write_all_thumbnails: Write all thumbnail formats to files
  270. writelink: Write an internet shortcut file, depending on the
  271. current platform (.url/.webloc/.desktop)
  272. writeurllink: Write a Windows internet shortcut file (.url)
  273. writewebloclink: Write a macOS internet shortcut file (.webloc)
  274. writedesktoplink: Write a Linux internet shortcut file (.desktop)
  275. writesubtitles: Write the video subtitles to a file
  276. writeautomaticsub: Write the automatically generated subtitles to a file
  277. listsubtitles: Lists all available subtitles for the video
  278. subtitlesformat: The format code for subtitles
  279. subtitleslangs: List of languages of the subtitles to download (can be regex).
  280. The list may contain "all" to refer to all the available
  281. subtitles. The language can be prefixed with a "-" to
  282. exclude it from the requested languages, e.g. ['all', '-live_chat']
  283. keepvideo: Keep the video file after post-processing
  284. daterange: A utils.DateRange object, download only if the upload_date is in the range.
  285. skip_download: Skip the actual download of the video file
  286. cachedir: Location of the cache files in the filesystem.
  287. False to disable filesystem cache.
  288. noplaylist: Download single video instead of a playlist if in doubt.
  289. age_limit: An integer representing the user's age in years.
  290. Unsuitable videos for the given age are skipped.
  291. min_views: An integer representing the minimum view count the video
  292. must have in order to not be skipped.
  293. Videos without view count information are always
  294. downloaded. None for no limit.
  295. max_views: An integer representing the maximum view count.
  296. Videos that are more popular than that are not
  297. downloaded.
  298. Videos without view count information are always
  299. downloaded. None for no limit.
  300. download_archive: A set, or the name of a file where all downloads are recorded.
  301. Videos already present in the file are not downloaded again.
  302. break_on_existing: Stop the download process after attempting to download a
  303. file that is in the archive.
  304. break_per_url: Whether break_on_reject and break_on_existing
  305. should act on each input URL as opposed to for the entire queue
  306. cookiefile: File name or text stream from where cookies should be read and dumped to
  307. cookiesfrombrowser: A tuple containing the name of the browser, the profile
  308. name/path from where cookies are loaded, the name of the keyring,
  309. and the container name, e.g. ('chrome', ) or
  310. ('vivaldi', 'default', 'BASICTEXT') or ('firefox', 'default', None, 'Meta')
  311. legacyserverconnect: Explicitly allow HTTPS connection to servers that do not
  312. support RFC 5746 secure renegotiation
  313. nocheckcertificate: Do not verify SSL certificates
  314. client_certificate: Path to client certificate file in PEM format. May include the private key
  315. client_certificate_key: Path to private key file for client certificate
  316. client_certificate_password: Password for client certificate private key, if encrypted.
  317. If not provided and the key is encrypted, yt-dlp will ask interactively
  318. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  319. (Only supported by some extractors)
  320. enable_file_urls: Enable file:// URLs. This is disabled by default for security reasons.
  321. http_headers: A dictionary of custom headers to be used for all requests
  322. proxy: URL of the proxy server to use
  323. geo_verification_proxy: URL of the proxy to use for IP address verification
  324. on geo-restricted sites.
  325. socket_timeout: Time to wait for unresponsive hosts, in seconds
  326. bidi_workaround: Work around buggy terminals without bidirectional text
  327. support, using fridibi
  328. debug_printtraffic:Print out sent and received HTTP traffic
  329. default_search: Prepend this string if an input url is not valid.
  330. 'auto' for elaborate guessing
  331. encoding: Use this encoding instead of the system-specified.
  332. extract_flat: Whether to resolve and process url_results further
  333. * False: Always process. Default for API
  334. * True: Never process
  335. * 'in_playlist': Do not process inside playlist/multi_video
  336. * 'discard': Always process, but don't return the result
  337. from inside playlist/multi_video
  338. * 'discard_in_playlist': Same as "discard", but only for
  339. playlists (not multi_video). Default for CLI
  340. wait_for_video: If given, wait for scheduled streams to become available.
  341. The value should be a tuple containing the range
  342. (min_secs, max_secs) to wait between retries
  343. postprocessors: A list of dictionaries, each with an entry
  344. * key: The name of the postprocessor. See
  345. yt_dlp/postprocessor/__init__.py for a list.
  346. * when: When to run the postprocessor. Allowed values are
  347. the entries of utils.POSTPROCESS_WHEN
  348. Assumed to be 'post_process' if not given
  349. progress_hooks: A list of functions that get called on download
  350. progress, with a dictionary with the entries
  351. * status: One of "downloading", "error", or "finished".
  352. Check this first and ignore unknown values.
  353. * info_dict: The extracted info_dict
  354. If status is one of "downloading", or "finished", the
  355. following properties may also be present:
  356. * filename: The final filename (always present)
  357. * tmpfilename: The filename we're currently writing to
  358. * downloaded_bytes: Bytes on disk
  359. * total_bytes: Size of the whole file, None if unknown
  360. * total_bytes_estimate: Guess of the eventual file size,
  361. None if unavailable.
  362. * elapsed: The number of seconds since download started.
  363. * eta: The estimated time in seconds, None if unknown
  364. * speed: The download speed in bytes/second, None if
  365. unknown
  366. * fragment_index: The counter of the currently
  367. downloaded video fragment.
  368. * fragment_count: The number of fragments (= individual
  369. files that will be merged)
  370. Progress hooks are guaranteed to be called at least once
  371. (with status "finished") if the download is successful.
  372. postprocessor_hooks: A list of functions that get called on postprocessing
  373. progress, with a dictionary with the entries
  374. * status: One of "started", "processing", or "finished".
  375. Check this first and ignore unknown values.
  376. * postprocessor: Name of the postprocessor
  377. * info_dict: The extracted info_dict
  378. Progress hooks are guaranteed to be called at least twice
  379. (with status "started" and "finished") if the processing is successful.
  380. merge_output_format: "/" separated list of extensions to use when merging formats.
  381. final_ext: Expected final extension; used to detect when the file was
  382. already downloaded and converted
  383. fixup: Automatically correct known faults of the file.
  384. One of:
  385. - "never": do nothing
  386. - "warn": only emit a warning
  387. - "detect_or_warn": check whether we can do anything
  388. about it, warn otherwise (default)
  389. source_address: Client-side IP address to bind to.
  390. sleep_interval_requests: Number of seconds to sleep between requests
  391. during extraction
  392. sleep_interval: Number of seconds to sleep before each download when
  393. used alone or a lower bound of a range for randomized
  394. sleep before each download (minimum possible number
  395. of seconds to sleep) when used along with
  396. max_sleep_interval.
  397. max_sleep_interval:Upper bound of a range for randomized sleep before each
  398. download (maximum possible number of seconds to sleep).
  399. Must only be used along with sleep_interval.
  400. Actual sleep time will be a random float from range
  401. [sleep_interval; max_sleep_interval].
  402. sleep_interval_subtitles: Number of seconds to sleep before each subtitle download
  403. listformats: Print an overview of available video formats and exit.
  404. list_thumbnails: Print a table of all thumbnails and exit.
  405. match_filter: A function that gets called for every video with the signature
  406. (info_dict, *, incomplete: bool) -> Optional[str]
  407. For backward compatibility with youtube-dl, the signature
  408. (info_dict) -> Optional[str] is also allowed.
  409. - If it returns a message, the video is ignored.
  410. - If it returns None, the video is downloaded.
  411. - If it returns utils.NO_DEFAULT, the user is interactively
  412. asked whether to download the video.
  413. - Raise utils.DownloadCancelled(msg) to abort remaining
  414. downloads when a video is rejected.
  415. match_filter_func in utils.py is one example for this.
  416. color: A Dictionary with output stream names as keys
  417. and their respective color policy as values.
  418. Can also just be a single color policy,
  419. in which case it applies to all outputs.
  420. Valid stream names are 'stdout' and 'stderr'.
  421. Valid color policies are one of 'always', 'auto', 'no_color' or 'never'.
  422. geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
  423. HTTP header
  424. geo_bypass_country:
  425. Two-letter ISO 3166-2 country code that will be used for
  426. explicit geographic restriction bypassing via faking
  427. X-Forwarded-For HTTP header
  428. geo_bypass_ip_block:
  429. IP range in CIDR notation that will be used similarly to
  430. geo_bypass_country
  431. external_downloader: A dictionary of protocol keys and the executable of the
  432. external downloader to use for it. The allowed protocols
  433. are default|http|ftp|m3u8|dash|rtsp|rtmp|mms.
  434. Set the value to 'native' to use the native downloader
  435. compat_opts: Compatibility options. See "Differences in default behavior".
  436. The following options do not work when used through the API:
  437. filename, abort-on-error, multistreams, no-live-chat, format-sort
  438. no-clean-infojson, no-playlist-metafiles, no-keep-subs, no-attach-info-json.
  439. Refer __init__.py for their implementation
  440. progress_template: Dictionary of templates for progress outputs.
  441. Allowed keys are 'download', 'postprocess',
  442. 'download-title' (console title) and 'postprocess-title'.
  443. The template is mapped on a dictionary with keys 'progress' and 'info'
  444. retry_sleep_functions: Dictionary of functions that takes the number of attempts
  445. as argument and returns the time to sleep in seconds.
  446. Allowed keys are 'http', 'fragment', 'file_access'
  447. download_ranges: A callback function that gets called for every video with
  448. the signature (info_dict, ydl) -> Iterable[Section].
  449. Only the returned sections will be downloaded.
  450. Each Section is a dict with the following keys:
  451. * start_time: Start time of the section in seconds
  452. * end_time: End time of the section in seconds
  453. * title: Section title (Optional)
  454. * index: Section number (Optional)
  455. force_keyframes_at_cuts: Re-encode the video when downloading ranges to get precise cuts
  456. noprogress: Do not print the progress bar
  457. live_from_start: Whether to download livestreams videos from the start
  458. The following parameters are not used by YoutubeDL itself, they are used by
  459. the downloader (see yt_dlp/downloader/common.py):
  460. nopart, updatetime, buffersize, ratelimit, throttledratelimit, min_filesize,
  461. max_filesize, test, noresizebuffer, retries, file_access_retries, fragment_retries,
  462. continuedl, xattr_set_filesize, hls_use_mpegts, http_chunk_size,
  463. external_downloader_args, concurrent_fragment_downloads.
  464. The following options are used by the post processors:
  465. ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
  466. to the binary or its containing directory.
  467. postprocessor_args: A dictionary of postprocessor/executable keys (in lower case)
  468. and a list of additional command-line arguments for the
  469. postprocessor/executable. The dict can also have "PP+EXE" keys
  470. which are used when the given exe is used by the given PP.
  471. Use 'default' as the name for arguments to passed to all PP
  472. For compatibility with youtube-dl, a single list of args
  473. can also be used
  474. The following options are used by the extractors:
  475. extractor_retries: Number of times to retry for known errors (default: 3)
  476. dynamic_mpd: Whether to process dynamic DASH manifests (default: True)
  477. hls_split_discontinuity: Split HLS playlists to different formats at
  478. discontinuities such as ad breaks (default: False)
  479. extractor_args: A dictionary of arguments to be passed to the extractors.
  480. See "EXTRACTOR ARGUMENTS" for details.
  481. E.g. {'youtube': {'skip': ['dash', 'hls']}}
  482. mark_watched: Mark videos watched (even with --simulate). Only for YouTube
  483. The following options are deprecated and may be removed in the future:
  484. break_on_reject: Stop the download process when encountering a video that
  485. has been filtered out.
  486. - `raise DownloadCancelled(msg)` in match_filter instead
  487. force_generic_extractor: Force downloader to use the generic extractor
  488. - Use allowed_extractors = ['generic', 'default']
  489. playliststart: - Use playlist_items
  490. Playlist item to start at.
  491. playlistend: - Use playlist_items
  492. Playlist item to end at.
  493. playlistreverse: - Use playlist_items
  494. Download playlist items in reverse order.
  495. forceurl: - Use forceprint
  496. Force printing final URL.
  497. forcetitle: - Use forceprint
  498. Force printing title.
  499. forceid: - Use forceprint
  500. Force printing ID.
  501. forcethumbnail: - Use forceprint
  502. Force printing thumbnail URL.
  503. forcedescription: - Use forceprint
  504. Force printing description.
  505. forcefilename: - Use forceprint
  506. Force printing final filename.
  507. forceduration: - Use forceprint
  508. Force printing duration.
  509. allsubtitles: - Use subtitleslangs = ['all']
  510. Downloads all the subtitles of the video
  511. (requires writesubtitles or writeautomaticsub)
  512. include_ads: - Doesn't work
  513. Download ads as well
  514. call_home: - Not implemented
  515. Boolean, true iff we are allowed to contact the
  516. yt-dlp servers for debugging.
  517. post_hooks: - Register a custom postprocessor
  518. A list of functions that get called as the final step
  519. for each video file, after all postprocessors have been
  520. called. The filename will be passed as the only argument.
  521. hls_prefer_native: - Use external_downloader = {'m3u8': 'native'} or {'m3u8': 'ffmpeg'}.
  522. Use the native HLS downloader instead of ffmpeg/avconv
  523. if True, otherwise use ffmpeg/avconv if False, otherwise
  524. use downloader suggested by extractor if None.
  525. prefer_ffmpeg: - avconv support is deprecated
  526. If False, use avconv instead of ffmpeg if both are available,
  527. otherwise prefer ffmpeg.
  528. youtube_include_dash_manifest: - Use extractor_args
  529. If True (default), DASH manifests and related
  530. data will be downloaded and processed by extractor.
  531. You can reduce network I/O by disabling it if you don't
  532. care about DASH. (only for youtube)
  533. youtube_include_hls_manifest: - Use extractor_args
  534. If True (default), HLS manifests and related
  535. data will be downloaded and processed by extractor.
  536. You can reduce network I/O by disabling it if you don't
  537. care about HLS. (only for youtube)
  538. no_color: Same as `color='no_color'`
  539. """
  540. _NUMERIC_FIELDS = {
  541. 'width', 'height', 'asr', 'audio_channels', 'fps',
  542. 'tbr', 'abr', 'vbr', 'filesize', 'filesize_approx',
  543. 'timestamp', 'release_timestamp',
  544. 'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
  545. 'average_rating', 'comment_count', 'age_limit',
  546. 'start_time', 'end_time',
  547. 'chapter_number', 'season_number', 'episode_number',
  548. 'track_number', 'disc_number', 'release_year',
  549. }
  550. _format_fields = {
  551. # NB: Keep in sync with the docstring of extractor/common.py
  552. 'url', 'manifest_url', 'manifest_stream_number', 'ext', 'format', 'format_id', 'format_note',
  553. 'width', 'height', 'aspect_ratio', 'resolution', 'dynamic_range', 'tbr', 'abr', 'acodec', 'asr', 'audio_channels',
  554. 'vbr', 'fps', 'vcodec', 'container', 'filesize', 'filesize_approx', 'rows', 'columns',
  555. 'player_url', 'protocol', 'fragment_base_url', 'fragments', 'is_from_start',
  556. 'preference', 'language', 'language_preference', 'quality', 'source_preference',
  557. 'http_headers', 'stretched_ratio', 'no_resume', 'has_drm', 'extra_param_to_segment_url', 'hls_aes', 'downloader_options',
  558. 'page_url', 'app', 'play_path', 'tc_url', 'flash_version', 'rtmp_live', 'rtmp_conn', 'rtmp_protocol', 'rtmp_real_time'
  559. }
  560. _format_selection_exts = {
  561. 'audio': set(MEDIA_EXTENSIONS.common_audio),
  562. 'video': set(MEDIA_EXTENSIONS.common_video + ('3gp', )),
  563. 'storyboards': set(MEDIA_EXTENSIONS.storyboards),
  564. }
  565. def __init__(self, params=None, auto_init=True):
  566. """Create a FileDownloader object with the given options.
  567. @param auto_init Whether to load the default extractors and print header (if verbose).
  568. Set to 'no_verbose_header' to not print the header
  569. """
  570. if params is None:
  571. params = {}
  572. self.params = params
  573. self._ies = {}
  574. self._ies_instances = {}
  575. self._pps = {k: [] for k in POSTPROCESS_WHEN}
  576. self._printed_messages = set()
  577. self._first_webpage_request = True
  578. self._post_hooks = []
  579. self._progress_hooks = []
  580. self._postprocessor_hooks = []
  581. self._download_retcode = 0
  582. self._num_downloads = 0
  583. self._num_videos = 0
  584. self._playlist_level = 0
  585. self._playlist_urls = set()
  586. self.cache = Cache(self)
  587. stdout = sys.stderr if self.params.get('logtostderr') else sys.stdout
  588. self._out_files = Namespace(
  589. out=stdout,
  590. error=sys.stderr,
  591. screen=sys.stderr if self.params.get('quiet') else stdout,
  592. console=None if compat_os_name == 'nt' else next(
  593. filter(supports_terminal_sequences, (sys.stderr, sys.stdout)), None)
  594. )
  595. try:
  596. windows_enable_vt_mode()
  597. except Exception as e:
  598. self.write_debug(f'Failed to enable VT mode: {e}')
  599. if self.params.get('no_color'):
  600. if self.params.get('color') is not None:
  601. self.report_warning('Overwriting params from "color" with "no_color"')
  602. self.params['color'] = 'no_color'
  603. term_allow_color = os.environ.get('TERM', '').lower() != 'dumb'
  604. def process_color_policy(stream):
  605. stream_name = {sys.stdout: 'stdout', sys.stderr: 'stderr'}[stream]
  606. policy = traverse_obj(self.params, ('color', (stream_name, None), {str}), get_all=False)
  607. if policy in ('auto', None):
  608. return term_allow_color and supports_terminal_sequences(stream)
  609. assert policy in ('always', 'never', 'no_color')
  610. return {'always': True, 'never': False}.get(policy, policy)
  611. self._allow_colors = Namespace(**{
  612. name: process_color_policy(stream)
  613. for name, stream in self._out_files.items_ if name != 'console'
  614. })
  615. # The code is left like this to be reused for future deprecations
  616. MIN_SUPPORTED, MIN_RECOMMENDED = (3, 7), (3, 7)
  617. current_version = sys.version_info[:2]
  618. if current_version < MIN_RECOMMENDED:
  619. msg = ('Support for Python version %d.%d has been deprecated. '
  620. 'See https://github.com/yt-dlp/yt-dlp/issues/3764 for more details.'
  621. '\n You will no longer receive updates on this version')
  622. if current_version < MIN_SUPPORTED:
  623. msg = 'Python version %d.%d is no longer supported'
  624. self.deprecated_feature(
  625. f'{msg}! Please update to Python %d.%d or above' % (*current_version, *MIN_RECOMMENDED))
  626. if self.params.get('allow_unplayable_formats'):
  627. self.report_warning(
  628. f'You have asked for {self._format_err("UNPLAYABLE", self.Styles.EMPHASIS)} formats to be listed/downloaded. '
  629. 'This is a developer option intended for debugging. \n'
  630. ' If you experience any issues while using this option, '
  631. f'{self._format_err("DO NOT", self.Styles.ERROR)} open a bug report')
  632. if self.params.get('bidi_workaround', False):
  633. try:
  634. import pty
  635. master, slave = pty.openpty()
  636. width = shutil.get_terminal_size().columns
  637. width_args = [] if width is None else ['-w', str(width)]
  638. sp_kwargs = {'stdin': subprocess.PIPE, 'stdout': slave, 'stderr': self._out_files.error}
  639. try:
  640. self._output_process = Popen(['bidiv'] + width_args, **sp_kwargs)
  641. except OSError:
  642. self._output_process = Popen(['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  643. self._output_channel = os.fdopen(master, 'rb')
  644. except OSError as ose:
  645. if ose.errno == errno.ENOENT:
  646. self.report_warning(
  647. 'Could not find fribidi executable, ignoring --bidi-workaround. '
  648. 'Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  649. else:
  650. raise
  651. self.params['compat_opts'] = set(self.params.get('compat_opts', ()))
  652. self.params['http_headers'] = HTTPHeaderDict(std_headers, self.params.get('http_headers'))
  653. self.__header_cookies = []
  654. self._load_cookies(self.params['http_headers'].get('Cookie')) # compat
  655. self.params['http_headers'].pop('Cookie', None)
  656. self._request_director = self.build_request_director(
  657. sorted(_REQUEST_HANDLERS.values(), key=lambda rh: rh.RH_NAME.lower()))
  658. if auto_init and auto_init != 'no_verbose_header':
  659. self.print_debug_header()
  660. def check_deprecated(param, option, suggestion):
  661. if self.params.get(param) is not None:
  662. self.report_warning(f'{option} is deprecated. Use {suggestion} instead')
  663. return True
  664. return False
  665. if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
  666. if self.params.get('geo_verification_proxy') is None:
  667. self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
  668. check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
  669. check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
  670. check_deprecated('useid', '--id', '-o "%(id)s.%(ext)s"')
  671. for msg in self.params.get('_warnings', []):
  672. self.report_warning(msg)
  673. for msg in self.params.get('_deprecation_warnings', []):
  674. self.deprecated_feature(msg)
  675. if 'list-formats' in self.params['compat_opts']:
  676. self.params['listformats_table'] = False
  677. if 'overwrites' not in self.params and self.params.get('nooverwrites') is not None:
  678. # nooverwrites was unnecessarily changed to overwrites
  679. # in 0c3d0f51778b153f65c21906031c2e091fcfb641
  680. # This ensures compatibility with both keys
  681. self.params['overwrites'] = not self.params['nooverwrites']
  682. elif self.params.get('overwrites') is None:
  683. self.params.pop('overwrites', None)
  684. else:
  685. self.params['nooverwrites'] = not self.params['overwrites']
  686. if self.params.get('simulate') is None and any((
  687. self.params.get('list_thumbnails'),
  688. self.params.get('listformats'),
  689. self.params.get('listsubtitles'),
  690. )):
  691. self.params['simulate'] = 'list_only'
  692. self.params.setdefault('forceprint', {})
  693. self.params.setdefault('print_to_file', {})
  694. # Compatibility with older syntax
  695. if not isinstance(params['forceprint'], dict):
  696. self.params['forceprint'] = {'video': params['forceprint']}
  697. if auto_init:
  698. self.add_default_info_extractors()
  699. if (sys.platform != 'win32'
  700. and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  701. and not self.params.get('restrictfilenames', False)):
  702. # Unicode filesystem API will throw errors (#1474, #13027)
  703. self.report_warning(
  704. 'Assuming --restrict-filenames since file system encoding '
  705. 'cannot encode all characters. '
  706. 'Set the LC_ALL environment variable to fix this.')
  707. self.params['restrictfilenames'] = True
  708. self._parse_outtmpl()
  709. # Creating format selector here allows us to catch syntax errors before the extraction
  710. self.format_selector = (
  711. self.params.get('format') if self.params.get('format') in (None, '-')
  712. else self.params['format'] if callable(self.params['format'])
  713. else self.build_format_selector(self.params['format']))
  714. hooks = {
  715. 'post_hooks': self.add_post_hook,
  716. 'progress_hooks': self.add_progress_hook,
  717. 'postprocessor_hooks': self.add_postprocessor_hook,
  718. }
  719. for opt, fn in hooks.items():
  720. for ph in self.params.get(opt, []):
  721. fn(ph)
  722. for pp_def_raw in self.params.get('postprocessors', []):
  723. pp_def = dict(pp_def_raw)
  724. when = pp_def.pop('when', 'post_process')
  725. self.add_post_processor(
  726. get_postprocessor(pp_def.pop('key'))(self, **pp_def),
  727. when=when)
  728. def preload_download_archive(fn):
  729. """Preload the archive, if any is specified"""
  730. archive = set()
  731. if fn is None:
  732. return archive
  733. elif not is_path_like(fn):
  734. return fn
  735. self.write_debug(f'Loading archive file {fn!r}')
  736. try:
  737. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  738. for line in archive_file:
  739. archive.add(line.strip())
  740. except OSError as ioe:
  741. if ioe.errno != errno.ENOENT:
  742. raise
  743. return archive
  744. self.archive = preload_download_archive(self.params.get('download_archive'))
  745. def warn_if_short_id(self, argv):
  746. # short YouTube ID starting with dash?
  747. idxs = [
  748. i for i, a in enumerate(argv)
  749. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  750. if idxs:
  751. correct_argv = (
  752. ['yt-dlp']
  753. + [a for i, a in enumerate(argv) if i not in idxs]
  754. + ['--'] + [argv[i] for i in idxs]
  755. )
  756. self.report_warning(
  757. 'Long argument string detected. '
  758. 'Use -- to separate parameters and URLs, like this:\n%s' %
  759. args_to_str(correct_argv))
  760. def add_info_extractor(self, ie):
  761. """Add an InfoExtractor object to the end of the list."""
  762. ie_key = ie.ie_key()
  763. self._ies[ie_key] = ie
  764. if not isinstance(ie, type):
  765. self._ies_instances[ie_key] = ie
  766. ie.set_downloader(self)
  767. def get_info_extractor(self, ie_key):
  768. """
  769. Get an instance of an IE with name ie_key, it will try to get one from
  770. the _ies list, if there's no instance it will create a new one and add
  771. it to the extractor list.
  772. """
  773. ie = self._ies_instances.get(ie_key)
  774. if ie is None:
  775. ie = get_info_extractor(ie_key)()
  776. self.add_info_extractor(ie)
  777. return ie
  778. def add_default_info_extractors(self):
  779. """
  780. Add the InfoExtractors returned by gen_extractors to the end of the list
  781. """
  782. all_ies = {ie.IE_NAME.lower(): ie for ie in gen_extractor_classes()}
  783. all_ies['end'] = UnsupportedURLIE()
  784. try:
  785. ie_names = orderedSet_from_options(
  786. self.params.get('allowed_extractors', ['default']), {
  787. 'all': list(all_ies),
  788. 'default': [name for name, ie in all_ies.items() if ie._ENABLED],
  789. }, use_regex=True)
  790. except re.error as e:
  791. raise ValueError(f'Wrong regex for allowed_extractors: {e.pattern}')
  792. for name in ie_names:
  793. self.add_info_extractor(all_ies[name])
  794. self.write_debug(f'Loaded {len(ie_names)} extractors')
  795. def add_post_processor(self, pp, when='post_process'):
  796. """Add a PostProcessor object to the end of the chain."""
  797. assert when in POSTPROCESS_WHEN, f'Invalid when={when}'
  798. self._pps[when].append(pp)
  799. pp.set_downloader(self)
  800. def add_post_hook(self, ph):
  801. """Add the post hook"""
  802. self._post_hooks.append(ph)
  803. def add_progress_hook(self, ph):
  804. """Add the download progress hook"""
  805. self._progress_hooks.append(ph)
  806. def add_postprocessor_hook(self, ph):
  807. """Add the postprocessing progress hook"""
  808. self._postprocessor_hooks.append(ph)
  809. for pps in self._pps.values():
  810. for pp in pps:
  811. pp.add_progress_hook(ph)
  812. def _bidi_workaround(self, message):
  813. if not hasattr(self, '_output_channel'):
  814. return message
  815. assert hasattr(self, '_output_process')
  816. assert isinstance(message, str)
  817. line_count = message.count('\n') + 1
  818. self._output_process.stdin.write((message + '\n').encode())
  819. self._output_process.stdin.flush()
  820. res = ''.join(self._output_channel.readline().decode()
  821. for _ in range(line_count))
  822. return res[:-len('\n')]
  823. def _write_string(self, message, out=None, only_once=False):
  824. if only_once:
  825. if message in self._printed_messages:
  826. return
  827. self._printed_messages.add(message)
  828. write_string(message, out=out, encoding=self.params.get('encoding'))
  829. def to_stdout(self, message, skip_eol=False, quiet=None):
  830. """Print message to stdout"""
  831. if quiet is not None:
  832. self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument quiet. '
  833. 'Use "YoutubeDL.to_screen" instead')
  834. if skip_eol is not False:
  835. self.deprecation_warning('"YoutubeDL.to_stdout" no longer accepts the argument skip_eol. '
  836. 'Use "YoutubeDL.to_screen" instead')
  837. self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.out)
  838. def to_screen(self, message, skip_eol=False, quiet=None, only_once=False):
  839. """Print message to screen if not in quiet mode"""
  840. if self.params.get('logger'):
  841. self.params['logger'].debug(message)
  842. return
  843. if (self.params.get('quiet') if quiet is None else quiet) and not self.params.get('verbose'):
  844. return
  845. self._write_string(
  846. '%s%s' % (self._bidi_workaround(message), ('' if skip_eol else '\n')),
  847. self._out_files.screen, only_once=only_once)
  848. def to_stderr(self, message, only_once=False):
  849. """Print message to stderr"""
  850. assert isinstance(message, str)
  851. if self.params.get('logger'):
  852. self.params['logger'].error(message)
  853. else:
  854. self._write_string(f'{self._bidi_workaround(message)}\n', self._out_files.error, only_once=only_once)
  855. def _send_console_code(self, code):
  856. if compat_os_name == 'nt' or not self._out_files.console:
  857. return
  858. self._write_string(code, self._out_files.console)
  859. def to_console_title(self, message):
  860. if not self.params.get('consoletitle', False):
  861. return
  862. message = remove_terminal_sequences(message)
  863. if compat_os_name == 'nt':
  864. if ctypes.windll.kernel32.GetConsoleWindow():
  865. # c_wchar_p() might not be necessary if `message` is
  866. # already of type unicode()
  867. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  868. else:
  869. self._send_console_code(f'\033]0;{message}\007')
  870. def save_console_title(self):
  871. if not self.params.get('consoletitle') or self.params.get('simulate'):
  872. return
  873. self._send_console_code('\033[22;0t') # Save the title on stack
  874. def restore_console_title(self):
  875. if not self.params.get('consoletitle') or self.params.get('simulate'):
  876. return
  877. self._send_console_code('\033[23;0t') # Restore the title from stack
  878. def __enter__(self):
  879. self.save_console_title()
  880. return self
  881. def save_cookies(self):
  882. if self.params.get('cookiefile') is not None:
  883. self.cookiejar.save(ignore_discard=True, ignore_expires=True)
  884. def __exit__(self, *args):
  885. self.restore_console_title()
  886. self.close()
  887. def close(self):
  888. self.save_cookies()
  889. self._request_director.close()
  890. def trouble(self, message=None, tb=None, is_error=True):
  891. """Determine action to take when a download problem appears.
  892. Depending on if the downloader has been configured to ignore
  893. download errors or not, this method may throw an exception or
  894. not when errors are found, after printing the message.
  895. @param tb If given, is additional traceback information
  896. @param is_error Whether to raise error according to ignorerrors
  897. """
  898. if message is not None:
  899. self.to_stderr(message)
  900. if self.params.get('verbose'):
  901. if tb is None:
  902. if sys.exc_info()[0]: # if .trouble has been called from an except block
  903. tb = ''
  904. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  905. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  906. tb += encode_compat_str(traceback.format_exc())
  907. else:
  908. tb_data = traceback.format_list(traceback.extract_stack())
  909. tb = ''.join(tb_data)
  910. if tb:
  911. self.to_stderr(tb)
  912. if not is_error:
  913. return
  914. if not self.params.get('ignoreerrors'):
  915. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  916. exc_info = sys.exc_info()[1].exc_info
  917. else:
  918. exc_info = sys.exc_info()
  919. raise DownloadError(message, exc_info)
  920. self._download_retcode = 1
  921. Styles = Namespace(
  922. HEADERS='yellow',
  923. EMPHASIS='light blue',
  924. FILENAME='green',
  925. ID='green',
  926. DELIM='blue',
  927. ERROR='red',
  928. BAD_FORMAT='light red',
  929. WARNING='yellow',
  930. SUPPRESS='light black',
  931. )
  932. def _format_text(self, handle, allow_colors, text, f, fallback=None, *, test_encoding=False):
  933. text = str(text)
  934. if test_encoding:
  935. original_text = text
  936. # handle.encoding can be None. See https://github.com/yt-dlp/yt-dlp/issues/2711
  937. encoding = self.params.get('encoding') or getattr(handle, 'encoding', None) or 'ascii'
  938. text = text.encode(encoding, 'ignore').decode(encoding)
  939. if fallback is not None and text != original_text:
  940. text = fallback
  941. return format_text(text, f) if allow_colors is True else text if fallback is None else fallback
  942. def _format_out(self, *args, **kwargs):
  943. return self._format_text(self._out_files.out, self._allow_colors.out, *args, **kwargs)
  944. def _format_screen(self, *args, **kwargs):
  945. return self._format_text(self._out_files.screen, self._allow_colors.screen, *args, **kwargs)
  946. def _format_err(self, *args, **kwargs):
  947. return self._format_text(self._out_files.error, self._allow_colors.error, *args, **kwargs)
  948. def report_warning(self, message, only_once=False):
  949. '''
  950. Print the message to stderr, it will be prefixed with 'WARNING:'
  951. If stderr is a tty file the 'WARNING:' will be colored
  952. '''
  953. if self.params.get('logger') is not None:
  954. self.params['logger'].warning(message)
  955. else:
  956. if self.params.get('no_warnings'):
  957. return
  958. self.to_stderr(f'{self._format_err("WARNING:", self.Styles.WARNING)} {message}', only_once)
  959. def deprecation_warning(self, message, *, stacklevel=0):
  960. deprecation_warning(
  961. message, stacklevel=stacklevel + 1, printer=self.report_error, is_error=False)
  962. def deprecated_feature(self, message):
  963. if self.params.get('logger') is not None:
  964. self.params['logger'].warning(f'Deprecated Feature: {message}')
  965. self.to_stderr(f'{self._format_err("Deprecated Feature:", self.Styles.ERROR)} {message}', True)
  966. def report_error(self, message, *args, **kwargs):
  967. '''
  968. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  969. in red if stderr is a tty file.
  970. '''
  971. self.trouble(f'{self._format_err("ERROR:", self.Styles.ERROR)} {message}', *args, **kwargs)
  972. def write_debug(self, message, only_once=False):
  973. '''Log debug message or Print message to stderr'''
  974. if not self.params.get('verbose', False):
  975. return
  976. message = f'[debug] {message}'
  977. if self.params.get('logger'):
  978. self.params['logger'].debug(message)
  979. else:
  980. self.to_stderr(message, only_once)
  981. def report_file_already_downloaded(self, file_name):
  982. """Report file has already been fully downloaded."""
  983. try:
  984. self.to_screen('[download] %s has already been downloaded' % file_name)
  985. except UnicodeEncodeError:
  986. self.to_screen('[download] The file has already been downloaded')
  987. def report_file_delete(self, file_name):
  988. """Report that existing file will be deleted."""
  989. try:
  990. self.to_screen('Deleting existing file %s' % file_name)
  991. except UnicodeEncodeError:
  992. self.to_screen('Deleting existing file')
  993. def raise_no_formats(self, info, forced=False, *, msg=None):
  994. has_drm = info.get('_has_drm')
  995. ignored, expected = self.params.get('ignore_no_formats_error'), bool(msg)
  996. msg = msg or has_drm and 'This video is DRM protected' or 'No video formats found!'
  997. if forced or not ignored:
  998. raise ExtractorError(msg, video_id=info['id'], ie=info['extractor'],
  999. expected=has_drm or ignored or expected)
  1000. else:
  1001. self.report_warning(msg)
  1002. def parse_outtmpl(self):
  1003. self.deprecation_warning('"YoutubeDL.parse_outtmpl" is deprecated and may be removed in a future version')
  1004. self._parse_outtmpl()
  1005. return self.params['outtmpl']
  1006. def _parse_outtmpl(self):
  1007. sanitize = IDENTITY
  1008. if self.params.get('restrictfilenames'): # Remove spaces in the default template
  1009. sanitize = lambda x: x.replace(' - ', ' ').replace(' ', '-')
  1010. outtmpl = self.params.setdefault('outtmpl', {})
  1011. if not isinstance(outtmpl, dict):
  1012. self.params['outtmpl'] = outtmpl = {'default': outtmpl}
  1013. outtmpl.update({k: sanitize(v) for k, v in DEFAULT_OUTTMPL.items() if outtmpl.get(k) is None})
  1014. def get_output_path(self, dir_type='', filename=None):
  1015. paths = self.params.get('paths', {})
  1016. assert isinstance(paths, dict), '"paths" parameter must be a dictionary'
  1017. path = os.path.join(
  1018. expand_path(paths.get('home', '').strip()),
  1019. expand_path(paths.get(dir_type, '').strip()) if dir_type else '',
  1020. filename or '')
  1021. return sanitize_path(path, force=self.params.get('windowsfilenames'))
  1022. @staticmethod
  1023. def _outtmpl_expandpath(outtmpl):
  1024. # expand_path translates '%%' into '%' and '$$' into '$'
  1025. # correspondingly that is not what we want since we need to keep
  1026. # '%%' intact for template dict substitution step. Working around
  1027. # with boundary-alike separator hack.
  1028. sep = ''.join(random.choices(string.ascii_letters, k=32))
  1029. outtmpl = outtmpl.replace('%%', f'%{sep}%').replace('$$', f'${sep}$')
  1030. # outtmpl should be expand_path'ed before template dict substitution
  1031. # because meta fields may contain env variables we don't want to
  1032. # be expanded. E.g. for outtmpl "%(title)s.%(ext)s" and
  1033. # title "Hello $PATH", we don't want `$PATH` to be expanded.
  1034. return expand_path(outtmpl).replace(sep, '')
  1035. @staticmethod
  1036. def escape_outtmpl(outtmpl):
  1037. ''' Escape any remaining strings like %s, %abc% etc. '''
  1038. return re.sub(
  1039. STR_FORMAT_RE_TMPL.format('', '(?![%(\0])'),
  1040. lambda mobj: ('' if mobj.group('has_key') else '%') + mobj.group(0),
  1041. outtmpl)
  1042. @classmethod
  1043. def validate_outtmpl(cls, outtmpl):
  1044. ''' @return None or Exception object '''
  1045. outtmpl = re.sub(
  1046. STR_FORMAT_RE_TMPL.format('[^)]*', '[ljhqBUDS]'),
  1047. lambda mobj: f'{mobj.group(0)[:-1]}s',
  1048. cls._outtmpl_expandpath(outtmpl))
  1049. try:
  1050. cls.escape_outtmpl(outtmpl) % collections.defaultdict(int)
  1051. return None
  1052. except ValueError as err:
  1053. return err
  1054. @staticmethod
  1055. def _copy_infodict(info_dict):
  1056. info_dict = dict(info_dict)
  1057. info_dict.pop('__postprocessors', None)
  1058. info_dict.pop('__pending_error', None)
  1059. return info_dict
  1060. def prepare_outtmpl(self, outtmpl, info_dict, sanitize=False):
  1061. """ Make the outtmpl and info_dict suitable for substitution: ydl.escape_outtmpl(outtmpl) % info_dict
  1062. @param sanitize Whether to sanitize the output as a filename.
  1063. For backward compatibility, a function can also be passed
  1064. """
  1065. info_dict.setdefault('epoch', int(time.time())) # keep epoch consistent once set
  1066. info_dict = self._copy_infodict(info_dict)
  1067. info_dict['duration_string'] = ( # %(duration>%H-%M-%S)s is wrong if duration > 24hrs
  1068. formatSeconds(info_dict['duration'], '-' if sanitize else ':')
  1069. if info_dict.get('duration', None) is not None
  1070. else None)
  1071. info_dict['autonumber'] = int(self.params.get('autonumber_start', 1) - 1 + self._num_downloads)
  1072. info_dict['video_autonumber'] = self._num_videos
  1073. if info_dict.get('resolution') is None:
  1074. info_dict['resolution'] = self.format_resolution(info_dict, default=None)
  1075. # For fields playlist_index, playlist_autonumber and autonumber convert all occurrences
  1076. # of %(field)s to %(field)0Nd for backward compatibility
  1077. field_size_compat_map = {
  1078. 'playlist_index': number_of_digits(info_dict.get('__last_playlist_index') or 0),
  1079. 'playlist_autonumber': number_of_digits(info_dict.get('n_entries') or 0),
  1080. 'autonumber': self.params.get('autonumber_size') or 5,
  1081. }
  1082. TMPL_DICT = {}
  1083. EXTERNAL_FORMAT_RE = re.compile(STR_FORMAT_RE_TMPL.format('[^)]*', f'[{STR_FORMAT_TYPES}ljhqBUDS]'))
  1084. MATH_FUNCTIONS = {
  1085. '+': float.__add__,
  1086. '-': float.__sub__,
  1087. }
  1088. # Field is of the form key1.key2...
  1089. # where keys (except first) can be string, int, slice or "{field, ...}"
  1090. FIELD_INNER_RE = r'(?:\w+|%(num)s|%(num)s?(?::%(num)s?){1,2})' % {'num': r'(?:-?\d+)'}
  1091. FIELD_RE = r'\w*(?:\.(?:%(inner)s|{%(field)s(?:,%(field)s)*}))*' % {
  1092. 'inner': FIELD_INNER_RE,
  1093. 'field': rf'\w*(?:\.{FIELD_INNER_RE})*'
  1094. }
  1095. MATH_FIELD_RE = rf'(?:{FIELD_RE}|-?{NUMBER_RE})'
  1096. MATH_OPERATORS_RE = r'(?:%s)' % '|'.join(map(re.escape, MATH_FUNCTIONS.keys()))
  1097. INTERNAL_FORMAT_RE = re.compile(rf'''(?xs)
  1098. (?P<negate>-)?
  1099. (?P<fields>{FIELD_RE})
  1100. (?P<maths>(?:{MATH_OPERATORS_RE}{MATH_FIELD_RE})*)
  1101. (?:>(?P<strf_format>.+?))?
  1102. (?P<remaining>
  1103. (?P<alternate>(?<!\\),[^|&)]+)?
  1104. (?:&(?P<replacement>.*?))?
  1105. (?:\|(?P<default>.*?))?
  1106. )$''')
  1107. def _traverse_infodict(fields):
  1108. fields = [f for x in re.split(r'\.({.+?})\.?', fields)
  1109. for f in ([x] if x.startswith('{') else x.split('.'))]
  1110. for i in (0, -1):
  1111. if fields and not fields[i]:
  1112. fields.pop(i)
  1113. for i, f in enumerate(fields):
  1114. if not f.startswith('{'):
  1115. continue
  1116. assert f.endswith('}'), f'No closing brace for {f} in {fields}'
  1117. fields[i] = {k: k.split('.') for k in f[1:-1].split(',')}
  1118. return traverse_obj(info_dict, fields, is_user_input=True, traverse_string=True)
  1119. def get_value(mdict):
  1120. # Object traversal
  1121. value = _traverse_infodict(mdict['fields'])
  1122. # Negative
  1123. if mdict['negate']:
  1124. value = float_or_none(value)
  1125. if value is not None:
  1126. value *= -1
  1127. # Do maths
  1128. offset_key = mdict['maths']
  1129. if offset_key:
  1130. value = float_or_none(value)
  1131. operator = None
  1132. while offset_key:
  1133. item = re.match(
  1134. MATH_FIELD_RE if operator else MATH_OPERATORS_RE,
  1135. offset_key).group(0)
  1136. offset_key = offset_key[len(item):]
  1137. if operator is None:
  1138. operator = MATH_FUNCTIONS[item]
  1139. continue
  1140. item, multiplier = (item[1:], -1) if item[0] == '-' else (item, 1)
  1141. offset = float_or_none(item)
  1142. if offset is None:
  1143. offset = float_or_none(_traverse_infodict(item))
  1144. try:
  1145. value = operator(value, multiplier * offset)
  1146. except (TypeError, ZeroDivisionError):
  1147. return None
  1148. operator = None
  1149. # Datetime formatting
  1150. if mdict['strf_format']:
  1151. value = strftime_or_none(value, mdict['strf_format'].replace('\\,', ','))
  1152. # XXX: Workaround for https://github.com/yt-dlp/yt-dlp/issues/4485
  1153. if sanitize and value == '':
  1154. value = None
  1155. return value
  1156. na = self.params.get('outtmpl_na_placeholder', 'NA')
  1157. def filename_sanitizer(key, value, restricted=self.params.get('restrictfilenames')):
  1158. return sanitize_filename(str(value), restricted=restricted, is_id=(
  1159. bool(re.search(r'(^|[_.])id(\.|$)', key))
  1160. if 'filename-sanitization' in self.params['compat_opts']
  1161. else NO_DEFAULT))
  1162. sanitizer = sanitize if callable(sanitize) else filename_sanitizer
  1163. sanitize = bool(sanitize)
  1164. def _dumpjson_default(obj):
  1165. if isinstance(obj, (set, LazyList)):
  1166. return list(obj)
  1167. return repr(obj)
  1168. class _ReplacementFormatter(string.Formatter):
  1169. def get_field(self, field_name, args, kwargs):
  1170. if field_name.isdigit():
  1171. return args[0], -1
  1172. raise ValueError('Unsupported field')
  1173. replacement_formatter = _ReplacementFormatter()
  1174. def create_key(outer_mobj):
  1175. if not outer_mobj.group('has_key'):
  1176. return outer_mobj.group(0)
  1177. key = outer_mobj.group('key')
  1178. mobj = re.match(INTERNAL_FORMAT_RE, key)
  1179. value, replacement, default, last_field = None, None, na, ''
  1180. while mobj:
  1181. mobj = mobj.groupdict()
  1182. default = mobj['default'] if mobj['default'] is not None else default
  1183. value = get_value(mobj)
  1184. last_field, replacement = mobj['fields'], mobj['replacement']
  1185. if value is None and mobj['alternate']:
  1186. mobj = re.match(INTERNAL_FORMAT_RE, mobj['remaining'][1:])
  1187. else:
  1188. break
  1189. fmt = outer_mobj.group('format')
  1190. if fmt == 's' and value is not None and last_field in field_size_compat_map.keys():
  1191. fmt = f'0{field_size_compat_map[last_field]:d}d'
  1192. if None not in (value, replacement):
  1193. try:
  1194. value = replacement_formatter.format(replacement, value)
  1195. except ValueError:
  1196. value, default = None, na
  1197. flags = outer_mobj.group('conversion') or ''
  1198. str_fmt = f'{fmt[:-1]}s'
  1199. if value is None:
  1200. value, fmt = default, 's'
  1201. elif fmt[-1] == 'l': # list
  1202. delim = '\n' if '#' in flags else ', '
  1203. value, fmt = delim.join(map(str, variadic(value, allowed_types=(str, bytes)))), str_fmt
  1204. elif fmt[-1] == 'j': # json
  1205. value, fmt = json.dumps(
  1206. value, default=_dumpjson_default,
  1207. indent=4 if '#' in flags else None, ensure_ascii='+' not in flags), str_fmt
  1208. elif fmt[-1] == 'h': # html
  1209. value, fmt = escapeHTML(str(value)), str_fmt
  1210. elif fmt[-1] == 'q': # quoted
  1211. value = map(str, variadic(value) if '#' in flags else [value])
  1212. value, fmt = ' '.join(map(compat_shlex_quote, value)), str_fmt
  1213. elif fmt[-1] == 'B': # bytes
  1214. value = f'%{str_fmt}'.encode() % str(value).encode()
  1215. value, fmt = value.decode('utf-8', 'ignore'), 's'
  1216. elif fmt[-1] == 'U': # unicode normalized
  1217. value, fmt = unicodedata.normalize(
  1218. # "+" = compatibility equivalence, "#" = NFD
  1219. 'NF%s%s' % ('K' if '+' in flags else '', 'D' if '#' in flags else 'C'),
  1220. value), str_fmt
  1221. elif fmt[-1] == 'D': # decimal suffix
  1222. num_fmt, fmt = fmt[:-1].replace('#', ''), 's'
  1223. value = format_decimal_suffix(value, f'%{num_fmt}f%s' if num_fmt else '%d%s',
  1224. factor=1024 if '#' in flags else 1000)
  1225. elif fmt[-1] == 'S': # filename sanitization
  1226. value, fmt = filename_sanitizer(last_field, value, restricted='#' in flags), str_fmt
  1227. elif fmt[-1] == 'c':
  1228. if value:
  1229. value = str(value)[0]
  1230. else:
  1231. fmt = str_fmt
  1232. elif fmt[-1] not in 'rsa': # numeric
  1233. value = float_or_none(value)
  1234. if value is None:
  1235. value, fmt = default, 's'
  1236. if sanitize:
  1237. # If value is an object, sanitize might convert it to a string
  1238. # So we convert it to repr first
  1239. if fmt[-1] == 'r':
  1240. value, fmt = repr(value), str_fmt
  1241. elif fmt[-1] == 'a':
  1242. value, fmt = ascii(value), str_fmt
  1243. if fmt[-1] in 'csra':
  1244. value = sanitizer(last_field, value)
  1245. key = '%s\0%s' % (key.replace('%', '%\0'), outer_mobj.group('format'))
  1246. TMPL_DICT[key] = value
  1247. return '{prefix}%({key}){fmt}'.format(key=key, fmt=fmt, prefix=outer_mobj.group('prefix'))
  1248. return EXTERNAL_FORMAT_RE.sub(create_key, outtmpl), TMPL_DICT
  1249. def evaluate_outtmpl(self, outtmpl, info_dict, *args, **kwargs):
  1250. outtmpl, info_dict = self.prepare_outtmpl(outtmpl, info_dict, *args, **kwargs)
  1251. return self.escape_outtmpl(outtmpl) % info_dict
  1252. def _prepare_filename(self, info_dict, *, outtmpl=None, tmpl_type=None):
  1253. assert None in (outtmpl, tmpl_type), 'outtmpl and tmpl_type are mutually exclusive'
  1254. if outtmpl is None:
  1255. outtmpl = self.params['outtmpl'].get(tmpl_type or 'default', self.params['outtmpl']['default'])
  1256. try:
  1257. outtmpl = self._outtmpl_expandpath(outtmpl)
  1258. filename = self.evaluate_outtmpl(outtmpl, info_dict, True)
  1259. if not filename:
  1260. return None
  1261. if tmpl_type in ('', 'temp'):
  1262. final_ext, ext = self.params.get('final_ext'), info_dict.get('ext')
  1263. if final_ext and ext and final_ext != ext and filename.endswith(f'.{final_ext}'):
  1264. filename = replace_extension(filename, ext, final_ext)
  1265. elif tmpl_type:
  1266. force_ext = OUTTMPL_TYPES[tmpl_type]
  1267. if force_ext:
  1268. filename = replace_extension(filename, force_ext, info_dict.get('ext'))
  1269. # https://github.com/blackjack4494/youtube-dlc/issues/85
  1270. trim_file_name = self.params.get('trim_file_name', False)
  1271. if trim_file_name:
  1272. no_ext, *ext = filename.rsplit('.', 2)
  1273. filename = join_nonempty(no_ext[:trim_file_name], *ext, delim='.')
  1274. return filename
  1275. except ValueError as err:
  1276. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  1277. return None
  1278. def prepare_filename(self, info_dict, dir_type='', *, outtmpl=None, warn=False):
  1279. """Generate the output filename"""
  1280. if outtmpl:
  1281. assert not dir_type, 'outtmpl and dir_type are mutually exclusive'
  1282. dir_type = None
  1283. filename = self._prepare_filename(info_dict, tmpl_type=dir_type, outtmpl=outtmpl)
  1284. if not filename and dir_type not in ('', 'temp'):
  1285. return ''
  1286. if warn:
  1287. if not self.params.get('paths'):
  1288. pass
  1289. elif filename == '-':
  1290. self.report_warning('--paths is ignored when an outputting to stdout', only_once=True)
  1291. elif os.path.isabs(filename):
  1292. self.report_warning('--paths is ignored since an absolute path is given in output template', only_once=True)
  1293. if filename == '-' or not filename:
  1294. return filename
  1295. return self.get_output_path(dir_type, filename)
  1296. def _match_entry(self, info_dict, incomplete=False, silent=False):
  1297. """Returns None if the file should be downloaded"""
  1298. _type = 'video' if 'playlist-match-filter' in self.params['compat_opts'] else info_dict.get('_type', 'video')
  1299. assert incomplete or _type == 'video', 'Only video result can be considered complete'
  1300. video_title = info_dict.get('title', info_dict.get('id', 'entry'))
  1301. def check_filter():
  1302. if _type in ('playlist', 'multi_video'):
  1303. return
  1304. elif _type in ('url', 'url_transparent') and not try_call(
  1305. lambda: self.get_info_extractor(info_dict['ie_key']).is_single_video(info_dict['url'])):
  1306. return
  1307. if 'title' in info_dict:
  1308. # This can happen when we're just evaluating the playlist
  1309. title = info_dict['title']
  1310. matchtitle = self.params.get('matchtitle', False)
  1311. if matchtitle:
  1312. if not re.search(matchtitle, title, re.IGNORECASE):
  1313. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  1314. rejecttitle = self.params.get('rejecttitle', False)
  1315. if rejecttitle:
  1316. if re.search(rejecttitle, title, re.IGNORECASE):
  1317. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  1318. date = info_dict.get('upload_date')
  1319. if date is not None:
  1320. dateRange = self.params.get('daterange', DateRange())
  1321. if date not in dateRange:
  1322. return f'{date_from_str(date).isoformat()} upload date is not in range {dateRange}'
  1323. view_count = info_dict.get('view_count')
  1324. if view_count is not None:
  1325. min_views = self.params.get('min_views')
  1326. if min_views is not None and view_count < min_views:
  1327. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  1328. max_views = self.params.get('max_views')
  1329. if max_views is not None and view_count > max_views:
  1330. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  1331. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  1332. return 'Skipping "%s" because it is age restricted' % video_title
  1333. match_filter = self.params.get('match_filter')
  1334. if match_filter is None:
  1335. return None
  1336. cancelled = None
  1337. try:
  1338. try:
  1339. ret = match_filter(info_dict, incomplete=incomplete)
  1340. except TypeError:
  1341. # For backward compatibility
  1342. ret = None if incomplete else match_filter(info_dict)
  1343. except DownloadCancelled as err:
  1344. if err.msg is not NO_DEFAULT:
  1345. raise
  1346. ret, cancelled = err.msg, err
  1347. if ret is NO_DEFAULT:
  1348. while True:
  1349. filename = self._format_screen(self.prepare_filename(info_dict), self.Styles.FILENAME)
  1350. reply = input(self._format_screen(
  1351. f'Download "{filename}"? (Y/n): ', self.Styles.EMPHASIS)).lower().strip()
  1352. if reply in {'y', ''}:
  1353. return None
  1354. elif reply == 'n':
  1355. if cancelled:
  1356. raise type(cancelled)(f'Skipping {video_title}')
  1357. return f'Skipping {video_title}'
  1358. return ret
  1359. if self.in_download_archive(info_dict):
  1360. reason = ''.join((
  1361. format_field(info_dict, 'id', f'{self._format_screen("%s", self.Styles.ID)}: '),
  1362. format_field(info_dict, 'title', f'{self._format_screen("%s", self.Styles.EMPHASIS)} '),
  1363. 'has already been recorded in the archive'))
  1364. break_opt, break_err = 'break_on_existing', ExistingVideoReached
  1365. else:
  1366. try:
  1367. reason = check_filter()
  1368. except DownloadCancelled as e:
  1369. reason, break_opt, break_err = e.msg, 'match_filter', type(e)
  1370. else:
  1371. break_opt, break_err = 'break_on_reject', RejectedVideoReached
  1372. if reason is not None:
  1373. if not silent:
  1374. self.to_screen('[download] ' + reason)
  1375. if self.params.get(break_opt, False):
  1376. raise break_err()
  1377. return reason
  1378. @staticmethod
  1379. def add_extra_info(info_dict, extra_info):
  1380. '''Set the keys from extra_info in info dict if they are missing'''
  1381. for key, value in extra_info.items():
  1382. info_dict.setdefault(key, value)
  1383. def extract_info(self, url, download=True, ie_key=None, extra_info=None,
  1384. process=True, force_generic_extractor=False):
  1385. """
  1386. Extract and return the information dictionary of the URL
  1387. Arguments:
  1388. @param url URL to extract
  1389. Keyword arguments:
  1390. @param download Whether to download videos
  1391. @param process Whether to resolve all unresolved references (URLs, playlist items).
  1392. Must be True for download to work
  1393. @param ie_key Use only the extractor with this key
  1394. @param extra_info Dictionary containing the extra values to add to the info (For internal use only)
  1395. @force_generic_extractor Force using the generic extractor (Deprecated; use ie_key='Generic')
  1396. """
  1397. if extra_info is None:
  1398. extra_info = {}
  1399. if not ie_key and force_generic_extractor:
  1400. ie_key = 'Generic'
  1401. if ie_key:
  1402. ies = {ie_key: self._ies[ie_key]} if ie_key in self._ies else {}
  1403. else:
  1404. ies = self._ies
  1405. for key, ie in ies.items():
  1406. if not ie.suitable(url):
  1407. continue
  1408. if not ie.working():
  1409. self.report_warning('The program functionality for this site has been marked as broken, '
  1410. 'and will probably not work.')
  1411. temp_id = ie.get_temp_id(url)
  1412. if temp_id is not None and self.in_download_archive({'id': temp_id, 'ie_key': key}):
  1413. self.to_screen(f'[download] {self._format_screen(temp_id, self.Styles.ID)}: '
  1414. 'has already been recorded in the archive')
  1415. if self.params.get('break_on_existing', False):
  1416. raise ExistingVideoReached()
  1417. break
  1418. return self.__extract_info(url, self.get_info_extractor(key), download, extra_info, process)
  1419. else:
  1420. extractors_restricted = self.params.get('allowed_extractors') not in (None, ['default'])
  1421. self.report_error(f'No suitable extractor{format_field(ie_key, None, " (%s)")} found for URL {url}',
  1422. tb=False if extractors_restricted else None)
  1423. def _handle_extraction_exceptions(func):
  1424. @functools.wraps(func)
  1425. def wrapper(self, *args, **kwargs):
  1426. while True:
  1427. try:
  1428. return func(self, *args, **kwargs)
  1429. except (DownloadCancelled, LazyList.IndexError, PagedList.IndexError):
  1430. raise
  1431. except ReExtractInfo as e:
  1432. if e.expected:
  1433. self.to_screen(f'{e}; Re-extracting data')
  1434. else:
  1435. self.to_stderr('\r')
  1436. self.report_warning(f'{e}; Re-extracting data')
  1437. continue
  1438. except GeoRestrictedError as e:
  1439. msg = e.msg
  1440. if e.countries:
  1441. msg += '\nThis video is available in %s.' % ', '.join(
  1442. map(ISO3166Utils.short2full, e.countries))
  1443. msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
  1444. self.report_error(msg)
  1445. except ExtractorError as e: # An error we somewhat expected
  1446. self.report_error(str(e), e.format_traceback())
  1447. except Exception as e:
  1448. if self.params.get('ignoreerrors'):
  1449. self.report_error(str(e), tb=encode_compat_str(traceback.format_exc()))
  1450. else:
  1451. raise
  1452. break
  1453. return wrapper
  1454. def _wait_for_video(self, ie_result={}):
  1455. if (not self.params.get('wait_for_video')
  1456. or ie_result.get('_type', 'video') != 'video'
  1457. or ie_result.get('formats') or ie_result.get('url')):
  1458. return
  1459. format_dur = lambda dur: '%02d:%02d:%02d' % timetuple_from_msec(dur * 1000)[:-1]
  1460. last_msg = ''
  1461. def progress(msg):
  1462. nonlocal last_msg
  1463. full_msg = f'{msg}\n'
  1464. if not self.params.get('noprogress'):
  1465. full_msg = msg + ' ' * (len(last_msg) - len(msg)) + '\r'
  1466. elif last_msg:
  1467. return
  1468. self.to_screen(full_msg, skip_eol=True)
  1469. last_msg = msg
  1470. min_wait, max_wait = self.params.get('wait_for_video')
  1471. diff = try_get(ie_result, lambda x: x['release_timestamp'] - time.time())
  1472. if diff is None and ie_result.get('live_status') == 'is_upcoming':
  1473. diff = round(random.uniform(min_wait, max_wait) if (max_wait and min_wait) else (max_wait or min_wait), 0)
  1474. self.report_warning('Release time of video is not known')
  1475. elif ie_result and (diff or 0) <= 0:
  1476. self.report_warning('Video should already be available according to extracted info')
  1477. diff = min(max(diff or 0, min_wait or 0), max_wait or float('inf'))
  1478. self.to_screen(f'[wait] Waiting for {format_dur(diff)} - Press Ctrl+C to try now')
  1479. wait_till = time.time() + diff
  1480. try:
  1481. while True:
  1482. diff = wait_till - time.time()
  1483. if diff <= 0:
  1484. progress('')
  1485. raise ReExtractInfo('[wait] Wait period ended', expected=True)
  1486. progress(f'[wait] Remaining time until next attempt: {self._format_screen(format_dur(diff), self.Styles.EMPHASIS)}')
  1487. time.sleep(1)
  1488. except KeyboardInterrupt:
  1489. progress('')
  1490. raise ReExtractInfo('[wait] Interrupted by user', expected=True)
  1491. except BaseException as e:
  1492. if not isinstance(e, ReExtractInfo):
  1493. self.to_screen('')
  1494. raise
  1495. def _load_cookies(self, data, *, autoscope=True):
  1496. """Loads cookies from a `Cookie` header
  1497. This tries to work around the security vulnerability of passing cookies to every domain.
  1498. See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj
  1499. @param data The Cookie header as string to load the cookies from
  1500. @param autoscope If `False`, scope cookies using Set-Cookie syntax and error for cookie without domains
  1501. If `True`, save cookies for later to be stored in the jar with a limited scope
  1502. If a URL, save cookies in the jar with the domain of the URL
  1503. """
  1504. for cookie in LenientSimpleCookie(data).values():
  1505. if autoscope and any(cookie.values()):
  1506. raise ValueError('Invalid syntax in Cookie Header')
  1507. domain = cookie.get('domain') or ''
  1508. expiry = cookie.get('expires')
  1509. if expiry == '': # 0 is valid
  1510. expiry = None
  1511. prepared_cookie = http.cookiejar.Cookie(
  1512. cookie.get('version') or 0, cookie.key, cookie.value, None, False,
  1513. domain, True, True, cookie.get('path') or '', bool(cookie.get('path')),
  1514. cookie.get('secure') or False, expiry, False, None, None, {})
  1515. if domain:
  1516. self.cookiejar.set_cookie(prepared_cookie)
  1517. elif autoscope is True:
  1518. self.deprecated_feature(
  1519. 'Passing cookies as a header is a potential security risk; '
  1520. 'they will be scoped to the domain of the downloaded urls. '
  1521. 'Please consider loading cookies from a file or browser instead.')
  1522. self.__header_cookies.append(prepared_cookie)
  1523. elif autoscope:
  1524. self.report_warning(
  1525. 'The extractor result contains an unscoped cookie as an HTTP header. '
  1526. f'If you are using yt-dlp with an input URL{bug_reports_message(before=",")}',
  1527. only_once=True)
  1528. self._apply_header_cookies(autoscope, [prepared_cookie])
  1529. else:
  1530. self.report_error('Unscoped cookies are not allowed; please specify some sort of scoping',
  1531. tb=False, is_error=False)
  1532. def _apply_header_cookies(self, url, cookies=None):
  1533. """Applies stray header cookies to the provided url
  1534. This loads header cookies and scopes them to the domain provided in `url`.
  1535. While this is not ideal, it helps reduce the risk of them being sent
  1536. to an unintended destination while mostly maintaining compatibility.
  1537. """
  1538. parsed = urllib.parse.urlparse(url)
  1539. if not parsed.hostname:
  1540. return
  1541. for cookie in map(copy.copy, cookies or self.__header_cookies):
  1542. cookie.domain = f'.{parsed.hostname}'
  1543. self.cookiejar.set_cookie(cookie)
  1544. @_handle_extraction_exceptions
  1545. def __extract_info(self, url, ie, download, extra_info, process):
  1546. self._apply_header_cookies(url)
  1547. try:
  1548. ie_result = ie.extract(url)
  1549. except UserNotLive as e:
  1550. if process:
  1551. if self.params.get('wait_for_video'):
  1552. self.report_warning(e)
  1553. self._wait_for_video()
  1554. raise
  1555. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  1556. self.report_warning(f'Extractor {ie.IE_NAME} returned nothing{bug_reports_message()}')
  1557. return
  1558. if isinstance(ie_result, list):
  1559. # Backwards compatibility: old IE result format
  1560. ie_result = {
  1561. '_type': 'compat_list',
  1562. 'entries': ie_result,
  1563. }
  1564. if extra_info.get('original_url'):
  1565. ie_result.setdefault('original_url', extra_info['original_url'])
  1566. self.add_default_extra_info(ie_result, ie, url)
  1567. if process:
  1568. self._wait_for_video(ie_result)
  1569. return self.process_ie_result(ie_result, download, extra_info)
  1570. else:
  1571. return ie_result
  1572. def add_default_extra_info(self, ie_result, ie, url):
  1573. if url is not None:
  1574. self.add_extra_info(ie_result, {
  1575. 'webpage_url': url,
  1576. 'original_url': url,
  1577. })
  1578. webpage_url = ie_result.get('webpage_url')
  1579. if webpage_url:
  1580. self.add_extra_info(ie_result, {
  1581. 'webpage_url_basename': url_basename(webpage_url),
  1582. 'webpage_url_domain': get_domain(webpage_url),
  1583. })
  1584. if ie is not None:
  1585. self.add_extra_info(ie_result, {
  1586. 'extractor': ie.IE_NAME,
  1587. 'extractor_key': ie.ie_key(),
  1588. })
  1589. def process_ie_result(self, ie_result, download=True, extra_info=None):
  1590. """
  1591. Take the result of the ie(may be modified) and resolve all unresolved
  1592. references (URLs, playlist items).
  1593. It will also download the videos if 'download'.
  1594. Returns the resolved ie_result.
  1595. """
  1596. if extra_info is None:
  1597. extra_info = {}
  1598. result_type = ie_result.get('_type', 'video')
  1599. if result_type in ('url', 'url_transparent'):
  1600. ie_result['url'] = sanitize_url(
  1601. ie_result['url'], scheme='http' if self.params.get('prefer_insecure') else 'https')
  1602. if ie_result.get('original_url') and not extra_info.get('original_url'):
  1603. extra_info = {'original_url': ie_result['original_url'], **extra_info}
  1604. extract_flat = self.params.get('extract_flat', False)
  1605. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
  1606. or extract_flat is True):
  1607. info_copy = ie_result.copy()
  1608. ie = try_get(ie_result.get('ie_key'), self.get_info_extractor)
  1609. if ie and not ie_result.get('id'):
  1610. info_copy['id'] = ie.get_temp_id(ie_result['url'])
  1611. self.add_default_extra_info(info_copy, ie, ie_result['url'])
  1612. self.add_extra_info(info_copy, extra_info)
  1613. info_copy, _ = self.pre_process(info_copy)
  1614. self._fill_common_fields(info_copy, False)
  1615. self.__forced_printings(info_copy)
  1616. self._raise_pending_errors(info_copy)
  1617. if self.params.get('force_write_download_archive', False):
  1618. self.record_download_archive(info_copy)
  1619. return ie_result
  1620. if result_type == 'video':
  1621. self.add_extra_info(ie_result, extra_info)
  1622. ie_result = self.process_video_result(ie_result, download=download)
  1623. self._raise_pending_errors(ie_result)
  1624. additional_urls = (ie_result or {}).get('additional_urls')
  1625. if additional_urls:
  1626. # TODO: Improve MetadataParserPP to allow setting a list
  1627. if isinstance(additional_urls, str):
  1628. additional_urls = [additional_urls]
  1629. self.to_screen(
  1630. '[info] %s: %d additional URL(s) requested' % (ie_result['id'], len(additional_urls)))
  1631. self.write_debug('Additional URLs: "%s"' % '", "'.join(additional_urls))
  1632. ie_result['additional_entries'] = [
  1633. self.extract_info(
  1634. url, download, extra_info=extra_info,
  1635. force_generic_extractor=self.params.get('force_generic_extractor'))
  1636. for url in additional_urls
  1637. ]
  1638. return ie_result
  1639. elif result_type == 'url':
  1640. # We have to add extra_info to the results because it may be
  1641. # contained in a playlist
  1642. return self.extract_info(
  1643. ie_result['url'], download,
  1644. ie_key=ie_result.get('ie_key'),
  1645. extra_info=extra_info)
  1646. elif result_type == 'url_transparent':
  1647. # Use the information from the embedding page
  1648. info = self.extract_info(
  1649. ie_result['url'], ie_key=ie_result.get('ie_key'),
  1650. extra_info=extra_info, download=False, process=False)
  1651. # extract_info may return None when ignoreerrors is enabled and
  1652. # extraction failed with an error, don't crash and return early
  1653. # in this case
  1654. if not info:
  1655. return info
  1656. exempted_fields = {'_type', 'url', 'ie_key'}
  1657. if not ie_result.get('section_end') and ie_result.get('section_start') is None:
  1658. # For video clips, the id etc of the clip extractor should be used
  1659. exempted_fields |= {'id', 'extractor', 'extractor_key'}
  1660. new_result = info.copy()
  1661. new_result.update(filter_dict(ie_result, lambda k, v: v is not None and k not in exempted_fields))
  1662. # Extracted info may not be a video result (i.e.
  1663. # info.get('_type', 'video') != video) but rather an url or
  1664. # url_transparent. In such cases outer metadata (from ie_result)
  1665. # should be propagated to inner one (info). For this to happen
  1666. # _type of info should be overridden with url_transparent. This
  1667. # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
  1668. if new_result.get('_type') == 'url':
  1669. new_result['_type'] = 'url_transparent'
  1670. return self.process_ie_result(
  1671. new_result, download=download, extra_info=extra_info)
  1672. elif result_type in ('playlist', 'multi_video'):
  1673. # Protect from infinite recursion due to recursively nested playlists
  1674. # (see https://github.com/ytdl-org/youtube-dl/issues/27833)
  1675. webpage_url = ie_result.get('webpage_url') # Playlists maynot have webpage_url
  1676. if webpage_url and webpage_url in self._playlist_urls:
  1677. self.to_screen(
  1678. '[download] Skipping already downloaded playlist: %s'
  1679. % ie_result.get('title') or ie_result.get('id'))
  1680. return
  1681. self._playlist_level += 1
  1682. self._playlist_urls.add(webpage_url)
  1683. self._fill_common_fields(ie_result, False)
  1684. self._sanitize_thumbnails(ie_result)
  1685. try:
  1686. return self.__process_playlist(ie_result, download)
  1687. finally:
  1688. self._playlist_level -= 1
  1689. if not self._playlist_level:
  1690. self._playlist_urls.clear()
  1691. elif result_type == 'compat_list':
  1692. self.report_warning(
  1693. 'Extractor %s returned a compat_list result. '
  1694. 'It needs to be updated.' % ie_result.get('extractor'))
  1695. def _fixup(r):
  1696. self.add_extra_info(r, {
  1697. 'extractor': ie_result['extractor'],
  1698. 'webpage_url': ie_result['webpage_url'],
  1699. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  1700. 'webpage_url_domain': get_domain(ie_result['webpage_url']),
  1701. 'extractor_key': ie_result['extractor_key'],
  1702. })
  1703. return r
  1704. ie_result['entries'] = [
  1705. self.process_ie_result(_fixup(r), download, extra_info)
  1706. for r in ie_result['entries']
  1707. ]
  1708. return ie_result
  1709. else:
  1710. raise Exception('Invalid result type: %s' % result_type)
  1711. def _ensure_dir_exists(self, path):
  1712. return make_dir(path, self.report_error)
  1713. @staticmethod
  1714. def _playlist_infodict(ie_result, strict=False, **kwargs):
  1715. info = {
  1716. 'playlist_count': ie_result.get('playlist_count'),
  1717. 'playlist': ie_result.get('title') or ie_result.get('id'),
  1718. 'playlist_id': ie_result.get('id'),
  1719. 'playlist_title': ie_result.get('title'),
  1720. 'playlist_uploader': ie_result.get('uploader'),
  1721. 'playlist_uploader_id': ie_result.get('uploader_id'),
  1722. **kwargs,
  1723. }
  1724. if strict:
  1725. return info
  1726. if ie_result.get('webpage_url'):
  1727. info.update({
  1728. 'webpage_url': ie_result['webpage_url'],
  1729. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  1730. 'webpage_url_domain': get_domain(ie_result['webpage_url']),
  1731. })
  1732. return {
  1733. **info,
  1734. 'playlist_index': 0,
  1735. '__last_playlist_index': max(ie_result.get('requested_entries') or (0, 0)),
  1736. 'extractor': ie_result['extractor'],
  1737. 'extractor_key': ie_result['extractor_key'],
  1738. }
  1739. def __process_playlist(self, ie_result, download):
  1740. """Process each entry in the playlist"""
  1741. assert ie_result['_type'] in ('playlist', 'multi_video')
  1742. common_info = self._playlist_infodict(ie_result, strict=True)
  1743. title = common_info.get('playlist') or '<Untitled>'
  1744. if self._match_entry(common_info, incomplete=True) is not None:
  1745. return
  1746. self.to_screen(f'[download] Downloading {ie_result["_type"]}: {title}')
  1747. all_entries = PlaylistEntries(self, ie_result)
  1748. entries = orderedSet(all_entries.get_requested_items(), lazy=True)
  1749. lazy = self.params.get('lazy_playlist')
  1750. if lazy:
  1751. resolved_entries, n_entries = [], 'N/A'
  1752. ie_result['requested_entries'], ie_result['entries'] = None, None
  1753. else:
  1754. entries = resolved_entries = list(entries)
  1755. n_entries = len(resolved_entries)
  1756. ie_result['requested_entries'], ie_result['entries'] = tuple(zip(*resolved_entries)) or ([], [])
  1757. if not ie_result.get('playlist_count'):
  1758. # Better to do this after potentially exhausting entries
  1759. ie_result['playlist_count'] = all_entries.get_full_count()
  1760. extra = self._playlist_infodict(ie_result, n_entries=int_or_none(n_entries))
  1761. ie_copy = collections.ChainMap(ie_result, extra)
  1762. _infojson_written = False
  1763. write_playlist_files = self.params.get('allow_playlist_files', True)
  1764. if write_playlist_files and self.params.get('list_thumbnails'):
  1765. self.list_thumbnails(ie_result)
  1766. if write_playlist_files and not self.params.get('simulate'):
  1767. _infojson_written = self._write_info_json(
  1768. 'playlist', ie_result, self.prepare_filename(ie_copy, 'pl_infojson'))
  1769. if _infojson_written is None:
  1770. return
  1771. if self._write_description('playlist', ie_result,
  1772. self.prepare_filename(ie_copy, 'pl_description')) is None:
  1773. return
  1774. # TODO: This should be passed to ThumbnailsConvertor if necessary
  1775. self._write_thumbnails('playlist', ie_result, self.prepare_filename(ie_copy, 'pl_thumbnail'))
  1776. if lazy:
  1777. if self.params.get('playlistreverse') or self.params.get('playlistrandom'):
  1778. self.report_warning('playlistreverse and playlistrandom are not supported with lazy_playlist', only_once=True)
  1779. elif self.params.get('playlistreverse'):
  1780. entries.reverse()
  1781. elif self.params.get('playlistrandom'):
  1782. random.shuffle(entries)
  1783. self.to_screen(f'[{ie_result["extractor"]}] Playlist {title}: Downloading {n_entries} items'
  1784. f'{format_field(ie_result, "playlist_count", " of %s")}')
  1785. keep_resolved_entries = self.params.get('extract_flat') != 'discard'
  1786. if self.params.get('extract_flat') == 'discard_in_playlist':
  1787. keep_resolved_entries = ie_result['_type'] != 'playlist'
  1788. if keep_resolved_entries:
  1789. self.write_debug('The information of all playlist entries will be held in memory')
  1790. failures = 0
  1791. max_failures = self.params.get('skip_playlist_after_errors') or float('inf')
  1792. for i, (playlist_index, entry) in enumerate(entries):
  1793. if lazy:
  1794. resolved_entries.append((playlist_index, entry))
  1795. if not entry:
  1796. continue
  1797. entry['__x_forwarded_for_ip'] = ie_result.get('__x_forwarded_for_ip')
  1798. if not lazy and 'playlist-index' in self.params['compat_opts']:
  1799. playlist_index = ie_result['requested_entries'][i]
  1800. entry_copy = collections.ChainMap(entry, {
  1801. **common_info,
  1802. 'n_entries': int_or_none(n_entries),
  1803. 'playlist_index': playlist_index,
  1804. 'playlist_autonumber': i + 1,
  1805. })
  1806. if self._match_entry(entry_copy, incomplete=True) is not None:
  1807. # For compatabilty with youtube-dl. See https://github.com/yt-dlp/yt-dlp/issues/4369
  1808. resolved_entries[i] = (playlist_index, NO_DEFAULT)
  1809. continue
  1810. self.to_screen('[download] Downloading item %s of %s' % (
  1811. self._format_screen(i + 1, self.Styles.ID), self._format_screen(n_entries, self.Styles.EMPHASIS)))
  1812. entry_result = self.__process_iterable_entry(entry, download, collections.ChainMap({
  1813. 'playlist_index': playlist_index,
  1814. 'playlist_autonumber': i + 1,
  1815. }, extra))
  1816. if not entry_result:
  1817. failures += 1
  1818. if failures >= max_failures:
  1819. self.report_error(
  1820. f'Skipping the remaining entries in playlist "{title}" since {failures} items failed extraction')
  1821. break
  1822. if keep_resolved_entries:
  1823. resolved_entries[i] = (playlist_index, entry_result)
  1824. # Update with processed data
  1825. ie_result['entries'] = [e for _, e in resolved_entries if e is not NO_DEFAULT]
  1826. ie_result['requested_entries'] = [i for i, e in resolved_entries if e is not NO_DEFAULT]
  1827. if ie_result['requested_entries'] == try_call(lambda: list(range(1, ie_result['playlist_count'] + 1))):
  1828. # Do not set for full playlist
  1829. ie_result.pop('requested_entries')
  1830. # Write the updated info to json
  1831. if _infojson_written is True and self._write_info_json(
  1832. 'updated playlist', ie_result,
  1833. self.prepare_filename(ie_copy, 'pl_infojson'), overwrite=True) is None:
  1834. return
  1835. ie_result = self.run_all_pps('playlist', ie_result)
  1836. self.to_screen(f'[download] Finished downloading playlist: {title}')
  1837. return ie_result
  1838. @_handle_extraction_exceptions
  1839. def __process_iterable_entry(self, entry, download, extra_info):
  1840. return self.process_ie_result(
  1841. entry, download=download, extra_info=extra_info)
  1842. def _build_format_filter(self, filter_spec):
  1843. " Returns a function to filter the formats according to the filter_spec "
  1844. OPERATORS = {
  1845. '<': operator.lt,
  1846. '<=': operator.le,
  1847. '>': operator.gt,
  1848. '>=': operator.ge,
  1849. '=': operator.eq,
  1850. '!=': operator.ne,
  1851. }
  1852. operator_rex = re.compile(r'''(?x)\s*
  1853. (?P<key>[\w.-]+)\s*
  1854. (?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1855. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)\s*
  1856. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  1857. m = operator_rex.fullmatch(filter_spec)
  1858. if m:
  1859. try:
  1860. comparison_value = int(m.group('value'))
  1861. except ValueError:
  1862. comparison_value = parse_filesize(m.group('value'))
  1863. if comparison_value is None:
  1864. comparison_value = parse_filesize(m.group('value') + 'B')
  1865. if comparison_value is None:
  1866. raise ValueError(
  1867. 'Invalid value %r in format specification %r' % (
  1868. m.group('value'), filter_spec))
  1869. op = OPERATORS[m.group('op')]
  1870. if not m:
  1871. STR_OPERATORS = {
  1872. '=': operator.eq,
  1873. '^=': lambda attr, value: attr.startswith(value),
  1874. '$=': lambda attr, value: attr.endswith(value),
  1875. '*=': lambda attr, value: value in attr,
  1876. '~=': lambda attr, value: value.search(attr) is not None
  1877. }
  1878. str_operator_rex = re.compile(r'''(?x)\s*
  1879. (?P<key>[a-zA-Z0-9._-]+)\s*
  1880. (?P<negation>!\s*)?(?P<op>%s)\s*(?P<none_inclusive>\?\s*)?
  1881. (?P<quote>["'])?
  1882. (?P<value>(?(quote)(?:(?!(?P=quote))[^\\]|\\.)+|[\w.-]+))
  1883. (?(quote)(?P=quote))\s*
  1884. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  1885. m = str_operator_rex.fullmatch(filter_spec)
  1886. if m:
  1887. if m.group('op') == '~=':
  1888. comparison_value = re.compile(m.group('value'))
  1889. else:
  1890. comparison_value = re.sub(r'''\\([\\"'])''', r'\1', m.group('value'))
  1891. str_op = STR_OPERATORS[m.group('op')]
  1892. if m.group('negation'):
  1893. op = lambda attr, value: not str_op(attr, value)
  1894. else:
  1895. op = str_op
  1896. if not m:
  1897. raise SyntaxError('Invalid filter specification %r' % filter_spec)
  1898. def _filter(f):
  1899. actual_value = f.get(m.group('key'))
  1900. if actual_value is None:
  1901. return m.group('none_inclusive')
  1902. return op(actual_value, comparison_value)
  1903. return _filter
  1904. def _check_formats(self, formats):
  1905. for f in formats:
  1906. self.to_screen('[info] Testing format %s' % f['format_id'])
  1907. path = self.get_output_path('temp')
  1908. if not self._ensure_dir_exists(f'{path}/'):
  1909. continue
  1910. temp_file = tempfile.NamedTemporaryFile(suffix='.tmp', delete=False, dir=path or None)
  1911. temp_file.close()
  1912. try:
  1913. success, _ = self.dl(temp_file.name, f, test=True)
  1914. except (DownloadError, OSError, ValueError) + network_exceptions:
  1915. success = False
  1916. finally:
  1917. if os.path.exists(temp_file.name):
  1918. try:
  1919. os.remove(temp_file.name)
  1920. except OSError:
  1921. self.report_warning('Unable to delete temporary file "%s"' % temp_file.name)
  1922. if success:
  1923. yield f
  1924. else:
  1925. self.to_screen('[info] Unable to download format %s. Skipping...' % f['format_id'])
  1926. def _default_format_spec(self, info_dict, download=True):
  1927. def can_merge():
  1928. merger = FFmpegMergerPP(self)
  1929. return merger.available and merger.can_merge()
  1930. prefer_best = (
  1931. not self.params.get('simulate')
  1932. and download
  1933. and (
  1934. not can_merge()
  1935. or info_dict.get('is_live') and not self.params.get('live_from_start')
  1936. or self.params['outtmpl']['default'] == '-'))
  1937. compat = (
  1938. prefer_best
  1939. or self.params.get('allow_multiple_audio_streams', False)
  1940. or 'format-spec' in self.params['compat_opts'])
  1941. return (
  1942. 'best/bestvideo+bestaudio' if prefer_best
  1943. else 'bestvideo*+bestaudio/best' if not compat
  1944. else 'bestvideo+bestaudio/best')
  1945. def build_format_selector(self, format_spec):
  1946. def syntax_error(note, start):
  1947. message = (
  1948. 'Invalid format specification: '
  1949. '{}\n\t{}\n\t{}^'.format(note, format_spec, ' ' * start[1]))
  1950. return SyntaxError(message)
  1951. PICKFIRST = 'PICKFIRST'
  1952. MERGE = 'MERGE'
  1953. SINGLE = 'SINGLE'
  1954. GROUP = 'GROUP'
  1955. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  1956. allow_multiple_streams = {'audio': self.params.get('allow_multiple_audio_streams', False),
  1957. 'video': self.params.get('allow_multiple_video_streams', False)}
  1958. def _parse_filter(tokens):
  1959. filter_parts = []
  1960. for type, string_, start, _, _ in tokens:
  1961. if type == tokenize.OP and string_ == ']':
  1962. return ''.join(filter_parts)
  1963. else:
  1964. filter_parts.append(string_)
  1965. def _remove_unused_ops(tokens):
  1966. # Remove operators that we don't use and join them with the surrounding strings.
  1967. # E.g. 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  1968. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  1969. last_string, last_start, last_end, last_line = None, None, None, None
  1970. for type, string_, start, end, line in tokens:
  1971. if type == tokenize.OP and string_ == '[':
  1972. if last_string:
  1973. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1974. last_string = None
  1975. yield type, string_, start, end, line
  1976. # everything inside brackets will be handled by _parse_filter
  1977. for type, string_, start, end, line in tokens:
  1978. yield type, string_, start, end, line
  1979. if type == tokenize.OP and string_ == ']':
  1980. break
  1981. elif type == tokenize.OP and string_ in ALLOWED_OPS:
  1982. if last_string:
  1983. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1984. last_string = None
  1985. yield type, string_, start, end, line
  1986. elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  1987. if not last_string:
  1988. last_string = string_
  1989. last_start = start
  1990. last_end = end
  1991. else:
  1992. last_string += string_
  1993. if last_string:
  1994. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1995. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  1996. selectors = []
  1997. current_selector = None
  1998. for type, string_, start, _, _ in tokens:
  1999. # ENCODING is only defined in python 3.x
  2000. if type == getattr(tokenize, 'ENCODING', None):
  2001. continue
  2002. elif type in [tokenize.NAME, tokenize.NUMBER]:
  2003. current_selector = FormatSelector(SINGLE, string_, [])
  2004. elif type == tokenize.OP:
  2005. if string_ == ')':
  2006. if not inside_group:
  2007. # ')' will be handled by the parentheses group
  2008. tokens.restore_last_token()
  2009. break
  2010. elif inside_merge and string_ in ['/', ',']:
  2011. tokens.restore_last_token()
  2012. break
  2013. elif inside_choice and string_ == ',':
  2014. tokens.restore_last_token()
  2015. break
  2016. elif string_ == ',':
  2017. if not current_selector:
  2018. raise syntax_error('"," must follow a format selector', start)
  2019. selectors.append(current_selector)
  2020. current_selector = None
  2021. elif string_ == '/':
  2022. if not current_selector:
  2023. raise syntax_error('"/" must follow a format selector', start)
  2024. first_choice = current_selector
  2025. second_choice = _parse_format_selection(tokens, inside_choice=True)
  2026. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  2027. elif string_ == '[':
  2028. if not current_selector:
  2029. current_selector = FormatSelector(SINGLE, 'best', [])
  2030. format_filter = _parse_filter(tokens)
  2031. current_selector.filters.append(format_filter)
  2032. elif string_ == '(':
  2033. if current_selector:
  2034. raise syntax_error('Unexpected "("', start)
  2035. group = _parse_format_selection(tokens, inside_group=True)
  2036. current_selector = FormatSelector(GROUP, group, [])
  2037. elif string_ == '+':
  2038. if not current_selector:
  2039. raise syntax_error('Unexpected "+"', start)
  2040. selector_1 = current_selector
  2041. selector_2 = _parse_format_selection(tokens, inside_merge=True)
  2042. if not selector_2:
  2043. raise syntax_error('Expected a selector', start)
  2044. current_selector = FormatSelector(MERGE, (selector_1, selector_2), [])
  2045. else:
  2046. raise syntax_error(f'Operator not recognized: "{string_}"', start)
  2047. elif type == tokenize.ENDMARKER:
  2048. break
  2049. if current_selector:
  2050. selectors.append(current_selector)
  2051. return selectors
  2052. def _merge(formats_pair):
  2053. format_1, format_2 = formats_pair
  2054. formats_info = []
  2055. formats_info.extend(format_1.get('requested_formats', (format_1,)))
  2056. formats_info.extend(format_2.get('requested_formats', (format_2,)))
  2057. if not allow_multiple_streams['video'] or not allow_multiple_streams['audio']:
  2058. get_no_more = {'video': False, 'audio': False}
  2059. for (i, fmt_info) in enumerate(formats_info):
  2060. if fmt_info.get('acodec') == fmt_info.get('vcodec') == 'none':
  2061. formats_info.pop(i)
  2062. continue
  2063. for aud_vid in ['audio', 'video']:
  2064. if not allow_multiple_streams[aud_vid] and fmt_info.get(aud_vid[0] + 'codec') != 'none':
  2065. if get_no_more[aud_vid]:
  2066. formats_info.pop(i)
  2067. break
  2068. get_no_more[aud_vid] = True
  2069. if len(formats_info) == 1:
  2070. return formats_info[0]
  2071. video_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('vcodec') != 'none']
  2072. audio_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('acodec') != 'none']
  2073. the_only_video = video_fmts[0] if len(video_fmts) == 1 else None
  2074. the_only_audio = audio_fmts[0] if len(audio_fmts) == 1 else None
  2075. output_ext = get_compatible_ext(
  2076. vcodecs=[f.get('vcodec') for f in video_fmts],
  2077. acodecs=[f.get('acodec') for f in audio_fmts],
  2078. vexts=[f['ext'] for f in video_fmts],
  2079. aexts=[f['ext'] for f in audio_fmts],
  2080. preferences=(try_call(lambda: self.params['merge_output_format'].split('/'))
  2081. or self.params.get('prefer_free_formats') and ('webm', 'mkv')))
  2082. filtered = lambda *keys: filter(None, (traverse_obj(fmt, *keys) for fmt in formats_info))
  2083. new_dict = {
  2084. 'requested_formats': formats_info,
  2085. 'format': '+'.join(filtered('format')),
  2086. 'format_id': '+'.join(filtered('format_id')),
  2087. 'ext': output_ext,
  2088. 'protocol': '+'.join(map(determine_protocol, formats_info)),
  2089. 'language': '+'.join(orderedSet(filtered('language'))) or None,
  2090. 'format_note': '+'.join(orderedSet(filtered('format_note'))) or None,
  2091. 'filesize_approx': sum(filtered('filesize', 'filesize_approx')) or None,
  2092. 'tbr': sum(filtered('tbr', 'vbr', 'abr')),
  2093. }
  2094. if the_only_video:
  2095. new_dict.update({
  2096. 'width': the_only_video.get('width'),
  2097. 'height': the_only_video.get('height'),
  2098. 'resolution': the_only_video.get('resolution') or self.format_resolution(the_only_video),
  2099. 'fps': the_only_video.get('fps'),
  2100. 'dynamic_range': the_only_video.get('dynamic_range'),
  2101. 'vcodec': the_only_video.get('vcodec'),
  2102. 'vbr': the_only_video.get('vbr'),
  2103. 'stretched_ratio': the_only_video.get('stretched_ratio'),
  2104. 'aspect_ratio': the_only_video.get('aspect_ratio'),
  2105. })
  2106. if the_only_audio:
  2107. new_dict.update({
  2108. 'acodec': the_only_audio.get('acodec'),
  2109. 'abr': the_only_audio.get('abr'),
  2110. 'asr': the_only_audio.get('asr'),
  2111. 'audio_channels': the_only_audio.get('audio_channels')
  2112. })
  2113. return new_dict
  2114. def _check_formats(formats):
  2115. if (self.params.get('check_formats') is not None
  2116. or self.params.get('allow_unplayable_formats')):
  2117. yield from formats
  2118. return
  2119. elif self.params.get('check_formats') == 'selected':
  2120. yield from self._check_formats(formats)
  2121. return
  2122. for f in formats:
  2123. if f.get('has_drm'):
  2124. yield from self._check_formats([f])
  2125. else:
  2126. yield f
  2127. def _build_selector_function(selector):
  2128. if isinstance(selector, list): # ,
  2129. fs = [_build_selector_function(s) for s in selector]
  2130. def selector_function(ctx):
  2131. for f in fs:
  2132. yield from f(ctx)
  2133. return selector_function
  2134. elif selector.type == GROUP: # ()
  2135. selector_function = _build_selector_function(selector.selector)
  2136. elif selector.type == PICKFIRST: # /
  2137. fs = [_build_selector_function(s) for s in selector.selector]
  2138. def selector_function(ctx):
  2139. for f in fs:
  2140. picked_formats = list(f(ctx))
  2141. if picked_formats:
  2142. return picked_formats
  2143. return []
  2144. elif selector.type == MERGE: # +
  2145. selector_1, selector_2 = map(_build_selector_function, selector.selector)
  2146. def selector_function(ctx):
  2147. for pair in itertools.product(selector_1(ctx), selector_2(ctx)):
  2148. yield _merge(pair)
  2149. elif selector.type == SINGLE: # atom
  2150. format_spec = selector.selector or 'best'
  2151. # TODO: Add allvideo, allaudio etc by generalizing the code with best/worst selector
  2152. if format_spec == 'all':
  2153. def selector_function(ctx):
  2154. yield from _check_formats(ctx['formats'][::-1])
  2155. elif format_spec == 'mergeall':
  2156. def selector_function(ctx):
  2157. formats = list(_check_formats(
  2158. f for f in ctx['formats'] if f.get('vcodec') != 'none' or f.get('acodec') != 'none'))
  2159. if not formats:
  2160. return
  2161. merged_format = formats[-1]
  2162. for f in formats[-2::-1]:
  2163. merged_format = _merge((merged_format, f))
  2164. yield merged_format
  2165. else:
  2166. format_fallback, seperate_fallback, format_reverse, format_idx = False, None, True, 1
  2167. mobj = re.match(
  2168. r'(?P<bw>best|worst|b|w)(?P<type>video|audio|v|a)?(?P<mod>\*)?(?:\.(?P<n>[1-9]\d*))?$',
  2169. format_spec)
  2170. if mobj is not None:
  2171. format_idx = int_or_none(mobj.group('n'), default=1)
  2172. format_reverse = mobj.group('bw')[0] == 'b'
  2173. format_type = (mobj.group('type') or [None])[0]
  2174. not_format_type = {'v': 'a', 'a': 'v'}.get(format_type)
  2175. format_modified = mobj.group('mod') is not None
  2176. format_fallback = not format_type and not format_modified # for b, w
  2177. _filter_f = (
  2178. (lambda f: f.get('%scodec' % format_type) != 'none')
  2179. if format_type and format_modified # bv*, ba*, wv*, wa*
  2180. else (lambda f: f.get('%scodec' % not_format_type) == 'none')
  2181. if format_type # bv, ba, wv, wa
  2182. else (lambda f: f.get('vcodec') != 'none' and f.get('acodec') != 'none')
  2183. if not format_modified # b, w
  2184. else lambda f: True) # b*, w*
  2185. filter_f = lambda f: _filter_f(f) and (
  2186. f.get('vcodec') != 'none' or f.get('acodec') != 'none')
  2187. else:
  2188. if format_spec in self._format_selection_exts['audio']:
  2189. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none'
  2190. elif format_spec in self._format_selection_exts['video']:
  2191. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') != 'none' and f.get('vcodec') != 'none'
  2192. seperate_fallback = lambda f: f.get('ext') == format_spec and f.get('vcodec') != 'none'
  2193. elif format_spec in self._format_selection_exts['storyboards']:
  2194. filter_f = lambda f: f.get('ext') == format_spec and f.get('acodec') == 'none' and f.get('vcodec') == 'none'
  2195. else:
  2196. filter_f = lambda f: f.get('format_id') == format_spec # id
  2197. def selector_function(ctx):
  2198. formats = list(ctx['formats'])
  2199. matches = list(filter(filter_f, formats)) if filter_f is not None else formats
  2200. if not matches:
  2201. if format_fallback and ctx['incomplete_formats']:
  2202. # for extractors with incomplete formats (audio only (soundcloud)
  2203. # or video only (imgur)) best/worst will fallback to
  2204. # best/worst {video,audio}-only format
  2205. matches = formats
  2206. elif seperate_fallback and not ctx['has_merged_format']:
  2207. # for compatibility with youtube-dl when there is no pre-merged format
  2208. matches = list(filter(seperate_fallback, formats))
  2209. matches = LazyList(_check_formats(matches[::-1 if format_reverse else 1]))
  2210. try:
  2211. yield matches[format_idx - 1]
  2212. except LazyList.IndexError:
  2213. return
  2214. filters = [self._build_format_filter(f) for f in selector.filters]
  2215. def final_selector(ctx):
  2216. ctx_copy = dict(ctx)
  2217. for _filter in filters:
  2218. ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
  2219. return selector_function(ctx_copy)
  2220. return final_selector
  2221. stream = io.BytesIO(format_spec.encode())
  2222. try:
  2223. tokens = list(_remove_unused_ops(tokenize.tokenize(stream.readline)))
  2224. except tokenize.TokenError:
  2225. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  2226. class TokenIterator:
  2227. def __init__(self, tokens):
  2228. self.tokens = tokens
  2229. self.counter = 0
  2230. def __iter__(self):
  2231. return self
  2232. def __next__(self):
  2233. if self.counter >= len(self.tokens):
  2234. raise StopIteration()
  2235. value = self.tokens[self.counter]
  2236. self.counter += 1
  2237. return value
  2238. next = __next__
  2239. def restore_last_token(self):
  2240. self.counter -= 1
  2241. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  2242. return _build_selector_function(parsed_selector)
  2243. def _calc_headers(self, info_dict, load_cookies=False):
  2244. res = HTTPHeaderDict(self.params['http_headers'], info_dict.get('http_headers'))
  2245. clean_headers(res)
  2246. if load_cookies: # For --load-info-json
  2247. self._load_cookies(res.get('Cookie'), autoscope=info_dict['url']) # compat
  2248. self._load_cookies(info_dict.get('cookies'), autoscope=False)
  2249. # The `Cookie` header is removed to prevent leaks and unscoped cookies.
  2250. # See: https://github.com/yt-dlp/yt-dlp/security/advisories/GHSA-v8mc-9377-rwjj
  2251. res.pop('Cookie', None)
  2252. cookies = self.cookiejar.get_cookies_for_url(info_dict['url'])
  2253. if cookies:
  2254. encoder = LenientSimpleCookie()
  2255. values = []
  2256. for cookie in cookies:
  2257. _, value = encoder.value_encode(cookie.value)
  2258. values.append(f'{cookie.name}={value}')
  2259. if cookie.domain:
  2260. values.append(f'Domain={cookie.domain}')
  2261. if cookie.path:
  2262. values.append(f'Path={cookie.path}')
  2263. if cookie.secure:
  2264. values.append('Secure')
  2265. if cookie.expires:
  2266. values.append(f'Expires={cookie.expires}')
  2267. if cookie.version:
  2268. values.append(f'Version={cookie.version}')
  2269. info_dict['cookies'] = '; '.join(values)
  2270. if 'X-Forwarded-For' not in res:
  2271. x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
  2272. if x_forwarded_for_ip:
  2273. res['X-Forwarded-For'] = x_forwarded_for_ip
  2274. return res
  2275. def _calc_cookies(self, url):
  2276. self.deprecation_warning('"YoutubeDL._calc_cookies" is deprecated and may be removed in a future version')
  2277. return self.cookiejar.get_cookie_header(url)
  2278. def _sort_thumbnails(self, thumbnails):
  2279. thumbnails.sort(key=lambda t: (
  2280. t.get('preference') if t.get('preference') is not None else -1,
  2281. t.get('width') if t.get('width') is not None else -1,
  2282. t.get('height') if t.get('height') is not None else -1,
  2283. t.get('id') if t.get('id') is not None else '',
  2284. t.get('url')))
  2285. def _sanitize_thumbnails(self, info_dict):
  2286. thumbnails = info_dict.get('thumbnails')
  2287. if thumbnails is None:
  2288. thumbnail = info_dict.get('thumbnail')
  2289. if thumbnail:
  2290. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  2291. if not thumbnails:
  2292. return
  2293. def check_thumbnails(thumbnails):
  2294. for t in thumbnails:
  2295. self.to_screen(f'[info] Testing thumbnail {t["id"]}')
  2296. try:
  2297. self.urlopen(HEADRequest(t['url']))
  2298. except network_exceptions as err:
  2299. self.to_screen(f'[info] Unable to connect to thumbnail {t["id"]} URL {t["url"]!r} - {err}. Skipping...')
  2300. continue
  2301. yield t
  2302. self._sort_thumbnails(thumbnails)
  2303. for i, t in enumerate(thumbnails):
  2304. if t.get('id') is None:
  2305. t['id'] = '%d' % i
  2306. if t.get('width') and t.get('height'):
  2307. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  2308. t['url'] = sanitize_url(t['url'])
  2309. if self.params.get('check_formats') is True:
  2310. info_dict['thumbnails'] = LazyList(check_thumbnails(thumbnails[::-1]), reverse=True)
  2311. else:
  2312. info_dict['thumbnails'] = thumbnails
  2313. def _fill_common_fields(self, info_dict, final=True):
  2314. # TODO: move sanitization here
  2315. if final:
  2316. title = info_dict['fulltitle'] = info_dict.get('title')
  2317. if not title:
  2318. if title == '':
  2319. self.write_debug('Extractor gave empty title. Creating a generic title')
  2320. else:
  2321. self.report_warning('Extractor failed to obtain "title". Creating a generic title instead')
  2322. info_dict['title'] = f'{info_dict["extractor"].replace(":", "-")} video #{info_dict["id"]}'
  2323. if info_dict.get('duration') is not None:
  2324. info_dict['duration_string'] = formatSeconds(info_dict['duration'])
  2325. for ts_key, date_key in (
  2326. ('timestamp', 'upload_date'),
  2327. ('release_timestamp', 'release_date'),
  2328. ('modified_timestamp', 'modified_date'),
  2329. ):
  2330. if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
  2331. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  2332. # see http://bugs.python.org/issue1646728)
  2333. with contextlib.suppress(ValueError, OverflowError, OSError):
  2334. upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
  2335. info_dict[date_key] = upload_date.strftime('%Y%m%d')
  2336. live_keys = ('is_live', 'was_live')
  2337. live_status = info_dict.get('live_status')
  2338. if live_status is None:
  2339. for key in live_keys:
  2340. if info_dict.get(key) is False:
  2341. continue
  2342. if info_dict.get(key):
  2343. live_status = key
  2344. break
  2345. if all(info_dict.get(key) is False for key in live_keys):
  2346. live_status = 'not_live'
  2347. if live_status:
  2348. info_dict['live_status'] = live_status
  2349. for key in live_keys:
  2350. if info_dict.get(key) is None:
  2351. info_dict[key] = (live_status == key)
  2352. if live_status == 'post_live':
  2353. info_dict['was_live'] = True
  2354. # Auto generate title fields corresponding to the *_number fields when missing
  2355. # in order to always have clean titles. This is very common for TV series.
  2356. for field in ('chapter', 'season', 'episode'):
  2357. if final and info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
  2358. info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
  2359. def _raise_pending_errors(self, info):
  2360. err = info.pop('__pending_error', None)
  2361. if err:
  2362. self.report_error(err, tb=False)
  2363. def sort_formats(self, info_dict):
  2364. formats = self._get_formats(info_dict)
  2365. formats.sort(key=FormatSorter(
  2366. self, info_dict.get('_format_sort_fields') or []).calculate_preference)
  2367. def process_video_result(self, info_dict, download=True):
  2368. assert info_dict.get('_type', 'video') == 'video'
  2369. self._num_videos += 1
  2370. if 'id' not in info_dict:
  2371. raise ExtractorError('Missing "id" field in extractor result', ie=info_dict['extractor'])
  2372. elif not info_dict.get('id'):
  2373. raise ExtractorError('Extractor failed to obtain "id"', ie=info_dict['extractor'])
  2374. def report_force_conversion(field, field_not, conversion):
  2375. self.report_warning(
  2376. '"%s" field is not %s - forcing %s conversion, there is an error in extractor'
  2377. % (field, field_not, conversion))
  2378. def sanitize_string_field(info, string_field):
  2379. field = info.get(string_field)
  2380. if field is None or isinstance(field, str):
  2381. return
  2382. report_force_conversion(string_field, 'a string', 'string')
  2383. info[string_field] = str(field)
  2384. def sanitize_numeric_fields(info):
  2385. for numeric_field in self._NUMERIC_FIELDS:
  2386. field = info.get(numeric_field)
  2387. if field is None or isinstance(field, (int, float)):
  2388. continue
  2389. report_force_conversion(numeric_field, 'numeric', 'int')
  2390. info[numeric_field] = int_or_none(field)
  2391. sanitize_string_field(info_dict, 'id')
  2392. sanitize_numeric_fields(info_dict)
  2393. if info_dict.get('section_end') and info_dict.get('section_start') is not None:
  2394. info_dict['duration'] = round(info_dict['section_end'] - info_dict['section_start'], 3)
  2395. if (info_dict.get('duration') or 0) <= 0 and info_dict.pop('duration', None):
  2396. self.report_warning('"duration" field is negative, there is an error in extractor')
  2397. chapters = info_dict.get('chapters') or []
  2398. if chapters and chapters[0].get('start_time'):
  2399. chapters.insert(0, {'start_time': 0})
  2400. dummy_chapter = {'end_time': 0, 'start_time': info_dict.get('duration')}
  2401. for idx, (prev, current, next_) in enumerate(zip(
  2402. (dummy_chapter, *chapters), chapters, (*chapters[1:], dummy_chapter)), 1):
  2403. if current.get('start_time') is None:
  2404. current['start_time'] = prev.get('end_time')
  2405. if not current.get('end_time'):
  2406. current['end_time'] = next_.get('start_time')
  2407. if not current.get('title'):
  2408. current['title'] = f'<Untitled Chapter {idx}>'
  2409. if 'playlist' not in info_dict:
  2410. # It isn't part of a playlist
  2411. info_dict['playlist'] = None
  2412. info_dict['playlist_index'] = None
  2413. self._sanitize_thumbnails(info_dict)
  2414. thumbnail = info_dict.get('thumbnail')
  2415. thumbnails = info_dict.get('thumbnails')
  2416. if thumbnail:
  2417. info_dict['thumbnail'] = sanitize_url(thumbnail)
  2418. elif thumbnails:
  2419. info_dict['thumbnail'] = thumbnails[-1]['url']
  2420. if info_dict.get('display_id') is None and 'id' in info_dict:
  2421. info_dict['display_id'] = info_dict['id']
  2422. self._fill_common_fields(info_dict)
  2423. for cc_kind in ('subtitles', 'automatic_captions'):
  2424. cc = info_dict.get(cc_kind)
  2425. if cc:
  2426. for _, subtitle in cc.items():
  2427. for subtitle_format in subtitle:
  2428. if subtitle_format.get('url'):
  2429. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  2430. if subtitle_format.get('ext') is None:
  2431. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  2432. automatic_captions = info_dict.get('automatic_captions')
  2433. subtitles = info_dict.get('subtitles')
  2434. info_dict['requested_subtitles'] = self.process_subtitles(
  2435. info_dict['id'], subtitles, automatic_captions)
  2436. formats = self._get_formats(info_dict)
  2437. # Backward compatibility with InfoExtractor._sort_formats
  2438. field_preference = (formats or [{}])[0].pop('__sort_fields', None)
  2439. if field_preference:
  2440. info_dict['_format_sort_fields'] = field_preference
  2441. info_dict['_has_drm'] = any( # or None ensures --clean-infojson removes it
  2442. f.get('has_drm') and f['has_drm'] != 'maybe' for f in formats) or None
  2443. if not self.params.get('allow_unplayable_formats'):
  2444. formats = [f for f in formats if not f.get('has_drm') or f['has_drm'] == 'maybe']
  2445. if formats and all(f.get('acodec') == f.get('vcodec') == 'none' for f in formats):
  2446. self.report_warning(
  2447. f'{"This video is DRM protected and " if info_dict["_has_drm"] else ""}'
  2448. 'only images are available for download. Use --list-formats to see them'.capitalize())
  2449. get_from_start = not info_dict.get('is_live') or bool(self.params.get('live_from_start'))
  2450. if not get_from_start:
  2451. info_dict['title'] += ' ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
  2452. if info_dict.get('is_live') and formats:
  2453. formats = [f for f in formats if bool(f.get('is_from_start')) == get_from_start]
  2454. if get_from_start and not formats:
  2455. self.raise_no_formats(info_dict, msg=(
  2456. '--live-from-start is passed, but there are no formats that can be downloaded from the start. '
  2457. 'If you want to download from the current time, use --no-live-from-start'))
  2458. def is_wellformed(f):
  2459. url = f.get('url')
  2460. if not url:
  2461. self.report_warning(
  2462. '"url" field is missing or empty - skipping format, '
  2463. 'there is an error in extractor')
  2464. return False
  2465. if isinstance(url, bytes):
  2466. sanitize_string_field(f, 'url')
  2467. return True
  2468. # Filter out malformed formats for better extraction robustness
  2469. formats = list(filter(is_wellformed, formats or []))
  2470. if not formats:
  2471. self.raise_no_formats(info_dict)
  2472. for format in formats:
  2473. sanitize_string_field(format, 'format_id')
  2474. sanitize_numeric_fields(format)
  2475. format['url'] = sanitize_url(format['url'])
  2476. if format.get('ext') is None:
  2477. format['ext'] = determine_ext(format['url']).lower()
  2478. if format.get('protocol') is None:
  2479. format['protocol'] = determine_protocol(format)
  2480. if format.get('resolution') is None:
  2481. format['resolution'] = self.format_resolution(format, default=None)
  2482. if format.get('dynamic_range') is None and format.get('vcodec') != 'none':
  2483. format['dynamic_range'] = 'SDR'
  2484. if format.get('aspect_ratio') is None:
  2485. format['aspect_ratio'] = try_call(lambda: round(format['width'] / format['height'], 2))
  2486. if (not format.get('manifest_url') # For fragmented formats, "tbr" is often max bitrate and not average
  2487. and info_dict.get('duration') and format.get('tbr')
  2488. and not format.get('filesize') and not format.get('filesize_approx')):
  2489. format['filesize_approx'] = int(info_dict['duration'] * format['tbr'] * (1024 / 8))
  2490. format['http_headers'] = self._calc_headers(collections.ChainMap(format, info_dict), load_cookies=True)
  2491. # Safeguard against old/insecure infojson when using --load-info-json
  2492. if info_dict.get('http_headers'):
  2493. info_dict['http_headers'] = HTTPHeaderDict(info_dict['http_headers'])
  2494. info_dict['http_headers'].pop('Cookie', None)
  2495. # This is copied to http_headers by the above _calc_headers and can now be removed
  2496. if '__x_forwarded_for_ip' in info_dict:
  2497. del info_dict['__x_forwarded_for_ip']
  2498. self.sort_formats({
  2499. 'formats': formats,
  2500. '_format_sort_fields': info_dict.get('_format_sort_fields')
  2501. })
  2502. # Sanitize and group by format_id
  2503. formats_dict = {}
  2504. for i, format in enumerate(formats):
  2505. if not format.get('format_id'):
  2506. format['format_id'] = str(i)
  2507. else:
  2508. # Sanitize format_id from characters used in format selector expression
  2509. format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
  2510. formats_dict.setdefault(format['format_id'], []).append(format)
  2511. # Make sure all formats have unique format_id
  2512. common_exts = set(itertools.chain(*self._format_selection_exts.values()))
  2513. for format_id, ambiguous_formats in formats_dict.items():
  2514. ambigious_id = len(ambiguous_formats) > 1
  2515. for i, format in enumerate(ambiguous_formats):
  2516. if ambigious_id:
  2517. format['format_id'] = '%s-%d' % (format_id, i)
  2518. # Ensure there is no conflict between id and ext in format selection
  2519. # See https://github.com/yt-dlp/yt-dlp/issues/1282
  2520. if format['format_id'] != format['ext'] and format['format_id'] in common_exts:
  2521. format['format_id'] = 'f%s' % format['format_id']
  2522. if format.get('format') is None:
  2523. format['format'] = '{id} - {res}{note}'.format(
  2524. id=format['format_id'],
  2525. res=self.format_resolution(format),
  2526. note=format_field(format, 'format_note', ' (%s)'),
  2527. )
  2528. if self.params.get('check_formats') is True:
  2529. formats = LazyList(self._check_formats(formats[::-1]), reverse=True)
  2530. if not formats or formats[0] is not info_dict:
  2531. # only set the 'formats' fields if the original info_dict list them
  2532. # otherwise we end up with a circular reference, the first (and unique)
  2533. # element in the 'formats' field in info_dict is info_dict itself,
  2534. # which can't be exported to json
  2535. info_dict['formats'] = formats
  2536. info_dict, _ = self.pre_process(info_dict)
  2537. if self._match_entry(info_dict, incomplete=self._format_fields) is not None:
  2538. return info_dict
  2539. self.post_extract(info_dict)
  2540. info_dict, _ = self.pre_process(info_dict, 'after_filter')
  2541. # The pre-processors may have modified the formats
  2542. formats = self._get_formats(info_dict)
  2543. list_only = self.params.get('simulate') == 'list_only'
  2544. interactive_format_selection = not list_only and self.format_selector == '-'
  2545. if self.params.get('list_thumbnails'):
  2546. self.list_thumbnails(info_dict)
  2547. if self.params.get('listsubtitles'):
  2548. if 'automatic_captions' in info_dict:
  2549. self.list_subtitles(
  2550. info_dict['id'], automatic_captions, 'automatic captions')
  2551. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  2552. if self.params.get('listformats') or interactive_format_selection:
  2553. self.list_formats(info_dict)
  2554. if list_only:
  2555. # Without this printing, -F --print-json will not work
  2556. self.__forced_printings(info_dict)
  2557. return info_dict
  2558. format_selector = self.format_selector
  2559. while True:
  2560. if interactive_format_selection:
  2561. req_format = input(self._format_screen('\nEnter format selector ', self.Styles.EMPHASIS)
  2562. + '(Press ENTER for default, or Ctrl+C to quit)'
  2563. + self._format_screen(': ', self.Styles.EMPHASIS))
  2564. try:
  2565. format_selector = self.build_format_selector(req_format) if req_format else None
  2566. except SyntaxError as err:
  2567. self.report_error(err, tb=False, is_error=False)
  2568. continue
  2569. if format_selector is None:
  2570. req_format = self._default_format_spec(info_dict, download=download)
  2571. self.write_debug(f'Default format spec: {req_format}')
  2572. format_selector = self.build_format_selector(req_format)
  2573. formats_to_download = list(format_selector({
  2574. 'formats': formats,
  2575. 'has_merged_format': any('none' not in (f.get('acodec'), f.get('vcodec')) for f in formats),
  2576. 'incomplete_formats': (all(f.get('vcodec') == 'none' for f in formats) # No formats with video
  2577. or all(f.get('acodec') == 'none' for f in formats)), # OR, No formats with audio
  2578. }))
  2579. if interactive_format_selection and not formats_to_download:
  2580. self.report_error('Requested format is not available', tb=False, is_error=False)
  2581. continue
  2582. break
  2583. if not formats_to_download:
  2584. if not self.params.get('ignore_no_formats_error'):
  2585. raise ExtractorError(
  2586. 'Requested format is not available. Use --list-formats for a list of available formats',
  2587. expected=True, video_id=info_dict['id'], ie=info_dict['extractor'])
  2588. self.report_warning('Requested format is not available')
  2589. # Process what we can, even without any available formats.
  2590. formats_to_download = [{}]
  2591. requested_ranges = tuple(self.params.get('download_ranges', lambda *_: [{}])(info_dict, self))
  2592. best_format, downloaded_formats = formats_to_download[-1], []
  2593. if download:
  2594. if best_format and requested_ranges:
  2595. def to_screen(*msg):
  2596. self.to_screen(f'[info] {info_dict["id"]}: {" ".join(", ".join(variadic(m)) for m in msg)}')
  2597. to_screen(f'Downloading {len(formats_to_download)} format(s):',
  2598. (f['format_id'] for f in formats_to_download))
  2599. if requested_ranges != ({}, ):
  2600. to_screen(f'Downloading {len(requested_ranges)} time ranges:',
  2601. (f'{c["start_time"]:.1f}-{c["end_time"]:.1f}' for c in requested_ranges))
  2602. max_downloads_reached = False
  2603. for fmt, chapter in itertools.product(formats_to_download, requested_ranges):
  2604. new_info = self._copy_infodict(info_dict)
  2605. new_info.update(fmt)
  2606. offset, duration = info_dict.get('section_start') or 0, info_dict.get('duration') or float('inf')
  2607. end_time = offset + min(chapter.get('end_time', duration), duration)
  2608. # duration may not be accurate. So allow deviations <1sec
  2609. if end_time == float('inf') or end_time > offset + duration + 1:
  2610. end_time = None
  2611. if chapter or offset:
  2612. new_info.update({
  2613. 'section_start': offset + chapter.get('start_time', 0),
  2614. 'section_end': end_time,
  2615. 'section_title': chapter.get('title'),
  2616. 'section_number': chapter.get('index'),
  2617. })
  2618. downloaded_formats.append(new_info)
  2619. try:
  2620. self.process_info(new_info)
  2621. except MaxDownloadsReached:
  2622. max_downloads_reached = True
  2623. self._raise_pending_errors(new_info)
  2624. # Remove copied info
  2625. for key, val in tuple(new_info.items()):
  2626. if info_dict.get(key) == val:
  2627. new_info.pop(key)
  2628. if max_downloads_reached:
  2629. break
  2630. write_archive = {f.get('__write_download_archive', False) for f in downloaded_formats}
  2631. assert write_archive.issubset({True, False, 'ignore'})
  2632. if True in write_archive and False not in write_archive:
  2633. self.record_download_archive(info_dict)
  2634. info_dict['requested_downloads'] = downloaded_formats
  2635. info_dict = self.run_all_pps('after_video', info_dict)
  2636. if max_downloads_reached:
  2637. raise MaxDownloadsReached()
  2638. # We update the info dict with the selected best quality format (backwards compatibility)
  2639. info_dict.update(best_format)
  2640. return info_dict
  2641. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  2642. """Select the requested subtitles and their format"""
  2643. available_subs, normal_sub_langs = {}, []
  2644. if normal_subtitles and self.params.get('writesubtitles'):
  2645. available_subs.update(normal_subtitles)
  2646. normal_sub_langs = tuple(normal_subtitles.keys())
  2647. if automatic_captions and self.params.get('writeautomaticsub'):
  2648. for lang, cap_info in automatic_captions.items():
  2649. if lang not in available_subs:
  2650. available_subs[lang] = cap_info
  2651. if not available_subs or (
  2652. not self.params.get('writesubtitles')
  2653. and not self.params.get('writeautomaticsub')):
  2654. return None
  2655. all_sub_langs = tuple(available_subs.keys())
  2656. if self.params.get('allsubtitles', False):
  2657. requested_langs = all_sub_langs
  2658. elif self.params.get('subtitleslangs', False):
  2659. try:
  2660. requested_langs = orderedSet_from_options(
  2661. self.params.get('subtitleslangs'), {'all': all_sub_langs}, use_regex=True)
  2662. except re.error as e:
  2663. raise ValueError(f'Wrong regex for subtitlelangs: {e.pattern}')
  2664. else:
  2665. requested_langs = LazyList(itertools.chain(
  2666. ['en'] if 'en' in normal_sub_langs else [],
  2667. filter(lambda f: f.startswith('en'), normal_sub_langs),
  2668. ['en'] if 'en' in all_sub_langs else [],
  2669. filter(lambda f: f.startswith('en'), all_sub_langs),
  2670. normal_sub_langs, all_sub_langs,
  2671. ))[:1]
  2672. if requested_langs:
  2673. self.to_screen(f'[info] {video_id}: Downloading subtitles: {", ".join(requested_langs)}')
  2674. formats_query = self.params.get('subtitlesformat', 'best')
  2675. formats_preference = formats_query.split('/') if formats_query else []
  2676. subs = {}
  2677. for lang in requested_langs:
  2678. formats = available_subs.get(lang)
  2679. if formats is None:
  2680. self.report_warning(f'{lang} subtitles not available for {video_id}')
  2681. continue
  2682. for ext in formats_preference:
  2683. if ext == 'best':
  2684. f = formats[-1]
  2685. break
  2686. matches = list(filter(lambda f: f['ext'] == ext, formats))
  2687. if matches:
  2688. f = matches[-1]
  2689. break
  2690. else:
  2691. f = formats[-1]
  2692. self.report_warning(
  2693. 'No subtitle format found matching "%s" for language %s, '
  2694. 'using %s' % (formats_query, lang, f['ext']))
  2695. subs[lang] = f
  2696. return subs
  2697. def _forceprint(self, key, info_dict):
  2698. if info_dict is None:
  2699. return
  2700. info_copy = info_dict.copy()
  2701. info_copy.setdefault('filename', self.prepare_filename(info_dict))
  2702. if info_dict.get('requested_formats') is not None:
  2703. # For RTMP URLs, also include the playpath
  2704. info_copy['urls'] = '\n'.join(f['url'] + f.get('play_path', '') for f in info_dict['requested_formats'])
  2705. elif info_dict.get('url'):
  2706. info_copy['urls'] = info_dict['url'] + info_dict.get('play_path', '')
  2707. info_copy['formats_table'] = self.render_formats_table(info_dict)
  2708. info_copy['thumbnails_table'] = self.render_thumbnails_table(info_dict)
  2709. info_copy['subtitles_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('subtitles'))
  2710. info_copy['automatic_captions_table'] = self.render_subtitles_table(info_dict.get('id'), info_dict.get('automatic_captions'))
  2711. def format_tmpl(tmpl):
  2712. mobj = re.fullmatch(r'([\w.:,]|-\d|(?P<dict>{([\w.:,]|-\d)+}))+=?', tmpl)
  2713. if not mobj:
  2714. return tmpl
  2715. fmt = '%({})s'
  2716. if tmpl.startswith('{'):
  2717. tmpl, fmt = f'.{tmpl}', '%({})j'
  2718. if tmpl.endswith('='):
  2719. tmpl, fmt = tmpl[:-1], '{0} = %({0})#j'
  2720. return '\n'.join(map(fmt.format, [tmpl] if mobj.group('dict') else tmpl.split(',')))
  2721. for tmpl in self.params['forceprint'].get(key, []):
  2722. self.to_stdout(self.evaluate_outtmpl(format_tmpl(tmpl), info_copy))
  2723. for tmpl, file_tmpl in self.params['print_to_file'].get(key, []):
  2724. filename = self.prepare_filename(info_dict, outtmpl=file_tmpl)
  2725. tmpl = format_tmpl(tmpl)
  2726. self.to_screen(f'[info] Writing {tmpl!r} to: {filename}')
  2727. if self._ensure_dir_exists(filename):
  2728. with open(filename, 'a', encoding='utf-8', newline='') as f:
  2729. f.write(self.evaluate_outtmpl(tmpl, info_copy) + os.linesep)
  2730. return info_copy
  2731. def __forced_printings(self, info_dict, filename=None, incomplete=True):
  2732. if (self.params.get('forcejson')
  2733. or self.params['forceprint'].get('video')
  2734. or self.params['print_to_file'].get('video')):
  2735. self.post_extract(info_dict)
  2736. if filename:
  2737. info_dict['filename'] = filename
  2738. info_copy = self._forceprint('video', info_dict)
  2739. def print_field(field, actual_field=None, optional=False):
  2740. if actual_field is None:
  2741. actual_field = field
  2742. if self.params.get(f'force{field}') and (
  2743. info_copy.get(field) is not None or (not optional and not incomplete)):
  2744. self.to_stdout(info_copy[actual_field])
  2745. print_field('title')
  2746. print_field('id')
  2747. print_field('url', 'urls')
  2748. print_field('thumbnail', optional=True)
  2749. print_field('description', optional=True)
  2750. print_field('filename')
  2751. if self.params.get('forceduration') and info_copy.get('duration') is not None:
  2752. self.to_stdout(formatSeconds(info_copy['duration']))
  2753. print_field('format')
  2754. if self.params.get('forcejson'):
  2755. self.to_stdout(json.dumps(self.sanitize_info(info_dict)))
  2756. def dl(self, name, info, subtitle=False, test=False):
  2757. if not info.get('url'):
  2758. self.raise_no_formats(info, True)
  2759. if test:
  2760. verbose = self.params.get('verbose')
  2761. params = {
  2762. 'test': True,
  2763. 'quiet': self.params.get('quiet') or not verbose,
  2764. 'verbose': verbose,
  2765. 'noprogress': not verbose,
  2766. 'nopart': True,
  2767. 'skip_unavailable_fragments': False,
  2768. 'keep_fragments': False,
  2769. 'overwrites': True,
  2770. '_no_ytdl_file': True,
  2771. }
  2772. else:
  2773. params = self.params
  2774. fd = get_suitable_downloader(info, params, to_stdout=(name == '-'))(self, params)
  2775. if not test:
  2776. for ph in self._progress_hooks:
  2777. fd.add_progress_hook(ph)
  2778. urls = '", "'.join(
  2779. (f['url'].split(',')[0] + ',<data>' if f['url'].startswith('data:') else f['url'])
  2780. for f in info.get('requested_formats', []) or [info])
  2781. self.write_debug(f'Invoking {fd.FD_NAME} downloader on "{urls}"')
  2782. # Note: Ideally info should be a deep-copied so that hooks cannot modify it.
  2783. # But it may contain objects that are not deep-copyable
  2784. new_info = self._copy_infodict(info)
  2785. if new_info.get('http_headers') is None:
  2786. new_info['http_headers'] = self._calc_headers(new_info)
  2787. return fd.download(name, new_info, subtitle)
  2788. def existing_file(self, filepaths, *, default_overwrite=True):
  2789. existing_files = list(filter(os.path.exists, orderedSet(filepaths)))
  2790. if existing_files and not self.params.get('overwrites', default_overwrite):
  2791. return existing_files[0]
  2792. for file in existing_files:
  2793. self.report_file_delete(file)
  2794. os.remove(file)
  2795. return None
  2796. def process_info(self, info_dict):
  2797. """Process a single resolved IE result. (Modifies it in-place)"""
  2798. assert info_dict.get('_type', 'video') == 'video'
  2799. original_infodict = info_dict
  2800. if 'format' not in info_dict and 'ext' in info_dict:
  2801. info_dict['format'] = info_dict['ext']
  2802. if self._match_entry(info_dict) is not None:
  2803. info_dict['__write_download_archive'] = 'ignore'
  2804. return
  2805. # Does nothing under normal operation - for backward compatibility of process_info
  2806. self.post_extract(info_dict)
  2807. def replace_info_dict(new_info):
  2808. nonlocal info_dict
  2809. if new_info == info_dict:
  2810. return
  2811. info_dict.clear()
  2812. info_dict.update(new_info)
  2813. new_info, _ = self.pre_process(info_dict, 'video')
  2814. replace_info_dict(new_info)
  2815. self._num_downloads += 1
  2816. # info_dict['_filename'] needs to be set for backward compatibility
  2817. info_dict['_filename'] = full_filename = self.prepare_filename(info_dict, warn=True)
  2818. temp_filename = self.prepare_filename(info_dict, 'temp')
  2819. files_to_move = {}
  2820. # Forced printings
  2821. self.__forced_printings(info_dict, full_filename, incomplete=('format' not in info_dict))
  2822. def check_max_downloads():
  2823. if self._num_downloads >= float(self.params.get('max_downloads') or 'inf'):
  2824. raise MaxDownloadsReached()
  2825. if self.params.get('simulate'):
  2826. info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
  2827. check_max_downloads()
  2828. return
  2829. if full_filename is None:
  2830. return
  2831. if not self._ensure_dir_exists(encodeFilename(full_filename)):
  2832. return
  2833. if not self._ensure_dir_exists(encodeFilename(temp_filename)):
  2834. return
  2835. if self._write_description('video', info_dict,
  2836. self.prepare_filename(info_dict, 'description')) is None:
  2837. return
  2838. sub_files = self._write_subtitles(info_dict, temp_filename)
  2839. if sub_files is None:
  2840. return
  2841. files_to_move.update(dict(sub_files))
  2842. thumb_files = self._write_thumbnails(
  2843. 'video', info_dict, temp_filename, self.prepare_filename(info_dict, 'thumbnail'))
  2844. if thumb_files is None:
  2845. return
  2846. files_to_move.update(dict(thumb_files))
  2847. infofn = self.prepare_filename(info_dict, 'infojson')
  2848. _infojson_written = self._write_info_json('video', info_dict, infofn)
  2849. if _infojson_written:
  2850. info_dict['infojson_filename'] = infofn
  2851. # For backward compatibility, even though it was a private field
  2852. info_dict['__infojson_filename'] = infofn
  2853. elif _infojson_written is None:
  2854. return
  2855. # Note: Annotations are deprecated
  2856. annofn = None
  2857. if self.params.get('writeannotations', False):
  2858. annofn = self.prepare_filename(info_dict, 'annotation')
  2859. if annofn:
  2860. if not self._ensure_dir_exists(encodeFilename(annofn)):
  2861. return
  2862. if not self.params.get('overwrites', True) and os.path.exists(encodeFilename(annofn)):
  2863. self.to_screen('[info] Video annotations are already present')
  2864. elif not info_dict.get('annotations'):
  2865. self.report_warning('There are no annotations to write.')
  2866. else:
  2867. try:
  2868. self.to_screen('[info] Writing video annotations to: ' + annofn)
  2869. with open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  2870. annofile.write(info_dict['annotations'])
  2871. except (KeyError, TypeError):
  2872. self.report_warning('There are no annotations to write.')
  2873. except OSError:
  2874. self.report_error('Cannot write annotations file: ' + annofn)
  2875. return
  2876. # Write internet shortcut files
  2877. def _write_link_file(link_type):
  2878. url = try_get(info_dict['webpage_url'], iri_to_uri)
  2879. if not url:
  2880. self.report_warning(
  2881. f'Cannot write internet shortcut file because the actual URL of "{info_dict["webpage_url"]}" is unknown')
  2882. return True
  2883. linkfn = replace_extension(self.prepare_filename(info_dict, 'link'), link_type, info_dict.get('ext'))
  2884. if not self._ensure_dir_exists(encodeFilename(linkfn)):
  2885. return False
  2886. if self.params.get('overwrites', True) and os.path.exists(encodeFilename(linkfn)):
  2887. self.to_screen(f'[info] Internet shortcut (.{link_type}) is already present')
  2888. return True
  2889. try:
  2890. self.to_screen(f'[info] Writing internet shortcut (.{link_type}) to: {linkfn}')
  2891. with open(encodeFilename(to_high_limit_path(linkfn)), 'w', encoding='utf-8',
  2892. newline='\r\n' if link_type == 'url' else '\n') as linkfile:
  2893. template_vars = {'url': url}
  2894. if link_type == 'desktop':
  2895. template_vars['filename'] = linkfn[:-(len(link_type) + 1)]
  2896. linkfile.write(LINK_TEMPLATES[link_type] % template_vars)
  2897. except OSError:
  2898. self.report_error(f'Cannot write internet shortcut {linkfn}')
  2899. return False
  2900. return True
  2901. write_links = {
  2902. 'url': self.params.get('writeurllink'),
  2903. 'webloc': self.params.get('writewebloclink'),
  2904. 'desktop': self.params.get('writedesktoplink'),
  2905. }
  2906. if self.params.get('writelink'):
  2907. link_type = ('webloc' if sys.platform == 'darwin'
  2908. else 'desktop' if sys.platform.startswith('linux')
  2909. else 'url')
  2910. write_links[link_type] = True
  2911. if any(should_write and not _write_link_file(link_type)
  2912. for link_type, should_write in write_links.items()):
  2913. return
  2914. new_info, files_to_move = self.pre_process(info_dict, 'before_dl', files_to_move)
  2915. replace_info_dict(new_info)
  2916. if self.params.get('skip_download'):
  2917. info_dict['filepath'] = temp_filename
  2918. info_dict['__finaldir'] = os.path.dirname(os.path.abspath(encodeFilename(full_filename)))
  2919. info_dict['__files_to_move'] = files_to_move
  2920. replace_info_dict(self.run_pp(MoveFilesAfterDownloadPP(self, False), info_dict))
  2921. info_dict['__write_download_archive'] = self.params.get('force_write_download_archive')
  2922. else:
  2923. # Download
  2924. info_dict.setdefault('__postprocessors', [])
  2925. try:
  2926. def existing_video_file(*filepaths):
  2927. ext = info_dict.get('ext')
  2928. converted = lambda file: replace_extension(file, self.params.get('final_ext') or ext, ext)
  2929. file = self.existing_file(itertools.chain(*zip(map(converted, filepaths), filepaths)),
  2930. default_overwrite=False)
  2931. if file:
  2932. info_dict['ext'] = os.path.splitext(file)[1][1:]
  2933. return file
  2934. fd, success = None, True
  2935. if info_dict.get('protocol') or info_dict.get('url'):
  2936. fd = get_suitable_downloader(info_dict, self.params, to_stdout=temp_filename == '-')
  2937. if fd is not FFmpegFD and 'no-direct-merge' not in self.params['compat_opts'] and (
  2938. info_dict.get('section_start') or info_dict.get('section_end')):
  2939. msg = ('This format cannot be partially downloaded' if FFmpegFD.available()
  2940. else 'You have requested downloading the video partially, but ffmpeg is not installed')
  2941. self.report_error(f'{msg}. Aborting')
  2942. return
  2943. if info_dict.get('requested_formats') is not None:
  2944. old_ext = info_dict['ext']
  2945. if self.params.get('merge_output_format') is None:
  2946. if (info_dict['ext'] == 'webm'
  2947. and info_dict.get('thumbnails')
  2948. # check with type instead of pp_key, __name__, or isinstance
  2949. # since we dont want any custom PPs to trigger this
  2950. and any(type(pp) == EmbedThumbnailPP for pp in self._pps['post_process'])): # noqa: E721
  2951. info_dict['ext'] = 'mkv'
  2952. self.report_warning(
  2953. 'webm doesn\'t support embedding a thumbnail, mkv will be used')
  2954. new_ext = info_dict['ext']
  2955. def correct_ext(filename, ext=new_ext):
  2956. if filename == '-':
  2957. return filename
  2958. filename_real_ext = os.path.splitext(filename)[1][1:]
  2959. filename_wo_ext = (
  2960. os.path.splitext(filename)[0]
  2961. if filename_real_ext in (old_ext, new_ext)
  2962. else filename)
  2963. return f'{filename_wo_ext}.{ext}'
  2964. # Ensure filename always has a correct extension for successful merge
  2965. full_filename = correct_ext(full_filename)
  2966. temp_filename = correct_ext(temp_filename)
  2967. dl_filename = existing_video_file(full_filename, temp_filename)
  2968. info_dict['__real_download'] = False
  2969. # NOTE: Copy so that original format dicts are not modified
  2970. info_dict['requested_formats'] = list(map(dict, info_dict['requested_formats']))
  2971. merger = FFmpegMergerPP(self)
  2972. downloaded = []
  2973. if dl_filename is not None:
  2974. self.report_file_already_downloaded(dl_filename)
  2975. elif fd:
  2976. for f in info_dict['requested_formats'] if fd != FFmpegFD else []:
  2977. f['filepath'] = fname = prepend_extension(
  2978. correct_ext(temp_filename, info_dict['ext']),
  2979. 'f%s' % f['format_id'], info_dict['ext'])
  2980. downloaded.append(fname)
  2981. info_dict['url'] = '\n'.join(f['url'] for f in info_dict['requested_formats'])
  2982. success, real_download = self.dl(temp_filename, info_dict)
  2983. info_dict['__real_download'] = real_download
  2984. else:
  2985. if self.params.get('allow_unplayable_formats'):
  2986. self.report_warning(
  2987. 'You have requested merging of multiple formats '
  2988. 'while also allowing unplayable formats to be downloaded. '
  2989. 'The formats won\'t be merged to prevent data corruption.')
  2990. elif not merger.available:
  2991. msg = 'You have requested merging of multiple formats but ffmpeg is not installed'
  2992. if not self.params.get('ignoreerrors'):
  2993. self.report_error(f'{msg}. Aborting due to --abort-on-error')
  2994. return
  2995. self.report_warning(f'{msg}. The formats won\'t be merged')
  2996. if temp_filename == '-':
  2997. reason = ('using a downloader other than ffmpeg' if FFmpegFD.can_merge_formats(info_dict, self.params)
  2998. else 'but the formats are incompatible for simultaneous download' if merger.available
  2999. else 'but ffmpeg is not installed')
  3000. self.report_warning(
  3001. f'You have requested downloading multiple formats to stdout {reason}. '
  3002. 'The formats will be streamed one after the other')
  3003. fname = temp_filename
  3004. for f in info_dict['requested_formats']:
  3005. new_info = dict(info_dict)
  3006. del new_info['requested_formats']
  3007. new_info.update(f)
  3008. if temp_filename != '-':
  3009. fname = prepend_extension(
  3010. correct_ext(temp_filename, new_info['ext']),
  3011. 'f%s' % f['format_id'], new_info['ext'])
  3012. if not self._ensure_dir_exists(fname):
  3013. return
  3014. f['filepath'] = fname
  3015. downloaded.append(fname)
  3016. partial_success, real_download = self.dl(fname, new_info)
  3017. info_dict['__real_download'] = info_dict['__real_download'] or real_download
  3018. success = success and partial_success
  3019. if downloaded and merger.available and not self.params.get('allow_unplayable_formats'):
  3020. info_dict['__postprocessors'].append(merger)
  3021. info_dict['__files_to_merge'] = downloaded
  3022. # Even if there were no downloads, it is being merged only now
  3023. info_dict['__real_download'] = True
  3024. else:
  3025. for file in downloaded:
  3026. files_to_move[file] = None
  3027. else:
  3028. # Just a single file
  3029. dl_filename = existing_video_file(full_filename, temp_filename)
  3030. if dl_filename is None or dl_filename == temp_filename:
  3031. # dl_filename == temp_filename could mean that the file was partially downloaded with --no-part.
  3032. # So we should try to resume the download
  3033. success, real_download = self.dl(temp_filename, info_dict)
  3034. info_dict['__real_download'] = real_download
  3035. else:
  3036. self.report_file_already_downloaded(dl_filename)
  3037. dl_filename = dl_filename or temp_filename
  3038. info_dict['__finaldir'] = os.path.dirname(os.path.abspath(encodeFilename(full_filename)))
  3039. except network_exceptions as err:
  3040. self.report_error('unable to download video data: %s' % error_to_compat_str(err))
  3041. return
  3042. except OSError as err:
  3043. raise UnavailableVideoError(err)
  3044. except (ContentTooShortError, ) as err:
  3045. self.report_error(f'content too short (expected {err.expected} bytes and served {err.downloaded})')
  3046. return
  3047. self._raise_pending_errors(info_dict)
  3048. if success and full_filename != '-':
  3049. def fixup():
  3050. do_fixup = True
  3051. fixup_policy = self.params.get('fixup')
  3052. vid = info_dict['id']
  3053. if fixup_policy in ('ignore', 'never'):
  3054. return
  3055. elif fixup_policy == 'warn':
  3056. do_fixup = 'warn'
  3057. elif fixup_policy != 'force':
  3058. assert fixup_policy in ('detect_or_warn', None)
  3059. if not info_dict.get('__real_download'):
  3060. do_fixup = False
  3061. def ffmpeg_fixup(cndn, msg, cls):
  3062. if not (do_fixup and cndn):
  3063. return
  3064. elif do_fixup == 'warn':
  3065. self.report_warning(f'{vid}: {msg}')
  3066. return
  3067. pp = cls(self)
  3068. if pp.available:
  3069. info_dict['__postprocessors'].append(pp)
  3070. else:
  3071. self.report_warning(f'{vid}: {msg}. Install ffmpeg to fix this automatically')
  3072. stretched_ratio = info_dict.get('stretched_ratio')
  3073. ffmpeg_fixup(stretched_ratio not in (1, None),
  3074. f'Non-uniform pixel ratio {stretched_ratio}',
  3075. FFmpegFixupStretchedPP)
  3076. downloader = get_suitable_downloader(info_dict, self.params) if 'protocol' in info_dict else None
  3077. downloader = downloader.FD_NAME if downloader else None
  3078. ext = info_dict.get('ext')
  3079. postprocessed_by_ffmpeg = info_dict.get('requested_formats') or any((
  3080. isinstance(pp, FFmpegVideoConvertorPP)
  3081. and resolve_recode_mapping(ext, pp.mapping)[0] not in (ext, None)
  3082. ) for pp in self._pps['post_process'])
  3083. if not postprocessed_by_ffmpeg:
  3084. ffmpeg_fixup(ext == 'm4a' and info_dict.get('container') == 'm4a_dash',
  3085. 'writing DASH m4a. Only some players support this container',
  3086. FFmpegFixupM4aPP)
  3087. ffmpeg_fixup(downloader == 'hlsnative' and not self.params.get('hls_use_mpegts')
  3088. or info_dict.get('is_live') and self.params.get('hls_use_mpegts') is None,
  3089. 'Possible MPEG-TS in MP4 container or malformed AAC timestamps',
  3090. FFmpegFixupM3u8PP)
  3091. ffmpeg_fixup(info_dict.get('is_live') and downloader == 'dashsegments',
  3092. 'Possible duplicate MOOV atoms', FFmpegFixupDuplicateMoovPP)
  3093. ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed timestamps detected', FFmpegFixupTimestampPP)
  3094. ffmpeg_fixup(downloader == 'web_socket_fragment', 'Malformed duration detected', FFmpegFixupDurationPP)
  3095. fixup()
  3096. try:
  3097. replace_info_dict(self.post_process(dl_filename, info_dict, files_to_move))
  3098. except PostProcessingError as err:
  3099. self.report_error('Postprocessing: %s' % str(err))
  3100. return
  3101. try:
  3102. for ph in self._post_hooks:
  3103. ph(info_dict['filepath'])
  3104. except Exception as err:
  3105. self.report_error('post hooks: %s' % str(err))
  3106. return
  3107. info_dict['__write_download_archive'] = True
  3108. assert info_dict is original_infodict # Make sure the info_dict was modified in-place
  3109. if self.params.get('force_write_download_archive'):
  3110. info_dict['__write_download_archive'] = True
  3111. check_max_downloads()
  3112. def __download_wrapper(self, func):
  3113. @functools.wraps(func)
  3114. def wrapper(*args, **kwargs):
  3115. try:
  3116. res = func(*args, **kwargs)
  3117. except UnavailableVideoError as e:
  3118. self.report_error(e)
  3119. except DownloadCancelled as e:
  3120. self.to_screen(f'[info] {e}')
  3121. if not self.params.get('break_per_url'):
  3122. raise
  3123. self._num_downloads = 0
  3124. else:
  3125. if self.params.get('dump_single_json', False):
  3126. self.post_extract(res)
  3127. self.to_stdout(json.dumps(self.sanitize_info(res)))
  3128. return wrapper
  3129. def download(self, url_list):
  3130. """Download a given list of URLs."""
  3131. url_list = variadic(url_list) # Passing a single URL is a common mistake
  3132. outtmpl = self.params['outtmpl']['default']
  3133. if (len(url_list) > 1
  3134. and outtmpl != '-'
  3135. and '%' not in outtmpl
  3136. and self.params.get('max_downloads') != 1):
  3137. raise SameFileError(outtmpl)
  3138. for url in url_list:
  3139. self.__download_wrapper(self.extract_info)(
  3140. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  3141. return self._download_retcode
  3142. def download_with_info_file(self, info_filename):
  3143. with contextlib.closing(fileinput.FileInput(
  3144. [info_filename], mode='r',
  3145. openhook=fileinput.hook_encoded('utf-8'))) as f:
  3146. # FileInput doesn't have a read method, we can't call json.load
  3147. infos = [self.sanitize_info(info, self.params.get('clean_infojson', True))
  3148. for info in variadic(json.loads('\n'.join(f)))]
  3149. for info in infos:
  3150. try:
  3151. self.__download_wrapper(self.process_ie_result)(info, download=True)
  3152. except (DownloadError, EntryNotInPlaylist, ReExtractInfo) as e:
  3153. if not isinstance(e, EntryNotInPlaylist):
  3154. self.to_stderr('\r')
  3155. webpage_url = info.get('webpage_url')
  3156. if webpage_url is None:
  3157. raise
  3158. self.report_warning(f'The info failed to download: {e}; trying with URL {webpage_url}')
  3159. self.download([webpage_url])
  3160. return self._download_retcode
  3161. @staticmethod
  3162. def sanitize_info(info_dict, remove_private_keys=False):
  3163. ''' Sanitize the infodict for converting to json '''
  3164. if info_dict is None:
  3165. return info_dict
  3166. info_dict.setdefault('epoch', int(time.time()))
  3167. info_dict.setdefault('_type', 'video')
  3168. info_dict.setdefault('_version', {
  3169. 'version': __version__,
  3170. 'current_git_head': current_git_head(),
  3171. 'release_git_head': RELEASE_GIT_HEAD,
  3172. 'repository': REPOSITORY,
  3173. })
  3174. if remove_private_keys:
  3175. reject = lambda k, v: v is None or k.startswith('__') or k in {
  3176. 'requested_downloads', 'requested_formats', 'requested_subtitles', 'requested_entries',
  3177. 'entries', 'filepath', '_filename', 'filename', 'infojson_filename', 'original_url',
  3178. 'playlist_autonumber', '_format_sort_fields',
  3179. }
  3180. else:
  3181. reject = lambda k, v: False
  3182. def filter_fn(obj):
  3183. if isinstance(obj, dict):
  3184. return {k: filter_fn(v) for k, v in obj.items() if not reject(k, v)}
  3185. elif isinstance(obj, (list, tuple, set, LazyList)):
  3186. return list(map(filter_fn, obj))
  3187. elif obj is None or isinstance(obj, (str, int, float, bool)):
  3188. return obj
  3189. else:
  3190. return repr(obj)
  3191. return filter_fn(info_dict)
  3192. @staticmethod
  3193. def filter_requested_info(info_dict, actually_filter=True):
  3194. ''' Alias of sanitize_info for backward compatibility '''
  3195. return YoutubeDL.sanitize_info(info_dict, actually_filter)
  3196. def _delete_downloaded_files(self, *files_to_delete, info={}, msg=None):
  3197. for filename in set(filter(None, files_to_delete)):
  3198. if msg:
  3199. self.to_screen(msg % filename)
  3200. try:
  3201. os.remove(filename)
  3202. except OSError:
  3203. self.report_warning(f'Unable to delete file {filename}')
  3204. if filename in info.get('__files_to_move', []): # NB: Delete even if None
  3205. del info['__files_to_move'][filename]
  3206. @staticmethod
  3207. def post_extract(info_dict):
  3208. def actual_post_extract(info_dict):
  3209. if info_dict.get('_type') in ('playlist', 'multi_video'):
  3210. for video_dict in info_dict.get('entries', {}):
  3211. actual_post_extract(video_dict or {})
  3212. return
  3213. post_extractor = info_dict.pop('__post_extractor', None) or (lambda: {})
  3214. info_dict.update(post_extractor())
  3215. actual_post_extract(info_dict or {})
  3216. def run_pp(self, pp, infodict):
  3217. files_to_delete = []
  3218. if '__files_to_move' not in infodict:
  3219. infodict['__files_to_move'] = {}
  3220. try:
  3221. files_to_delete, infodict = pp.run(infodict)
  3222. except PostProcessingError as e:
  3223. # Must be True and not 'only_download'
  3224. if self.params.get('ignoreerrors') is True:
  3225. self.report_error(e)
  3226. return infodict
  3227. raise
  3228. if not files_to_delete:
  3229. return infodict
  3230. if self.params.get('keepvideo', False):
  3231. for f in files_to_delete:
  3232. infodict['__files_to_move'].setdefault(f, '')
  3233. else:
  3234. self._delete_downloaded_files(
  3235. *files_to_delete, info=infodict, msg='Deleting original file %s (pass -k to keep)')
  3236. return infodict
  3237. def run_all_pps(self, key, info, *, additional_pps=None):
  3238. if key != 'video':
  3239. self._forceprint(key, info)
  3240. for pp in (additional_pps or []) + self._pps[key]:
  3241. info = self.run_pp(pp, info)
  3242. return info
  3243. def pre_process(self, ie_info, key='pre_process', files_to_move=None):
  3244. info = dict(ie_info)
  3245. info['__files_to_move'] = files_to_move or {}
  3246. try:
  3247. info = self.run_all_pps(key, info)
  3248. except PostProcessingError as err:
  3249. msg = f'Preprocessing: {err}'
  3250. info.setdefault('__pending_error', msg)
  3251. self.report_error(msg, is_error=False)
  3252. return info, info.pop('__files_to_move', None)
  3253. def post_process(self, filename, info, files_to_move=None):
  3254. """Run all the postprocessors on the given file."""
  3255. info['filepath'] = filename
  3256. info['__files_to_move'] = files_to_move or {}
  3257. info = self.run_all_pps('post_process', info, additional_pps=info.get('__postprocessors'))
  3258. info = self.run_pp(MoveFilesAfterDownloadPP(self), info)
  3259. del info['__files_to_move']
  3260. return self.run_all_pps('after_move', info)
  3261. def _make_archive_id(self, info_dict):
  3262. video_id = info_dict.get('id')
  3263. if not video_id:
  3264. return
  3265. # Future-proof against any change in case
  3266. # and backwards compatibility with prior versions
  3267. extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
  3268. if extractor is None:
  3269. url = str_or_none(info_dict.get('url'))
  3270. if not url:
  3271. return
  3272. # Try to find matching extractor for the URL and take its ie_key
  3273. for ie_key, ie in self._ies.items():
  3274. if ie.suitable(url):
  3275. extractor = ie_key
  3276. break
  3277. else:
  3278. return
  3279. return make_archive_id(extractor, video_id)
  3280. def in_download_archive(self, info_dict):
  3281. if not self.archive:
  3282. return False
  3283. vid_ids = [self._make_archive_id(info_dict)]
  3284. vid_ids.extend(info_dict.get('_old_archive_ids') or [])
  3285. return any(id_ in self.archive for id_ in vid_ids)
  3286. def record_download_archive(self, info_dict):
  3287. fn = self.params.get('download_archive')
  3288. if fn is None:
  3289. return
  3290. vid_id = self._make_archive_id(info_dict)
  3291. assert vid_id
  3292. self.write_debug(f'Adding to archive: {vid_id}')
  3293. if is_path_like(fn):
  3294. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  3295. archive_file.write(vid_id + '\n')
  3296. self.archive.add(vid_id)
  3297. @staticmethod
  3298. def format_resolution(format, default='unknown'):
  3299. if format.get('vcodec') == 'none' and format.get('acodec') != 'none':
  3300. return 'audio only'
  3301. if format.get('resolution') is not None:
  3302. return format['resolution']
  3303. if format.get('width') and format.get('height'):
  3304. return '%dx%d' % (format['width'], format['height'])
  3305. elif format.get('height'):
  3306. return '%sp' % format['height']
  3307. elif format.get('width'):
  3308. return '%dx?' % format['width']
  3309. return default
  3310. def _list_format_headers(self, *headers):
  3311. if self.params.get('listformats_table', True) is not False:
  3312. return [self._format_out(header, self.Styles.HEADERS) for header in headers]
  3313. return headers
  3314. def _format_note(self, fdict):
  3315. res = ''
  3316. if fdict.get('ext') in ['f4f', 'f4m']:
  3317. res += '(unsupported)'
  3318. if fdict.get('language'):
  3319. if res:
  3320. res += ' '
  3321. res += '[%s]' % fdict['language']
  3322. if fdict.get('format_note') is not None:
  3323. if res:
  3324. res += ' '
  3325. res += fdict['format_note']
  3326. if fdict.get('tbr') is not None:
  3327. if res:
  3328. res += ', '
  3329. res += '%4dk' % fdict['tbr']
  3330. if fdict.get('container') is not None:
  3331. if res:
  3332. res += ', '
  3333. res += '%s container' % fdict['container']
  3334. if (fdict.get('vcodec') is not None
  3335. and fdict.get('vcodec') != 'none'):
  3336. if res:
  3337. res += ', '
  3338. res += fdict['vcodec']
  3339. if fdict.get('vbr') is not None:
  3340. res += '@'
  3341. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  3342. res += 'video@'
  3343. if fdict.get('vbr') is not None:
  3344. res += '%4dk' % fdict['vbr']
  3345. if fdict.get('fps') is not None:
  3346. if res:
  3347. res += ', '
  3348. res += '%sfps' % fdict['fps']
  3349. if fdict.get('acodec') is not None:
  3350. if res:
  3351. res += ', '
  3352. if fdict['acodec'] == 'none':
  3353. res += 'video only'
  3354. else:
  3355. res += '%-5s' % fdict['acodec']
  3356. elif fdict.get('abr') is not None:
  3357. if res:
  3358. res += ', '
  3359. res += 'audio'
  3360. if fdict.get('abr') is not None:
  3361. res += '@%3dk' % fdict['abr']
  3362. if fdict.get('asr') is not None:
  3363. res += ' (%5dHz)' % fdict['asr']
  3364. if fdict.get('filesize') is not None:
  3365. if res:
  3366. res += ', '
  3367. res += format_bytes(fdict['filesize'])
  3368. elif fdict.get('filesize_approx') is not None:
  3369. if res:
  3370. res += ', '
  3371. res += '~' + format_bytes(fdict['filesize_approx'])
  3372. return res
  3373. def _get_formats(self, info_dict):
  3374. if info_dict.get('formats') is None:
  3375. if info_dict.get('url') and info_dict.get('_type', 'video') == 'video':
  3376. return [info_dict]
  3377. return []
  3378. return info_dict['formats']
  3379. def render_formats_table(self, info_dict):
  3380. formats = self._get_formats(info_dict)
  3381. if not formats:
  3382. return
  3383. if not self.params.get('listformats_table', True) is not False:
  3384. table = [
  3385. [
  3386. format_field(f, 'format_id'),
  3387. format_field(f, 'ext'),
  3388. self.format_resolution(f),
  3389. self._format_note(f)
  3390. ] for f in formats if (f.get('preference') or 0) >= -1000]
  3391. return render_table(['format code', 'extension', 'resolution', 'note'], table, extra_gap=1)
  3392. def simplified_codec(f, field):
  3393. assert field in ('acodec', 'vcodec')
  3394. codec = f.get(field)
  3395. if not codec:
  3396. return 'unknown'
  3397. elif codec != 'none':
  3398. return '.'.join(codec.split('.')[:4])
  3399. if field == 'vcodec' and f.get('acodec') == 'none':
  3400. return 'images'
  3401. elif field == 'acodec' and f.get('vcodec') == 'none':
  3402. return ''
  3403. return self._format_out('audio only' if field == 'vcodec' else 'video only',
  3404. self.Styles.SUPPRESS)
  3405. delim = self._format_out('\u2502', self.Styles.DELIM, '|', test_encoding=True)
  3406. table = [
  3407. [
  3408. self._format_out(format_field(f, 'format_id'), self.Styles.ID),
  3409. format_field(f, 'ext'),
  3410. format_field(f, func=self.format_resolution, ignore=('audio only', 'images')),
  3411. format_field(f, 'fps', '\t%d', func=round),
  3412. format_field(f, 'dynamic_range', '%s', ignore=(None, 'SDR')).replace('HDR', ''),
  3413. format_field(f, 'audio_channels', '\t%s'),
  3414. delim, (
  3415. format_field(f, 'filesize', ' \t%s', func=format_bytes)
  3416. or format_field(f, 'filesize_approx', '≈\t%s', func=format_bytes)
  3417. or format_field(try_call(lambda: format_bytes(int(info_dict['duration'] * f['tbr'] * (1024 / 8)))),
  3418. None, self._format_out('~\t%s', self.Styles.SUPPRESS))),
  3419. format_field(f, 'tbr', '\t%dk', func=round),
  3420. shorten_protocol_name(f.get('protocol', '')),
  3421. delim,
  3422. simplified_codec(f, 'vcodec'),
  3423. format_field(f, 'vbr', '\t%dk', func=round),
  3424. simplified_codec(f, 'acodec'),
  3425. format_field(f, 'abr', '\t%dk', func=round),
  3426. format_field(f, 'asr', '\t%s', func=format_decimal_suffix),
  3427. join_nonempty(format_field(f, 'language', '[%s]'), join_nonempty(
  3428. self._format_out('UNSUPPORTED', self.Styles.BAD_FORMAT) if f.get('ext') in ('f4f', 'f4m') else None,
  3429. (self._format_out('Maybe DRM', self.Styles.WARNING) if f.get('has_drm') == 'maybe'
  3430. else self._format_out('DRM', self.Styles.BAD_FORMAT) if f.get('has_drm') else None),
  3431. format_field(f, 'format_note'),
  3432. format_field(f, 'container', ignore=(None, f.get('ext'))),
  3433. delim=', '), delim=' '),
  3434. ] for f in formats if f.get('preference') is None or f['preference'] >= -1000]
  3435. header_line = self._list_format_headers(
  3436. 'ID', 'EXT', 'RESOLUTION', '\tFPS', 'HDR', 'CH', delim, '\tFILESIZE', '\tTBR', 'PROTO',
  3437. delim, 'VCODEC', '\tVBR', 'ACODEC', '\tABR', '\tASR', 'MORE INFO')
  3438. return render_table(
  3439. header_line, table, hide_empty=True,
  3440. delim=self._format_out('\u2500', self.Styles.DELIM, '-', test_encoding=True))
  3441. def render_thumbnails_table(self, info_dict):
  3442. thumbnails = list(info_dict.get('thumbnails') or [])
  3443. if not thumbnails:
  3444. return None
  3445. return render_table(
  3446. self._list_format_headers('ID', 'Width', 'Height', 'URL'),
  3447. [[t.get('id'), t.get('width') or 'unknown', t.get('height') or 'unknown', t['url']] for t in thumbnails])
  3448. def render_subtitles_table(self, video_id, subtitles):
  3449. def _row(lang, formats):
  3450. exts, names = zip(*((f['ext'], f.get('name') or 'unknown') for f in reversed(formats)))
  3451. if len(set(names)) == 1:
  3452. names = [] if names[0] == 'unknown' else names[:1]
  3453. return [lang, ', '.join(names), ', '.join(exts)]
  3454. if not subtitles:
  3455. return None
  3456. return render_table(
  3457. self._list_format_headers('Language', 'Name', 'Formats'),
  3458. [_row(lang, formats) for lang, formats in subtitles.items()],
  3459. hide_empty=True)
  3460. def __list_table(self, video_id, name, func, *args):
  3461. table = func(*args)
  3462. if not table:
  3463. self.to_screen(f'{video_id} has no {name}')
  3464. return
  3465. self.to_screen(f'[info] Available {name} for {video_id}:')
  3466. self.to_stdout(table)
  3467. def list_formats(self, info_dict):
  3468. self.__list_table(info_dict['id'], 'formats', self.render_formats_table, info_dict)
  3469. def list_thumbnails(self, info_dict):
  3470. self.__list_table(info_dict['id'], 'thumbnails', self.render_thumbnails_table, info_dict)
  3471. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  3472. self.__list_table(video_id, name, self.render_subtitles_table, video_id, subtitles)
  3473. def print_debug_header(self):
  3474. if not self.params.get('verbose'):
  3475. return
  3476. from . import _IN_CLI # Must be delayed import
  3477. # These imports can be slow. So import them only as needed
  3478. from .extractor.extractors import _LAZY_LOADER
  3479. from .extractor.extractors import (
  3480. _PLUGIN_CLASSES as plugin_ies,
  3481. _PLUGIN_OVERRIDES as plugin_ie_overrides
  3482. )
  3483. def get_encoding(stream):
  3484. ret = str(getattr(stream, 'encoding', 'missing (%s)' % type(stream).__name__))
  3485. additional_info = []
  3486. if os.environ.get('TERM', '').lower() == 'dumb':
  3487. additional_info.append('dumb')
  3488. if not supports_terminal_sequences(stream):
  3489. from .utils import WINDOWS_VT_MODE # Must be imported locally
  3490. additional_info.append('No VT' if WINDOWS_VT_MODE is False else 'No ANSI')
  3491. if additional_info:
  3492. ret = f'{ret} ({",".join(additional_info)})'
  3493. return ret
  3494. encoding_str = 'Encodings: locale %s, fs %s, pref %s, %s' % (
  3495. locale.getpreferredencoding(),
  3496. sys.getfilesystemencoding(),
  3497. self.get_encoding(),
  3498. ', '.join(
  3499. f'{key} {get_encoding(stream)}' for key, stream in self._out_files.items_
  3500. if stream is not None and key != 'console')
  3501. )
  3502. logger = self.params.get('logger')
  3503. if logger:
  3504. write_debug = lambda msg: logger.debug(f'[debug] {msg}')
  3505. write_debug(encoding_str)
  3506. else:
  3507. write_string(f'[debug] {encoding_str}\n', encoding=None)
  3508. write_debug = lambda msg: self._write_string(f'[debug] {msg}\n')
  3509. source = detect_variant()
  3510. if VARIANT not in (None, 'pip'):
  3511. source += '*'
  3512. klass = type(self)
  3513. write_debug(join_nonempty(
  3514. f'{"yt-dlp" if REPOSITORY == "yt-dlp/yt-dlp" else REPOSITORY} version',
  3515. f'{CHANNEL}@{__version__}',
  3516. f'[{RELEASE_GIT_HEAD[:9]}]' if RELEASE_GIT_HEAD else '',
  3517. '' if source == 'unknown' else f'({source})',
  3518. '' if _IN_CLI else 'API' if klass == YoutubeDL else f'API:{self.__module__}.{klass.__qualname__}',
  3519. delim=' '))
  3520. if not _IN_CLI:
  3521. write_debug(f'params: {self.params}')
  3522. if not _LAZY_LOADER:
  3523. if os.environ.get('YTDLP_NO_LAZY_EXTRACTORS'):
  3524. write_debug('Lazy loading extractors is forcibly disabled')
  3525. else:
  3526. write_debug('Lazy loading extractors is disabled')
  3527. if self.params['compat_opts']:
  3528. write_debug('Compatibility options: %s' % ', '.join(self.params['compat_opts']))
  3529. if current_git_head():
  3530. write_debug(f'Git HEAD: {current_git_head()}')
  3531. write_debug(system_identifier())
  3532. exe_versions, ffmpeg_features = FFmpegPostProcessor.get_versions_and_features(self)
  3533. ffmpeg_features = {key for key, val in ffmpeg_features.items() if val}
  3534. if ffmpeg_features:
  3535. exe_versions['ffmpeg'] += ' (%s)' % ','.join(sorted(ffmpeg_features))
  3536. exe_versions['rtmpdump'] = rtmpdump_version()
  3537. exe_versions['phantomjs'] = PhantomJSwrapper._version()
  3538. exe_str = ', '.join(
  3539. f'{exe} {v}' for exe, v in sorted(exe_versions.items()) if v
  3540. ) or 'none'
  3541. write_debug('exe versions: %s' % exe_str)
  3542. from .compat.compat_utils import get_package_info
  3543. from .dependencies import available_dependencies
  3544. write_debug('Optional libraries: %s' % (', '.join(sorted({
  3545. join_nonempty(*get_package_info(m)) for m in available_dependencies.values()
  3546. })) or 'none'))
  3547. write_debug(f'Proxy map: {self.proxies}')
  3548. # write_debug(f'Request Handlers: {", ".join(rh.RH_NAME for rh in self._request_director.handlers)}')
  3549. for plugin_type, plugins in {'Extractor': plugin_ies, 'Post-Processor': plugin_pps}.items():
  3550. display_list = ['%s%s' % (
  3551. klass.__name__, '' if klass.__name__ == name else f' as {name}')
  3552. for name, klass in plugins.items()]
  3553. if plugin_type == 'Extractor':
  3554. display_list.extend(f'{plugins[-1].IE_NAME.partition("+")[2]} ({parent.__name__})'
  3555. for parent, plugins in plugin_ie_overrides.items())
  3556. if not display_list:
  3557. continue
  3558. write_debug(f'{plugin_type} Plugins: {", ".join(sorted(display_list))}')
  3559. plugin_dirs = plugin_directories()
  3560. if plugin_dirs:
  3561. write_debug(f'Plugin directories: {plugin_dirs}')
  3562. # Not implemented
  3563. if False and self.params.get('call_home'):
  3564. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode()
  3565. write_debug('Public IP address: %s' % ipaddr)
  3566. latest_version = self.urlopen(
  3567. 'https://yt-dl.org/latest/version').read().decode()
  3568. if version_tuple(latest_version) > version_tuple(__version__):
  3569. self.report_warning(
  3570. 'You are using an outdated version (newest version: %s)! '
  3571. 'See https://yt-dl.org/update if you need help updating.' %
  3572. latest_version)
  3573. @functools.cached_property
  3574. def proxies(self):
  3575. """Global proxy configuration"""
  3576. opts_proxy = self.params.get('proxy')
  3577. if opts_proxy is not None:
  3578. if opts_proxy == '':
  3579. opts_proxy = '__noproxy__'
  3580. proxies = {'all': opts_proxy}
  3581. else:
  3582. proxies = urllib.request.getproxies()
  3583. # compat. Set HTTPS_PROXY to __noproxy__ to revert
  3584. if 'http' in proxies and 'https' not in proxies:
  3585. proxies['https'] = proxies['http']
  3586. return proxies
  3587. @functools.cached_property
  3588. def cookiejar(self):
  3589. """Global cookiejar instance"""
  3590. return load_cookies(
  3591. self.params.get('cookiefile'), self.params.get('cookiesfrombrowser'), self)
  3592. @property
  3593. def _opener(self):
  3594. """
  3595. Get a urllib OpenerDirector from the Urllib handler (deprecated).
  3596. """
  3597. self.deprecation_warning('YoutubeDL._opener() is deprecated, use YoutubeDL.urlopen()')
  3598. handler = self._request_director.handlers['Urllib']
  3599. return handler._get_instance(cookiejar=self.cookiejar, proxies=self.proxies)
  3600. def urlopen(self, req):
  3601. """ Start an HTTP download """
  3602. if isinstance(req, str):
  3603. req = Request(req)
  3604. elif isinstance(req, urllib.request.Request):
  3605. self.deprecation_warning(
  3606. 'Passing a urllib.request.Request object to YoutubeDL.urlopen() is deprecated. '
  3607. 'Use yt_dlp.networking.common.Request instead.')
  3608. req = urllib_req_to_req(req)
  3609. assert isinstance(req, Request)
  3610. # compat: Assume user:pass url params are basic auth
  3611. url, basic_auth_header = extract_basic_auth(req.url)
  3612. if basic_auth_header:
  3613. req.headers['Authorization'] = basic_auth_header
  3614. req.url = sanitize_url(url)
  3615. clean_proxies(proxies=req.proxies, headers=req.headers)
  3616. clean_headers(req.headers)
  3617. try:
  3618. return self._request_director.send(req)
  3619. except NoSupportingHandlers as e:
  3620. for ue in e.unsupported_errors:
  3621. if not (ue.handler and ue.msg):
  3622. continue
  3623. if ue.handler.RH_KEY == 'Urllib' and 'unsupported url scheme: "file"' in ue.msg.lower():
  3624. raise RequestError(
  3625. 'file:// URLs are disabled by default in yt-dlp for security reasons. '
  3626. 'Use --enable-file-urls to enable at your own risk.', cause=ue) from ue
  3627. raise
  3628. except SSLError as e:
  3629. if 'UNSAFE_LEGACY_RENEGOTIATION_DISABLED' in str(e):
  3630. raise RequestError('UNSAFE_LEGACY_RENEGOTIATION_DISABLED: Try using --legacy-server-connect', cause=e) from e
  3631. elif 'SSLV3_ALERT_HANDSHAKE_FAILURE' in str(e):
  3632. raise RequestError(
  3633. 'SSLV3_ALERT_HANDSHAKE_FAILURE: The server may not support the current cipher list. '
  3634. 'Try using --legacy-server-connect', cause=e) from e
  3635. raise
  3636. except HTTPError as e: # TODO: Remove in a future release
  3637. raise _CompatHTTPError(e) from e
  3638. def build_request_director(self, handlers):
  3639. logger = _YDLLogger(self)
  3640. headers = self.params.get('http_headers').copy()
  3641. proxies = self.proxies.copy()
  3642. clean_headers(headers)
  3643. clean_proxies(proxies, headers)
  3644. director = RequestDirector(logger=logger, verbose=self.params.get('debug_printtraffic'))
  3645. for handler in handlers:
  3646. director.add_handler(handler(
  3647. logger=logger,
  3648. headers=headers,
  3649. cookiejar=self.cookiejar,
  3650. proxies=proxies,
  3651. prefer_system_certs='no-certifi' in self.params['compat_opts'],
  3652. verify=not self.params.get('nocheckcertificate'),
  3653. **traverse_obj(self.params, {
  3654. 'verbose': 'debug_printtraffic',
  3655. 'source_address': 'source_address',
  3656. 'timeout': 'socket_timeout',
  3657. 'legacy_ssl_support': 'legacy_server_connect',
  3658. 'enable_file_urls': 'enable_file_urls',
  3659. 'client_cert': {
  3660. 'client_certificate': 'client_certificate',
  3661. 'client_certificate_key': 'client_certificate_key',
  3662. 'client_certificate_password': 'client_certificate_password',
  3663. },
  3664. }),
  3665. ))
  3666. return director
  3667. def encode(self, s):
  3668. if isinstance(s, bytes):
  3669. return s # Already encoded
  3670. try:
  3671. return s.encode(self.get_encoding())
  3672. except UnicodeEncodeError as err:
  3673. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  3674. raise
  3675. def get_encoding(self):
  3676. encoding = self.params.get('encoding')
  3677. if encoding is None:
  3678. encoding = preferredencoding()
  3679. return encoding
  3680. def _write_info_json(self, label, ie_result, infofn, overwrite=None):
  3681. ''' Write infojson and returns True = written, 'exists' = Already exists, False = skip, None = error '''
  3682. if overwrite is None:
  3683. overwrite = self.params.get('overwrites', True)
  3684. if not self.params.get('writeinfojson'):
  3685. return False
  3686. elif not infofn:
  3687. self.write_debug(f'Skipping writing {label} infojson')
  3688. return False
  3689. elif not self._ensure_dir_exists(infofn):
  3690. return None
  3691. elif not overwrite and os.path.exists(infofn):
  3692. self.to_screen(f'[info] {label.title()} metadata is already present')
  3693. return 'exists'
  3694. self.to_screen(f'[info] Writing {label} metadata as JSON to: {infofn}')
  3695. try:
  3696. write_json_file(self.sanitize_info(ie_result, self.params.get('clean_infojson', True)), infofn)
  3697. return True
  3698. except OSError:
  3699. self.report_error(f'Cannot write {label} metadata to JSON file {infofn}')
  3700. return None
  3701. def _write_description(self, label, ie_result, descfn):
  3702. ''' Write description and returns True = written, False = skip, None = error '''
  3703. if not self.params.get('writedescription'):
  3704. return False
  3705. elif not descfn:
  3706. self.write_debug(f'Skipping writing {label} description')
  3707. return False
  3708. elif not self._ensure_dir_exists(descfn):
  3709. return None
  3710. elif not self.params.get('overwrites', True) and os.path.exists(descfn):
  3711. self.to_screen(f'[info] {label.title()} description is already present')
  3712. elif ie_result.get('description') is None:
  3713. self.to_screen(f'[info] There\'s no {label} description to write')
  3714. return False
  3715. else:
  3716. try:
  3717. self.to_screen(f'[info] Writing {label} description to: {descfn}')
  3718. with open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  3719. descfile.write(ie_result['description'])
  3720. except OSError:
  3721. self.report_error(f'Cannot write {label} description file {descfn}')
  3722. return None
  3723. return True
  3724. def _write_subtitles(self, info_dict, filename):
  3725. ''' Write subtitles to file and return list of (sub_filename, final_sub_filename); or None if error'''
  3726. ret = []
  3727. subtitles = info_dict.get('requested_subtitles')
  3728. if not (self.params.get('writesubtitles') or self.params.get('writeautomaticsub')):
  3729. # subtitles download errors are already managed as troubles in relevant IE
  3730. # that way it will silently go on when used with unsupporting IE
  3731. return ret
  3732. elif not subtitles:
  3733. self.to_screen('[info] There are no subtitles for the requested languages')
  3734. return ret
  3735. sub_filename_base = self.prepare_filename(info_dict, 'subtitle')
  3736. if not sub_filename_base:
  3737. self.to_screen('[info] Skipping writing video subtitles')
  3738. return ret
  3739. for sub_lang, sub_info in subtitles.items():
  3740. sub_format = sub_info['ext']
  3741. sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
  3742. sub_filename_final = subtitles_filename(sub_filename_base, sub_lang, sub_format, info_dict.get('ext'))
  3743. existing_sub = self.existing_file((sub_filename_final, sub_filename))
  3744. if existing_sub:
  3745. self.to_screen(f'[info] Video subtitle {sub_lang}.{sub_format} is already present')
  3746. sub_info['filepath'] = existing_sub
  3747. ret.append((existing_sub, sub_filename_final))
  3748. continue
  3749. self.to_screen(f'[info] Writing video subtitles to: {sub_filename}')
  3750. if sub_info.get('data') is not None:
  3751. try:
  3752. # Use newline='' to prevent conversion of newline characters
  3753. # See https://github.com/ytdl-org/youtube-dl/issues/10268
  3754. with open(sub_filename, 'w', encoding='utf-8', newline='') as subfile:
  3755. subfile.write(sub_info['data'])
  3756. sub_info['filepath'] = sub_filename
  3757. ret.append((sub_filename, sub_filename_final))
  3758. continue
  3759. except OSError:
  3760. self.report_error(f'Cannot write video subtitles file {sub_filename}')
  3761. return None
  3762. try:
  3763. sub_copy = sub_info.copy()
  3764. sub_copy.setdefault('http_headers', info_dict.get('http_headers'))
  3765. self.dl(sub_filename, sub_copy, subtitle=True)
  3766. sub_info['filepath'] = sub_filename
  3767. ret.append((sub_filename, sub_filename_final))
  3768. except (DownloadError, ExtractorError, IOError, OSError, ValueError) + network_exceptions as err:
  3769. msg = f'Unable to download video subtitles for {sub_lang!r}: {err}'
  3770. if self.params.get('ignoreerrors') is not True: # False or 'only_download'
  3771. if not self.params.get('ignoreerrors'):
  3772. self.report_error(msg)
  3773. raise DownloadError(msg)
  3774. self.report_warning(msg)
  3775. return ret
  3776. def _write_thumbnails(self, label, info_dict, filename, thumb_filename_base=None):
  3777. ''' Write thumbnails to file and return list of (thumb_filename, final_thumb_filename) '''
  3778. write_all = self.params.get('write_all_thumbnails', False)
  3779. thumbnails, ret = [], []
  3780. if write_all or self.params.get('writethumbnail', False):
  3781. thumbnails = info_dict.get('thumbnails') or []
  3782. if not thumbnails:
  3783. self.to_screen(f'[info] There are no {label} thumbnails to download')
  3784. return ret
  3785. multiple = write_all and len(thumbnails) > 1
  3786. if thumb_filename_base is None:
  3787. thumb_filename_base = filename
  3788. if thumbnails and not thumb_filename_base:
  3789. self.write_debug(f'Skipping writing {label} thumbnail')
  3790. return ret
  3791. for idx, t in list(enumerate(thumbnails))[::-1]:
  3792. thumb_ext = (f'{t["id"]}.' if multiple else '') + determine_ext(t['url'], 'jpg')
  3793. thumb_display_id = f'{label} thumbnail {t["id"]}'
  3794. thumb_filename = replace_extension(filename, thumb_ext, info_dict.get('ext'))
  3795. thumb_filename_final = replace_extension(thumb_filename_base, thumb_ext, info_dict.get('ext'))
  3796. existing_thumb = self.existing_file((thumb_filename_final, thumb_filename))
  3797. if existing_thumb:
  3798. self.to_screen('[info] %s is already present' % (
  3799. thumb_display_id if multiple else f'{label} thumbnail').capitalize())
  3800. t['filepath'] = existing_thumb
  3801. ret.append((existing_thumb, thumb_filename_final))
  3802. else:
  3803. self.to_screen(f'[info] Downloading {thumb_display_id} ...')
  3804. try:
  3805. uf = self.urlopen(Request(t['url'], headers=t.get('http_headers', {})))
  3806. self.to_screen(f'[info] Writing {thumb_display_id} to: {thumb_filename}')
  3807. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  3808. shutil.copyfileobj(uf, thumbf)
  3809. ret.append((thumb_filename, thumb_filename_final))
  3810. t['filepath'] = thumb_filename
  3811. except network_exceptions as err:
  3812. if isinstance(err, HTTPError) and err.status == 404:
  3813. self.to_screen(f'[info] {thumb_display_id.title()} does not exist')
  3814. else:
  3815. self.report_warning(f'Unable to download {thumb_display_id}: {err}')
  3816. thumbnails.pop(idx)
  3817. if ret and not write_all:
  3818. break
  3819. return ret