YoutubeDL.py 206 KB

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