utils.py 182 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652
  1. import asyncio
  2. import atexit
  3. import base64
  4. import binascii
  5. import calendar
  6. import codecs
  7. import collections
  8. import contextlib
  9. import ctypes
  10. import datetime
  11. import email.header
  12. import email.utils
  13. import errno
  14. import gzip
  15. import hashlib
  16. import hmac
  17. import html.entities
  18. import html.parser
  19. import http.client
  20. import http.cookiejar
  21. import importlib.util
  22. import inspect
  23. import io
  24. import itertools
  25. import json
  26. import locale
  27. import math
  28. import mimetypes
  29. import operator
  30. import os
  31. import platform
  32. import random
  33. import re
  34. import shlex
  35. import socket
  36. import ssl
  37. import struct
  38. import subprocess
  39. import sys
  40. import tempfile
  41. import time
  42. import traceback
  43. import types
  44. import urllib.error
  45. import urllib.parse
  46. import urllib.request
  47. import xml.etree.ElementTree
  48. import zlib
  49. from .compat import functools # isort: split
  50. from .compat import (
  51. compat_etree_fromstring,
  52. compat_expanduser,
  53. compat_HTMLParseError,
  54. compat_os_name,
  55. compat_shlex_quote,
  56. )
  57. from .dependencies import brotli, certifi, websockets, xattr
  58. from .socks import ProxyType, sockssocket
  59. def register_socks_protocols():
  60. # "Register" SOCKS protocols
  61. # In Python < 2.6.5, urlsplit() suffers from bug https://bugs.python.org/issue7904
  62. # URLs with protocols not in urlparse.uses_netloc are not handled correctly
  63. for scheme in ('socks', 'socks4', 'socks4a', 'socks5'):
  64. if scheme not in urllib.parse.uses_netloc:
  65. urllib.parse.uses_netloc.append(scheme)
  66. # This is not clearly defined otherwise
  67. compiled_regex_type = type(re.compile(''))
  68. def random_user_agent():
  69. _USER_AGENT_TPL = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'
  70. _CHROME_VERSIONS = (
  71. '90.0.4430.212',
  72. '90.0.4430.24',
  73. '90.0.4430.70',
  74. '90.0.4430.72',
  75. '90.0.4430.85',
  76. '90.0.4430.93',
  77. '91.0.4472.101',
  78. '91.0.4472.106',
  79. '91.0.4472.114',
  80. '91.0.4472.124',
  81. '91.0.4472.164',
  82. '91.0.4472.19',
  83. '91.0.4472.77',
  84. '92.0.4515.107',
  85. '92.0.4515.115',
  86. '92.0.4515.131',
  87. '92.0.4515.159',
  88. '92.0.4515.43',
  89. '93.0.4556.0',
  90. '93.0.4577.15',
  91. '93.0.4577.63',
  92. '93.0.4577.82',
  93. '94.0.4606.41',
  94. '94.0.4606.54',
  95. '94.0.4606.61',
  96. '94.0.4606.71',
  97. '94.0.4606.81',
  98. '94.0.4606.85',
  99. '95.0.4638.17',
  100. '95.0.4638.50',
  101. '95.0.4638.54',
  102. '95.0.4638.69',
  103. '95.0.4638.74',
  104. '96.0.4664.18',
  105. '96.0.4664.45',
  106. '96.0.4664.55',
  107. '96.0.4664.93',
  108. '97.0.4692.20',
  109. )
  110. return _USER_AGENT_TPL % random.choice(_CHROME_VERSIONS)
  111. SUPPORTED_ENCODINGS = [
  112. 'gzip', 'deflate'
  113. ]
  114. if brotli:
  115. SUPPORTED_ENCODINGS.append('br')
  116. std_headers = {
  117. 'User-Agent': random_user_agent(),
  118. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  119. 'Accept-Language': 'en-us,en;q=0.5',
  120. 'Sec-Fetch-Mode': 'navigate',
  121. }
  122. USER_AGENTS = {
  123. 'Safari': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
  124. }
  125. NO_DEFAULT = object()
  126. IDENTITY = lambda x: x
  127. ENGLISH_MONTH_NAMES = [
  128. 'January', 'February', 'March', 'April', 'May', 'June',
  129. 'July', 'August', 'September', 'October', 'November', 'December']
  130. MONTH_NAMES = {
  131. 'en': ENGLISH_MONTH_NAMES,
  132. 'fr': [
  133. 'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
  134. 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
  135. }
  136. KNOWN_EXTENSIONS = (
  137. 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'aac',
  138. 'flv', 'f4v', 'f4a', 'f4b',
  139. 'webm', 'ogg', 'ogv', 'oga', 'ogx', 'spx', 'opus',
  140. 'mkv', 'mka', 'mk3d',
  141. 'avi', 'divx',
  142. 'mov',
  143. 'asf', 'wmv', 'wma',
  144. '3gp', '3g2',
  145. 'mp3',
  146. 'mpg',
  147. 'flac',
  148. 'ape',
  149. 'wav',
  150. 'f4f', 'f4m', 'm3u8', 'smil')
  151. # needed for sanitizing filenames in restricted mode
  152. ACCENT_CHARS = dict(zip('ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ',
  153. itertools.chain('AAAAAA', ['AE'], 'CEEEEIIIIDNOOOOOOO', ['OE'], 'UUUUUY', ['TH', 'ss'],
  154. 'aaaaaa', ['ae'], 'ceeeeiiiionooooooo', ['oe'], 'uuuuuy', ['th'], 'y')))
  155. DATE_FORMATS = (
  156. '%d %B %Y',
  157. '%d %b %Y',
  158. '%B %d %Y',
  159. '%B %dst %Y',
  160. '%B %dnd %Y',
  161. '%B %drd %Y',
  162. '%B %dth %Y',
  163. '%b %d %Y',
  164. '%b %dst %Y',
  165. '%b %dnd %Y',
  166. '%b %drd %Y',
  167. '%b %dth %Y',
  168. '%b %dst %Y %I:%M',
  169. '%b %dnd %Y %I:%M',
  170. '%b %drd %Y %I:%M',
  171. '%b %dth %Y %I:%M',
  172. '%Y %m %d',
  173. '%Y-%m-%d',
  174. '%Y.%m.%d.',
  175. '%Y/%m/%d',
  176. '%Y/%m/%d %H:%M',
  177. '%Y/%m/%d %H:%M:%S',
  178. '%Y%m%d%H%M',
  179. '%Y%m%d%H%M%S',
  180. '%Y%m%d',
  181. '%Y-%m-%d %H:%M',
  182. '%Y-%m-%d %H:%M:%S',
  183. '%Y-%m-%d %H:%M:%S.%f',
  184. '%Y-%m-%d %H:%M:%S:%f',
  185. '%d.%m.%Y %H:%M',
  186. '%d.%m.%Y %H.%M',
  187. '%Y-%m-%dT%H:%M:%SZ',
  188. '%Y-%m-%dT%H:%M:%S.%fZ',
  189. '%Y-%m-%dT%H:%M:%S.%f0Z',
  190. '%Y-%m-%dT%H:%M:%S',
  191. '%Y-%m-%dT%H:%M:%S.%f',
  192. '%Y-%m-%dT%H:%M',
  193. '%b %d %Y at %H:%M',
  194. '%b %d %Y at %H:%M:%S',
  195. '%B %d %Y at %H:%M',
  196. '%B %d %Y at %H:%M:%S',
  197. '%H:%M %d-%b-%Y',
  198. )
  199. DATE_FORMATS_DAY_FIRST = list(DATE_FORMATS)
  200. DATE_FORMATS_DAY_FIRST.extend([
  201. '%d-%m-%Y',
  202. '%d.%m.%Y',
  203. '%d.%m.%y',
  204. '%d/%m/%Y',
  205. '%d/%m/%y',
  206. '%d/%m/%Y %H:%M:%S',
  207. ])
  208. DATE_FORMATS_MONTH_FIRST = list(DATE_FORMATS)
  209. DATE_FORMATS_MONTH_FIRST.extend([
  210. '%m-%d-%Y',
  211. '%m.%d.%Y',
  212. '%m/%d/%Y',
  213. '%m/%d/%y',
  214. '%m/%d/%Y %H:%M:%S',
  215. ])
  216. PACKED_CODES_RE = r"}\('(.+)',(\d+),(\d+),'([^']+)'\.split\('\|'\)"
  217. JSON_LD_RE = r'(?is)<script[^>]+type=(["\']?)application/ld\+json\1[^>]*>\s*(?P<json_ld>{.+?})\s*</script>'
  218. NUMBER_RE = r'\d+(?:\.\d+)?'
  219. @functools.cache
  220. def preferredencoding():
  221. """Get preferred encoding.
  222. Returns the best encoding scheme for the system, based on
  223. locale.getpreferredencoding() and some further tweaks.
  224. """
  225. try:
  226. pref = locale.getpreferredencoding()
  227. 'TEST'.encode(pref)
  228. except Exception:
  229. pref = 'UTF-8'
  230. return pref
  231. def write_json_file(obj, fn):
  232. """ Encode obj as JSON and write it to fn, atomically if possible """
  233. tf = tempfile.NamedTemporaryFile(
  234. prefix=f'{os.path.basename(fn)}.', dir=os.path.dirname(fn),
  235. suffix='.tmp', delete=False, mode='w', encoding='utf-8')
  236. try:
  237. with tf:
  238. json.dump(obj, tf, ensure_ascii=False)
  239. if sys.platform == 'win32':
  240. # Need to remove existing file on Windows, else os.rename raises
  241. # WindowsError or FileExistsError.
  242. with contextlib.suppress(OSError):
  243. os.unlink(fn)
  244. with contextlib.suppress(OSError):
  245. mask = os.umask(0)
  246. os.umask(mask)
  247. os.chmod(tf.name, 0o666 & ~mask)
  248. os.rename(tf.name, fn)
  249. except Exception:
  250. with contextlib.suppress(OSError):
  251. os.remove(tf.name)
  252. raise
  253. def find_xpath_attr(node, xpath, key, val=None):
  254. """ Find the xpath xpath[@key=val] """
  255. assert re.match(r'^[a-zA-Z_-]+$', key)
  256. expr = xpath + ('[@%s]' % key if val is None else f"[@{key}='{val}']")
  257. return node.find(expr)
  258. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  259. # the namespace parameter
  260. def xpath_with_ns(path, ns_map):
  261. components = [c.split(':') for c in path.split('/')]
  262. replaced = []
  263. for c in components:
  264. if len(c) == 1:
  265. replaced.append(c[0])
  266. else:
  267. ns, tag = c
  268. replaced.append('{%s}%s' % (ns_map[ns], tag))
  269. return '/'.join(replaced)
  270. def xpath_element(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  271. def _find_xpath(xpath):
  272. return node.find(xpath)
  273. if isinstance(xpath, str):
  274. n = _find_xpath(xpath)
  275. else:
  276. for xp in xpath:
  277. n = _find_xpath(xp)
  278. if n is not None:
  279. break
  280. if n is None:
  281. if default is not NO_DEFAULT:
  282. return default
  283. elif fatal:
  284. name = xpath if name is None else name
  285. raise ExtractorError('Could not find XML element %s' % name)
  286. else:
  287. return None
  288. return n
  289. def xpath_text(node, xpath, name=None, fatal=False, default=NO_DEFAULT):
  290. n = xpath_element(node, xpath, name, fatal=fatal, default=default)
  291. if n is None or n == default:
  292. return n
  293. if n.text is None:
  294. if default is not NO_DEFAULT:
  295. return default
  296. elif fatal:
  297. name = xpath if name is None else name
  298. raise ExtractorError('Could not find XML element\'s text %s' % name)
  299. else:
  300. return None
  301. return n.text
  302. def xpath_attr(node, xpath, key, name=None, fatal=False, default=NO_DEFAULT):
  303. n = find_xpath_attr(node, xpath, key)
  304. if n is None:
  305. if default is not NO_DEFAULT:
  306. return default
  307. elif fatal:
  308. name = f'{xpath}[@{key}]' if name is None else name
  309. raise ExtractorError('Could not find XML attribute %s' % name)
  310. else:
  311. return None
  312. return n.attrib[key]
  313. def get_element_by_id(id, html, **kwargs):
  314. """Return the content of the tag with the specified ID in the passed HTML document"""
  315. return get_element_by_attribute('id', id, html, **kwargs)
  316. def get_element_html_by_id(id, html, **kwargs):
  317. """Return the html of the tag with the specified ID in the passed HTML document"""
  318. return get_element_html_by_attribute('id', id, html, **kwargs)
  319. def get_element_by_class(class_name, html):
  320. """Return the content of the first tag with the specified class in the passed HTML document"""
  321. retval = get_elements_by_class(class_name, html)
  322. return retval[0] if retval else None
  323. def get_element_html_by_class(class_name, html):
  324. """Return the html of the first tag with the specified class in the passed HTML document"""
  325. retval = get_elements_html_by_class(class_name, html)
  326. return retval[0] if retval else None
  327. def get_element_by_attribute(attribute, value, html, **kwargs):
  328. retval = get_elements_by_attribute(attribute, value, html, **kwargs)
  329. return retval[0] if retval else None
  330. def get_element_html_by_attribute(attribute, value, html, **kargs):
  331. retval = get_elements_html_by_attribute(attribute, value, html, **kargs)
  332. return retval[0] if retval else None
  333. def get_elements_by_class(class_name, html, **kargs):
  334. """Return the content of all tags with the specified class in the passed HTML document as a list"""
  335. return get_elements_by_attribute(
  336. 'class', r'[^\'"]*(?<=[\'"\s])%s(?=[\'"\s])[^\'"]*' % re.escape(class_name),
  337. html, escape_value=False)
  338. def get_elements_html_by_class(class_name, html):
  339. """Return the html of all tags with the specified class in the passed HTML document as a list"""
  340. return get_elements_html_by_attribute(
  341. 'class', r'[^\'"]*(?<=[\'"\s])%s(?=[\'"\s])[^\'"]*' % re.escape(class_name),
  342. html, escape_value=False)
  343. def get_elements_by_attribute(*args, **kwargs):
  344. """Return the content of the tag with the specified attribute in the passed HTML document"""
  345. return [content for content, _ in get_elements_text_and_html_by_attribute(*args, **kwargs)]
  346. def get_elements_html_by_attribute(*args, **kwargs):
  347. """Return the html of the tag with the specified attribute in the passed HTML document"""
  348. return [whole for _, whole in get_elements_text_and_html_by_attribute(*args, **kwargs)]
  349. def get_elements_text_and_html_by_attribute(attribute, value, html, escape_value=True):
  350. """
  351. Return the text (content) and the html (whole) of the tag with the specified
  352. attribute in the passed HTML document
  353. """
  354. quote = '' if re.match(r'''[\s"'`=<>]''', value) else '?'
  355. value = re.escape(value) if escape_value else value
  356. partial_element_re = rf'''(?x)
  357. <(?P<tag>[a-zA-Z0-9:._-]+)
  358. (?:\s(?:[^>"']|"[^"]*"|'[^']*')*)?
  359. \s{re.escape(attribute)}\s*=\s*(?P<_q>['"]{quote})(?-x:{value})(?P=_q)
  360. '''
  361. for m in re.finditer(partial_element_re, html):
  362. content, whole = get_element_text_and_html_by_tag(m.group('tag'), html[m.start():])
  363. yield (
  364. unescapeHTML(re.sub(r'^(?P<q>["\'])(?P<content>.*)(?P=q)$', r'\g<content>', content, flags=re.DOTALL)),
  365. whole
  366. )
  367. class HTMLBreakOnClosingTagParser(html.parser.HTMLParser):
  368. """
  369. HTML parser which raises HTMLBreakOnClosingTagException upon reaching the
  370. closing tag for the first opening tag it has encountered, and can be used
  371. as a context manager
  372. """
  373. class HTMLBreakOnClosingTagException(Exception):
  374. pass
  375. def __init__(self):
  376. self.tagstack = collections.deque()
  377. html.parser.HTMLParser.__init__(self)
  378. def __enter__(self):
  379. return self
  380. def __exit__(self, *_):
  381. self.close()
  382. def close(self):
  383. # handle_endtag does not return upon raising HTMLBreakOnClosingTagException,
  384. # so data remains buffered; we no longer have any interest in it, thus
  385. # override this method to discard it
  386. pass
  387. def handle_starttag(self, tag, _):
  388. self.tagstack.append(tag)
  389. def handle_endtag(self, tag):
  390. if not self.tagstack:
  391. raise compat_HTMLParseError('no tags in the stack')
  392. while self.tagstack:
  393. inner_tag = self.tagstack.pop()
  394. if inner_tag == tag:
  395. break
  396. else:
  397. raise compat_HTMLParseError(f'matching opening tag for closing {tag} tag not found')
  398. if not self.tagstack:
  399. raise self.HTMLBreakOnClosingTagException()
  400. def get_element_text_and_html_by_tag(tag, html):
  401. """
  402. For the first element with the specified tag in the passed HTML document
  403. return its' content (text) and the whole element (html)
  404. """
  405. def find_or_raise(haystack, needle, exc):
  406. try:
  407. return haystack.index(needle)
  408. except ValueError:
  409. raise exc
  410. closing_tag = f'</{tag}>'
  411. whole_start = find_or_raise(
  412. html, f'<{tag}', compat_HTMLParseError(f'opening {tag} tag not found'))
  413. content_start = find_or_raise(
  414. html[whole_start:], '>', compat_HTMLParseError(f'malformed opening {tag} tag'))
  415. content_start += whole_start + 1
  416. with HTMLBreakOnClosingTagParser() as parser:
  417. parser.feed(html[whole_start:content_start])
  418. if not parser.tagstack or parser.tagstack[0] != tag:
  419. raise compat_HTMLParseError(f'parser did not match opening {tag} tag')
  420. offset = content_start
  421. while offset < len(html):
  422. next_closing_tag_start = find_or_raise(
  423. html[offset:], closing_tag,
  424. compat_HTMLParseError(f'closing {tag} tag not found'))
  425. next_closing_tag_end = next_closing_tag_start + len(closing_tag)
  426. try:
  427. parser.feed(html[offset:offset + next_closing_tag_end])
  428. offset += next_closing_tag_end
  429. except HTMLBreakOnClosingTagParser.HTMLBreakOnClosingTagException:
  430. return html[content_start:offset + next_closing_tag_start], \
  431. html[whole_start:offset + next_closing_tag_end]
  432. raise compat_HTMLParseError('unexpected end of html')
  433. class HTMLAttributeParser(html.parser.HTMLParser):
  434. """Trivial HTML parser to gather the attributes for a single element"""
  435. def __init__(self):
  436. self.attrs = {}
  437. html.parser.HTMLParser.__init__(self)
  438. def handle_starttag(self, tag, attrs):
  439. self.attrs = dict(attrs)
  440. class HTMLListAttrsParser(html.parser.HTMLParser):
  441. """HTML parser to gather the attributes for the elements of a list"""
  442. def __init__(self):
  443. html.parser.HTMLParser.__init__(self)
  444. self.items = []
  445. self._level = 0
  446. def handle_starttag(self, tag, attrs):
  447. if tag == 'li' and self._level == 0:
  448. self.items.append(dict(attrs))
  449. self._level += 1
  450. def handle_endtag(self, tag):
  451. self._level -= 1
  452. def extract_attributes(html_element):
  453. """Given a string for an HTML element such as
  454. <el
  455. a="foo" B="bar" c="&98;az" d=boz
  456. empty= noval entity="&amp;"
  457. sq='"' dq="'"
  458. >
  459. Decode and return a dictionary of attributes.
  460. {
  461. 'a': 'foo', 'b': 'bar', c: 'baz', d: 'boz',
  462. 'empty': '', 'noval': None, 'entity': '&',
  463. 'sq': '"', 'dq': '\''
  464. }.
  465. """
  466. parser = HTMLAttributeParser()
  467. with contextlib.suppress(compat_HTMLParseError):
  468. parser.feed(html_element)
  469. parser.close()
  470. return parser.attrs
  471. def parse_list(webpage):
  472. """Given a string for an series of HTML <li> elements,
  473. return a dictionary of their attributes"""
  474. parser = HTMLListAttrsParser()
  475. parser.feed(webpage)
  476. parser.close()
  477. return parser.items
  478. def clean_html(html):
  479. """Clean an HTML snippet into a readable string"""
  480. if html is None: # Convenience for sanitizing descriptions etc.
  481. return html
  482. html = re.sub(r'\s+', ' ', html)
  483. html = re.sub(r'(?u)\s?<\s?br\s?/?\s?>\s?', '\n', html)
  484. html = re.sub(r'(?u)<\s?/\s?p\s?>\s?<\s?p[^>]*>', '\n', html)
  485. # Strip html tags
  486. html = re.sub('<.*?>', '', html)
  487. # Replace html entities
  488. html = unescapeHTML(html)
  489. return html.strip()
  490. class LenientJSONDecoder(json.JSONDecoder):
  491. def __init__(self, *args, transform_source=None, ignore_extra=False, **kwargs):
  492. self.transform_source, self.ignore_extra = transform_source, ignore_extra
  493. super().__init__(*args, **kwargs)
  494. def decode(self, s):
  495. if self.transform_source:
  496. s = self.transform_source(s)
  497. if self.ignore_extra:
  498. return self.raw_decode(s.lstrip())[0]
  499. return super().decode(s)
  500. def sanitize_open(filename, open_mode):
  501. """Try to open the given filename, and slightly tweak it if this fails.
  502. Attempts to open the given filename. If this fails, it tries to change
  503. the filename slightly, step by step, until it's either able to open it
  504. or it fails and raises a final exception, like the standard open()
  505. function.
  506. It returns the tuple (stream, definitive_file_name).
  507. """
  508. if filename == '-':
  509. if sys.platform == 'win32':
  510. import msvcrt
  511. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  512. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  513. for attempt in range(2):
  514. try:
  515. try:
  516. if sys.platform == 'win32':
  517. # FIXME: An exclusive lock also locks the file from being read.
  518. # Since windows locks are mandatory, don't lock the file on windows (for now).
  519. # Ref: https://github.com/yt-dlp/yt-dlp/issues/3124
  520. raise LockingUnsupportedError()
  521. stream = locked_file(filename, open_mode, block=False).__enter__()
  522. except OSError:
  523. stream = open(filename, open_mode)
  524. return stream, filename
  525. except OSError as err:
  526. if attempt or err.errno in (errno.EACCES,):
  527. raise
  528. old_filename, filename = filename, sanitize_path(filename)
  529. if old_filename == filename:
  530. raise
  531. def timeconvert(timestr):
  532. """Convert RFC 2822 defined time string into system timestamp"""
  533. timestamp = None
  534. timetuple = email.utils.parsedate_tz(timestr)
  535. if timetuple is not None:
  536. timestamp = email.utils.mktime_tz(timetuple)
  537. return timestamp
  538. def sanitize_filename(s, restricted=False, is_id=NO_DEFAULT):
  539. """Sanitizes a string so it could be used as part of a filename.
  540. @param restricted Use a stricter subset of allowed characters
  541. @param is_id Whether this is an ID that should be kept unchanged if possible.
  542. If unset, yt-dlp's new sanitization rules are in effect
  543. """
  544. if s == '':
  545. return ''
  546. def replace_insane(char):
  547. if restricted and char in ACCENT_CHARS:
  548. return ACCENT_CHARS[char]
  549. elif not restricted and char == '\n':
  550. return '\0 '
  551. elif char == '?' or ord(char) < 32 or ord(char) == 127:
  552. return ''
  553. elif char == '"':
  554. return '' if restricted else '\''
  555. elif char == ':':
  556. return '\0_\0-' if restricted else '\0 \0-'
  557. elif char in '\\/|*<>':
  558. return '\0_'
  559. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace() or ord(char) > 127):
  560. return '\0_'
  561. return char
  562. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s) # Handle timestamps
  563. result = ''.join(map(replace_insane, s))
  564. if is_id is NO_DEFAULT:
  565. result = re.sub(r'(\0.)(?:(?=\1)..)+', r'\1', result) # Remove repeated substitute chars
  566. STRIP_RE = r'(?:\0.|[ _-])*'
  567. result = re.sub(f'^\0.{STRIP_RE}|{STRIP_RE}\0.$', '', result) # Remove substitute chars from start/end
  568. result = result.replace('\0', '') or '_'
  569. if not is_id:
  570. while '__' in result:
  571. result = result.replace('__', '_')
  572. result = result.strip('_')
  573. # Common case of "Foreign band name - English song title"
  574. if restricted and result.startswith('-_'):
  575. result = result[2:]
  576. if result.startswith('-'):
  577. result = '_' + result[len('-'):]
  578. result = result.lstrip('.')
  579. if not result:
  580. result = '_'
  581. return result
  582. def sanitize_path(s, force=False):
  583. """Sanitizes and normalizes path on Windows"""
  584. if sys.platform == 'win32':
  585. force = False
  586. drive_or_unc, _ = os.path.splitdrive(s)
  587. elif force:
  588. drive_or_unc = ''
  589. else:
  590. return s
  591. norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
  592. if drive_or_unc:
  593. norm_path.pop(0)
  594. sanitized_path = [
  595. path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
  596. for path_part in norm_path]
  597. if drive_or_unc:
  598. sanitized_path.insert(0, drive_or_unc + os.path.sep)
  599. elif force and s and s[0] == os.path.sep:
  600. sanitized_path.insert(0, os.path.sep)
  601. return os.path.join(*sanitized_path)
  602. def sanitize_url(url):
  603. # Prepend protocol-less URLs with `http:` scheme in order to mitigate
  604. # the number of unwanted failures due to missing protocol
  605. if url is None:
  606. return
  607. elif url.startswith('//'):
  608. return 'http:%s' % url
  609. # Fix some common typos seen so far
  610. COMMON_TYPOS = (
  611. # https://github.com/ytdl-org/youtube-dl/issues/15649
  612. (r'^httpss://', r'https://'),
  613. # https://bx1.be/lives/direct-tv/
  614. (r'^rmtp([es]?)://', r'rtmp\1://'),
  615. )
  616. for mistake, fixup in COMMON_TYPOS:
  617. if re.match(mistake, url):
  618. return re.sub(mistake, fixup, url)
  619. return url
  620. def extract_basic_auth(url):
  621. parts = urllib.parse.urlsplit(url)
  622. if parts.username is None:
  623. return url, None
  624. url = urllib.parse.urlunsplit(parts._replace(netloc=(
  625. parts.hostname if parts.port is None
  626. else '%s:%d' % (parts.hostname, parts.port))))
  627. auth_payload = base64.b64encode(
  628. ('%s:%s' % (parts.username, parts.password or '')).encode())
  629. return url, f'Basic {auth_payload.decode()}'
  630. def sanitized_Request(url, *args, **kwargs):
  631. url, auth_header = extract_basic_auth(escape_url(sanitize_url(url)))
  632. if auth_header is not None:
  633. headers = args[1] if len(args) >= 2 else kwargs.setdefault('headers', {})
  634. headers['Authorization'] = auth_header
  635. return urllib.request.Request(url, *args, **kwargs)
  636. def expand_path(s):
  637. """Expand shell variables and ~"""
  638. return os.path.expandvars(compat_expanduser(s))
  639. def orderedSet(iterable, *, lazy=False):
  640. """Remove all duplicates from the input iterable"""
  641. def _iter():
  642. seen = [] # Do not use set since the items can be unhashable
  643. for x in iterable:
  644. if x not in seen:
  645. seen.append(x)
  646. yield x
  647. return _iter() if lazy else list(_iter())
  648. def _htmlentity_transform(entity_with_semicolon):
  649. """Transforms an HTML entity to a character."""
  650. entity = entity_with_semicolon[:-1]
  651. # Known non-numeric HTML entity
  652. if entity in html.entities.name2codepoint:
  653. return chr(html.entities.name2codepoint[entity])
  654. # TODO: HTML5 allows entities without a semicolon. For example,
  655. # '&Eacuteric' should be decoded as 'Éric'.
  656. if entity_with_semicolon in html.entities.html5:
  657. return html.entities.html5[entity_with_semicolon]
  658. mobj = re.match(r'#(x[0-9a-fA-F]+|[0-9]+)', entity)
  659. if mobj is not None:
  660. numstr = mobj.group(1)
  661. if numstr.startswith('x'):
  662. base = 16
  663. numstr = '0%s' % numstr
  664. else:
  665. base = 10
  666. # See https://github.com/ytdl-org/youtube-dl/issues/7518
  667. with contextlib.suppress(ValueError):
  668. return chr(int(numstr, base))
  669. # Unknown entity in name, return its literal representation
  670. return '&%s;' % entity
  671. def unescapeHTML(s):
  672. if s is None:
  673. return None
  674. assert isinstance(s, str)
  675. return re.sub(
  676. r'&([^&;]+;)', lambda m: _htmlentity_transform(m.group(1)), s)
  677. def escapeHTML(text):
  678. return (
  679. text
  680. .replace('&', '&amp;')
  681. .replace('<', '&lt;')
  682. .replace('>', '&gt;')
  683. .replace('"', '&quot;')
  684. .replace("'", '&#39;')
  685. )
  686. def process_communicate_or_kill(p, *args, **kwargs):
  687. write_string('DeprecationWarning: yt_dlp.utils.process_communicate_or_kill is deprecated '
  688. 'and may be removed in a future version. Use yt_dlp.utils.Popen.communicate_or_kill instead')
  689. return Popen.communicate_or_kill(p, *args, **kwargs)
  690. class Popen(subprocess.Popen):
  691. if sys.platform == 'win32':
  692. _startupinfo = subprocess.STARTUPINFO()
  693. _startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  694. else:
  695. _startupinfo = None
  696. def __init__(self, *args, text=False, **kwargs):
  697. if text is True:
  698. kwargs['universal_newlines'] = True # For 3.6 compatibility
  699. kwargs.setdefault('encoding', 'utf-8')
  700. kwargs.setdefault('errors', 'replace')
  701. super().__init__(*args, **kwargs, startupinfo=self._startupinfo)
  702. def communicate_or_kill(self, *args, **kwargs):
  703. try:
  704. return self.communicate(*args, **kwargs)
  705. except BaseException: # Including KeyboardInterrupt
  706. self.kill(timeout=None)
  707. raise
  708. def kill(self, *, timeout=0):
  709. super().kill()
  710. if timeout != 0:
  711. self.wait(timeout=timeout)
  712. @classmethod
  713. def run(cls, *args, **kwargs):
  714. with cls(*args, **kwargs) as proc:
  715. stdout, stderr = proc.communicate_or_kill()
  716. return stdout or '', stderr or '', proc.returncode
  717. def get_subprocess_encoding():
  718. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  719. # For subprocess calls, encode with locale encoding
  720. # Refer to http://stackoverflow.com/a/9951851/35070
  721. encoding = preferredencoding()
  722. else:
  723. encoding = sys.getfilesystemencoding()
  724. if encoding is None:
  725. encoding = 'utf-8'
  726. return encoding
  727. def encodeFilename(s, for_subprocess=False):
  728. assert isinstance(s, str)
  729. return s
  730. def decodeFilename(b, for_subprocess=False):
  731. return b
  732. def encodeArgument(s):
  733. # Legacy code that uses byte strings
  734. # Uncomment the following line after fixing all post processors
  735. # assert isinstance(s, str), 'Internal error: %r should be of type %r, is %r' % (s, str, type(s))
  736. return s if isinstance(s, str) else s.decode('ascii')
  737. def decodeArgument(b):
  738. return b
  739. def decodeOption(optval):
  740. if optval is None:
  741. return optval
  742. if isinstance(optval, bytes):
  743. optval = optval.decode(preferredencoding())
  744. assert isinstance(optval, str)
  745. return optval
  746. _timetuple = collections.namedtuple('Time', ('hours', 'minutes', 'seconds', 'milliseconds'))
  747. def timetuple_from_msec(msec):
  748. secs, msec = divmod(msec, 1000)
  749. mins, secs = divmod(secs, 60)
  750. hrs, mins = divmod(mins, 60)
  751. return _timetuple(hrs, mins, secs, msec)
  752. def formatSeconds(secs, delim=':', msec=False):
  753. time = timetuple_from_msec(secs * 1000)
  754. if time.hours:
  755. ret = '%d%s%02d%s%02d' % (time.hours, delim, time.minutes, delim, time.seconds)
  756. elif time.minutes:
  757. ret = '%d%s%02d' % (time.minutes, delim, time.seconds)
  758. else:
  759. ret = '%d' % time.seconds
  760. return '%s.%03d' % (ret, time.milliseconds) if msec else ret
  761. def _ssl_load_windows_store_certs(ssl_context, storename):
  762. # Code adapted from _load_windows_store_certs in https://github.com/python/cpython/blob/main/Lib/ssl.py
  763. try:
  764. certs = [cert for cert, encoding, trust in ssl.enum_certificates(storename)
  765. if encoding == 'x509_asn' and (
  766. trust is True or ssl.Purpose.SERVER_AUTH.oid in trust)]
  767. except PermissionError:
  768. return
  769. for cert in certs:
  770. with contextlib.suppress(ssl.SSLError):
  771. ssl_context.load_verify_locations(cadata=cert)
  772. def make_HTTPS_handler(params, **kwargs):
  773. opts_check_certificate = not params.get('nocheckcertificate')
  774. context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
  775. context.check_hostname = opts_check_certificate
  776. if params.get('legacyserverconnect'):
  777. context.options |= 4 # SSL_OP_LEGACY_SERVER_CONNECT
  778. # Allow use of weaker ciphers in Python 3.10+. See https://bugs.python.org/issue43998
  779. context.set_ciphers('DEFAULT')
  780. context.verify_mode = ssl.CERT_REQUIRED if opts_check_certificate else ssl.CERT_NONE
  781. if opts_check_certificate:
  782. if has_certifi and 'no-certifi' not in params.get('compat_opts', []):
  783. context.load_verify_locations(cafile=certifi.where())
  784. else:
  785. try:
  786. context.load_default_certs()
  787. # Work around the issue in load_default_certs when there are bad certificates. See:
  788. # https://github.com/yt-dlp/yt-dlp/issues/1060,
  789. # https://bugs.python.org/issue35665, https://bugs.python.org/issue45312
  790. except ssl.SSLError:
  791. # enum_certificates is not present in mingw python. See https://github.com/yt-dlp/yt-dlp/issues/1151
  792. if sys.platform == 'win32' and hasattr(ssl, 'enum_certificates'):
  793. for storename in ('CA', 'ROOT'):
  794. _ssl_load_windows_store_certs(context, storename)
  795. context.set_default_verify_paths()
  796. client_certfile = params.get('client_certificate')
  797. if client_certfile:
  798. try:
  799. context.load_cert_chain(
  800. client_certfile, keyfile=params.get('client_certificate_key'),
  801. password=params.get('client_certificate_password'))
  802. except ssl.SSLError:
  803. raise YoutubeDLError('Unable to load client certificate')
  804. # Some servers may reject requests if ALPN extension is not sent. See:
  805. # https://github.com/python/cpython/issues/85140
  806. # https://github.com/yt-dlp/yt-dlp/issues/3878
  807. with contextlib.suppress(NotImplementedError):
  808. context.set_alpn_protocols(['http/1.1'])
  809. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  810. def bug_reports_message(before=';'):
  811. from .update import REPOSITORY
  812. msg = (f'please report this issue on https://github.com/{REPOSITORY}/issues?q= , '
  813. 'filling out the appropriate issue template. Confirm you are on the latest version using yt-dlp -U')
  814. before = before.rstrip()
  815. if not before or before.endswith(('.', '!', '?')):
  816. msg = msg[0].title() + msg[1:]
  817. return (before + ' ' if before else '') + msg
  818. class YoutubeDLError(Exception):
  819. """Base exception for YoutubeDL errors."""
  820. msg = None
  821. def __init__(self, msg=None):
  822. if msg is not None:
  823. self.msg = msg
  824. elif self.msg is None:
  825. self.msg = type(self).__name__
  826. super().__init__(self.msg)
  827. network_exceptions = [urllib.error.URLError, http.client.HTTPException, socket.error]
  828. if hasattr(ssl, 'CertificateError'):
  829. network_exceptions.append(ssl.CertificateError)
  830. network_exceptions = tuple(network_exceptions)
  831. class ExtractorError(YoutubeDLError):
  832. """Error during info extraction."""
  833. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None, ie=None):
  834. """ tb, if given, is the original traceback (so that it can be printed out).
  835. If expected is set, this is a normal error message and most likely not a bug in yt-dlp.
  836. """
  837. if sys.exc_info()[0] in network_exceptions:
  838. expected = True
  839. self.orig_msg = str(msg)
  840. self.traceback = tb
  841. self.expected = expected
  842. self.cause = cause
  843. self.video_id = video_id
  844. self.ie = ie
  845. self.exc_info = sys.exc_info() # preserve original exception
  846. if isinstance(self.exc_info[1], ExtractorError):
  847. self.exc_info = self.exc_info[1].exc_info
  848. super().__init__(''.join((
  849. format_field(ie, None, '[%s] '),
  850. format_field(video_id, None, '%s: '),
  851. msg,
  852. format_field(cause, None, ' (caused by %r)'),
  853. '' if expected else bug_reports_message())))
  854. def format_traceback(self):
  855. return join_nonempty(
  856. self.traceback and ''.join(traceback.format_tb(self.traceback)),
  857. self.cause and ''.join(traceback.format_exception(None, self.cause, self.cause.__traceback__)[1:]),
  858. delim='\n') or None
  859. class UnsupportedError(ExtractorError):
  860. def __init__(self, url):
  861. super().__init__(
  862. 'Unsupported URL: %s' % url, expected=True)
  863. self.url = url
  864. class RegexNotFoundError(ExtractorError):
  865. """Error when a regex didn't match"""
  866. pass
  867. class GeoRestrictedError(ExtractorError):
  868. """Geographic restriction Error exception.
  869. This exception may be thrown when a video is not available from your
  870. geographic location due to geographic restrictions imposed by a website.
  871. """
  872. def __init__(self, msg, countries=None, **kwargs):
  873. kwargs['expected'] = True
  874. super().__init__(msg, **kwargs)
  875. self.countries = countries
  876. class UserNotLive(ExtractorError):
  877. """Error when a channel/user is not live"""
  878. def __init__(self, msg=None, **kwargs):
  879. kwargs['expected'] = True
  880. super().__init__(msg or 'The channel is not currently live', **kwargs)
  881. class DownloadError(YoutubeDLError):
  882. """Download Error exception.
  883. This exception may be thrown by FileDownloader objects if they are not
  884. configured to continue on errors. They will contain the appropriate
  885. error message.
  886. """
  887. def __init__(self, msg, exc_info=None):
  888. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  889. super().__init__(msg)
  890. self.exc_info = exc_info
  891. class EntryNotInPlaylist(YoutubeDLError):
  892. """Entry not in playlist exception.
  893. This exception will be thrown by YoutubeDL when a requested entry
  894. is not found in the playlist info_dict
  895. """
  896. msg = 'Entry not found in info'
  897. class SameFileError(YoutubeDLError):
  898. """Same File exception.
  899. This exception will be thrown by FileDownloader objects if they detect
  900. multiple files would have to be downloaded to the same file on disk.
  901. """
  902. msg = 'Fixed output name but more than one file to download'
  903. def __init__(self, filename=None):
  904. if filename is not None:
  905. self.msg += f': {filename}'
  906. super().__init__(self.msg)
  907. class PostProcessingError(YoutubeDLError):
  908. """Post Processing exception.
  909. This exception may be raised by PostProcessor's .run() method to
  910. indicate an error in the postprocessing task.
  911. """
  912. class DownloadCancelled(YoutubeDLError):
  913. """ Exception raised when the download queue should be interrupted """
  914. msg = 'The download was cancelled'
  915. class ExistingVideoReached(DownloadCancelled):
  916. """ --break-on-existing triggered """
  917. msg = 'Encountered a video that is already in the archive, stopping due to --break-on-existing'
  918. class RejectedVideoReached(DownloadCancelled):
  919. """ --break-on-reject triggered """
  920. msg = 'Encountered a video that did not match filter, stopping due to --break-on-reject'
  921. class MaxDownloadsReached(DownloadCancelled):
  922. """ --max-downloads limit has been reached. """
  923. msg = 'Maximum number of downloads reached, stopping due to --max-downloads'
  924. class ReExtractInfo(YoutubeDLError):
  925. """ Video info needs to be re-extracted. """
  926. def __init__(self, msg, expected=False):
  927. super().__init__(msg)
  928. self.expected = expected
  929. class ThrottledDownload(ReExtractInfo):
  930. """ Download speed below --throttled-rate. """
  931. msg = 'The download speed is below throttle limit'
  932. def __init__(self):
  933. super().__init__(self.msg, expected=False)
  934. class UnavailableVideoError(YoutubeDLError):
  935. """Unavailable Format exception.
  936. This exception will be thrown when a video is requested
  937. in a format that is not available for that video.
  938. """
  939. msg = 'Unable to download video'
  940. def __init__(self, err=None):
  941. if err is not None:
  942. self.msg += f': {err}'
  943. super().__init__(self.msg)
  944. class ContentTooShortError(YoutubeDLError):
  945. """Content Too Short exception.
  946. This exception may be raised by FileDownloader objects when a file they
  947. download is too small for what the server announced first, indicating
  948. the connection was probably interrupted.
  949. """
  950. def __init__(self, downloaded, expected):
  951. super().__init__(f'Downloaded {downloaded} bytes, expected {expected} bytes')
  952. # Both in bytes
  953. self.downloaded = downloaded
  954. self.expected = expected
  955. class XAttrMetadataError(YoutubeDLError):
  956. def __init__(self, code=None, msg='Unknown error'):
  957. super().__init__(msg)
  958. self.code = code
  959. self.msg = msg
  960. # Parsing code and msg
  961. if (self.code in (errno.ENOSPC, errno.EDQUOT)
  962. or 'No space left' in self.msg or 'Disk quota exceeded' in self.msg):
  963. self.reason = 'NO_SPACE'
  964. elif self.code == errno.E2BIG or 'Argument list too long' in self.msg:
  965. self.reason = 'VALUE_TOO_LONG'
  966. else:
  967. self.reason = 'NOT_SUPPORTED'
  968. class XAttrUnavailableError(YoutubeDLError):
  969. pass
  970. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  971. hc = http_class(*args, **kwargs)
  972. source_address = ydl_handler._params.get('source_address')
  973. if source_address is not None:
  974. # This is to workaround _create_connection() from socket where it will try all
  975. # address data from getaddrinfo() including IPv6. This filters the result from
  976. # getaddrinfo() based on the source_address value.
  977. # This is based on the cpython socket.create_connection() function.
  978. # https://github.com/python/cpython/blob/master/Lib/socket.py#L691
  979. def _create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
  980. host, port = address
  981. err = None
  982. addrs = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
  983. af = socket.AF_INET if '.' in source_address[0] else socket.AF_INET6
  984. ip_addrs = [addr for addr in addrs if addr[0] == af]
  985. if addrs and not ip_addrs:
  986. ip_version = 'v4' if af == socket.AF_INET else 'v6'
  987. raise OSError(
  988. "No remote IP%s addresses available for connect, can't use '%s' as source address"
  989. % (ip_version, source_address[0]))
  990. for res in ip_addrs:
  991. af, socktype, proto, canonname, sa = res
  992. sock = None
  993. try:
  994. sock = socket.socket(af, socktype, proto)
  995. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  996. sock.settimeout(timeout)
  997. sock.bind(source_address)
  998. sock.connect(sa)
  999. err = None # Explicitly break reference cycle
  1000. return sock
  1001. except OSError as _:
  1002. err = _
  1003. if sock is not None:
  1004. sock.close()
  1005. if err is not None:
  1006. raise err
  1007. else:
  1008. raise OSError('getaddrinfo returns an empty list')
  1009. if hasattr(hc, '_create_connection'):
  1010. hc._create_connection = _create_connection
  1011. hc.source_address = (source_address, 0)
  1012. return hc
  1013. def handle_youtubedl_headers(headers):
  1014. filtered_headers = headers
  1015. if 'Youtubedl-no-compression' in filtered_headers:
  1016. filtered_headers = {k: v for k, v in filtered_headers.items() if k.lower() != 'accept-encoding'}
  1017. del filtered_headers['Youtubedl-no-compression']
  1018. return filtered_headers
  1019. class YoutubeDLHandler(urllib.request.HTTPHandler):
  1020. """Handler for HTTP requests and responses.
  1021. This class, when installed with an OpenerDirector, automatically adds
  1022. the standard headers to every HTTP request and handles gzipped and
  1023. deflated responses from web servers. If compression is to be avoided in
  1024. a particular request, the original request in the program code only has
  1025. to include the HTTP header "Youtubedl-no-compression", which will be
  1026. removed before making the real request.
  1027. Part of this code was copied from:
  1028. http://techknack.net/python-urllib2-handlers/
  1029. Andrew Rowls, the author of that code, agreed to release it to the
  1030. public domain.
  1031. """
  1032. def __init__(self, params, *args, **kwargs):
  1033. urllib.request.HTTPHandler.__init__(self, *args, **kwargs)
  1034. self._params = params
  1035. def http_open(self, req):
  1036. conn_class = http.client.HTTPConnection
  1037. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  1038. if socks_proxy:
  1039. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  1040. del req.headers['Ytdl-socks-proxy']
  1041. return self.do_open(functools.partial(
  1042. _create_http_connection, self, conn_class, False),
  1043. req)
  1044. @staticmethod
  1045. def deflate(data):
  1046. if not data:
  1047. return data
  1048. try:
  1049. return zlib.decompress(data, -zlib.MAX_WBITS)
  1050. except zlib.error:
  1051. return zlib.decompress(data)
  1052. @staticmethod
  1053. def brotli(data):
  1054. if not data:
  1055. return data
  1056. return brotli.decompress(data)
  1057. def http_request(self, req):
  1058. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1059. # always respected by websites, some tend to give out URLs with non percent-encoded
  1060. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1061. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1062. # To work around aforementioned issue we will replace request's original URL with
  1063. # percent-encoded one
  1064. # Since redirects are also affected (e.g. http://www.southpark.de/alle-episoden/s18e09)
  1065. # the code of this workaround has been moved here from YoutubeDL.urlopen()
  1066. url = req.get_full_url()
  1067. url_escaped = escape_url(url)
  1068. # Substitute URL if any change after escaping
  1069. if url != url_escaped:
  1070. req = update_Request(req, url=url_escaped)
  1071. for h, v in self._params.get('http_headers', std_headers).items():
  1072. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  1073. # The dict keys are capitalized because of this bug by urllib
  1074. if h.capitalize() not in req.headers:
  1075. req.add_header(h, v)
  1076. if 'Accept-encoding' not in req.headers:
  1077. req.add_header('Accept-encoding', ', '.join(SUPPORTED_ENCODINGS))
  1078. req.headers = handle_youtubedl_headers(req.headers)
  1079. return super().do_request_(req)
  1080. def http_response(self, req, resp):
  1081. old_resp = resp
  1082. # gzip
  1083. if resp.headers.get('Content-encoding', '') == 'gzip':
  1084. content = resp.read()
  1085. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  1086. try:
  1087. uncompressed = io.BytesIO(gz.read())
  1088. except OSError as original_ioerror:
  1089. # There may be junk add the end of the file
  1090. # See http://stackoverflow.com/q/4928560/35070 for details
  1091. for i in range(1, 1024):
  1092. try:
  1093. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  1094. uncompressed = io.BytesIO(gz.read())
  1095. except OSError:
  1096. continue
  1097. break
  1098. else:
  1099. raise original_ioerror
  1100. resp = urllib.request.addinfourl(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  1101. resp.msg = old_resp.msg
  1102. del resp.headers['Content-encoding']
  1103. # deflate
  1104. if resp.headers.get('Content-encoding', '') == 'deflate':
  1105. gz = io.BytesIO(self.deflate(resp.read()))
  1106. resp = urllib.request.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
  1107. resp.msg = old_resp.msg
  1108. del resp.headers['Content-encoding']
  1109. # brotli
  1110. if resp.headers.get('Content-encoding', '') == 'br':
  1111. resp = urllib.request.addinfourl(
  1112. io.BytesIO(self.brotli(resp.read())), old_resp.headers, old_resp.url, old_resp.code)
  1113. resp.msg = old_resp.msg
  1114. del resp.headers['Content-encoding']
  1115. # Percent-encode redirect URL of Location HTTP header to satisfy RFC 3986 (see
  1116. # https://github.com/ytdl-org/youtube-dl/issues/6457).
  1117. if 300 <= resp.code < 400:
  1118. location = resp.headers.get('Location')
  1119. if location:
  1120. # As of RFC 2616 default charset is iso-8859-1 that is respected by python 3
  1121. location = location.encode('iso-8859-1').decode()
  1122. location_escaped = escape_url(location)
  1123. if location != location_escaped:
  1124. del resp.headers['Location']
  1125. resp.headers['Location'] = location_escaped
  1126. return resp
  1127. https_request = http_request
  1128. https_response = http_response
  1129. def make_socks_conn_class(base_class, socks_proxy):
  1130. assert issubclass(base_class, (
  1131. http.client.HTTPConnection, http.client.HTTPSConnection))
  1132. url_components = urllib.parse.urlparse(socks_proxy)
  1133. if url_components.scheme.lower() == 'socks5':
  1134. socks_type = ProxyType.SOCKS5
  1135. elif url_components.scheme.lower() in ('socks', 'socks4'):
  1136. socks_type = ProxyType.SOCKS4
  1137. elif url_components.scheme.lower() == 'socks4a':
  1138. socks_type = ProxyType.SOCKS4A
  1139. def unquote_if_non_empty(s):
  1140. if not s:
  1141. return s
  1142. return urllib.parse.unquote_plus(s)
  1143. proxy_args = (
  1144. socks_type,
  1145. url_components.hostname, url_components.port or 1080,
  1146. True, # Remote DNS
  1147. unquote_if_non_empty(url_components.username),
  1148. unquote_if_non_empty(url_components.password),
  1149. )
  1150. class SocksConnection(base_class):
  1151. def connect(self):
  1152. self.sock = sockssocket()
  1153. self.sock.setproxy(*proxy_args)
  1154. if isinstance(self.timeout, (int, float)):
  1155. self.sock.settimeout(self.timeout)
  1156. self.sock.connect((self.host, self.port))
  1157. if isinstance(self, http.client.HTTPSConnection):
  1158. if hasattr(self, '_context'): # Python > 2.6
  1159. self.sock = self._context.wrap_socket(
  1160. self.sock, server_hostname=self.host)
  1161. else:
  1162. self.sock = ssl.wrap_socket(self.sock)
  1163. return SocksConnection
  1164. class YoutubeDLHTTPSHandler(urllib.request.HTTPSHandler):
  1165. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  1166. urllib.request.HTTPSHandler.__init__(self, *args, **kwargs)
  1167. self._https_conn_class = https_conn_class or http.client.HTTPSConnection
  1168. self._params = params
  1169. def https_open(self, req):
  1170. kwargs = {}
  1171. conn_class = self._https_conn_class
  1172. if hasattr(self, '_context'): # python > 2.6
  1173. kwargs['context'] = self._context
  1174. if hasattr(self, '_check_hostname'): # python 3.x
  1175. kwargs['check_hostname'] = self._check_hostname
  1176. socks_proxy = req.headers.get('Ytdl-socks-proxy')
  1177. if socks_proxy:
  1178. conn_class = make_socks_conn_class(conn_class, socks_proxy)
  1179. del req.headers['Ytdl-socks-proxy']
  1180. try:
  1181. return self.do_open(
  1182. functools.partial(_create_http_connection, self, conn_class, True), req, **kwargs)
  1183. except urllib.error.URLError as e:
  1184. if (isinstance(e.reason, ssl.SSLError)
  1185. and getattr(e.reason, 'reason', None) == 'SSLV3_ALERT_HANDSHAKE_FAILURE'):
  1186. raise YoutubeDLError('SSLV3_ALERT_HANDSHAKE_FAILURE: Try using --legacy-server-connect')
  1187. raise
  1188. class YoutubeDLCookieJar(http.cookiejar.MozillaCookieJar):
  1189. """
  1190. See [1] for cookie file format.
  1191. 1. https://curl.haxx.se/docs/http-cookies.html
  1192. """
  1193. _HTTPONLY_PREFIX = '#HttpOnly_'
  1194. _ENTRY_LEN = 7
  1195. _HEADER = '''# Netscape HTTP Cookie File
  1196. # This file is generated by yt-dlp. Do not edit.
  1197. '''
  1198. _CookieFileEntry = collections.namedtuple(
  1199. 'CookieFileEntry',
  1200. ('domain_name', 'include_subdomains', 'path', 'https_only', 'expires_at', 'name', 'value'))
  1201. def __init__(self, filename=None, *args, **kwargs):
  1202. super().__init__(None, *args, **kwargs)
  1203. if self.is_path(filename):
  1204. filename = os.fspath(filename)
  1205. self.filename = filename
  1206. @staticmethod
  1207. def _true_or_false(cndn):
  1208. return 'TRUE' if cndn else 'FALSE'
  1209. @staticmethod
  1210. def is_path(file):
  1211. return isinstance(file, (str, bytes, os.PathLike))
  1212. @contextlib.contextmanager
  1213. def open(self, file, *, write=False):
  1214. if self.is_path(file):
  1215. with open(file, 'w' if write else 'r', encoding='utf-8') as f:
  1216. yield f
  1217. else:
  1218. if write:
  1219. file.truncate(0)
  1220. yield file
  1221. def _really_save(self, f, ignore_discard=False, ignore_expires=False):
  1222. now = time.time()
  1223. for cookie in self:
  1224. if (not ignore_discard and cookie.discard
  1225. or not ignore_expires and cookie.is_expired(now)):
  1226. continue
  1227. name, value = cookie.name, cookie.value
  1228. if value is None:
  1229. # cookies.txt regards 'Set-Cookie: foo' as a cookie
  1230. # with no name, whereas http.cookiejar regards it as a
  1231. # cookie with no value.
  1232. name, value = '', name
  1233. f.write('%s\n' % '\t'.join((
  1234. cookie.domain,
  1235. self._true_or_false(cookie.domain.startswith('.')),
  1236. cookie.path,
  1237. self._true_or_false(cookie.secure),
  1238. str_or_none(cookie.expires, default=''),
  1239. name, value
  1240. )))
  1241. def save(self, filename=None, *args, **kwargs):
  1242. """
  1243. Save cookies to a file.
  1244. Code is taken from CPython 3.6
  1245. https://github.com/python/cpython/blob/8d999cbf4adea053be6dbb612b9844635c4dfb8e/Lib/http/cookiejar.py#L2091-L2117 """
  1246. if filename is None:
  1247. if self.filename is not None:
  1248. filename = self.filename
  1249. else:
  1250. raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT)
  1251. # Store session cookies with `expires` set to 0 instead of an empty string
  1252. for cookie in self:
  1253. if cookie.expires is None:
  1254. cookie.expires = 0
  1255. with self.open(filename, write=True) as f:
  1256. f.write(self._HEADER)
  1257. self._really_save(f, *args, **kwargs)
  1258. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  1259. """Load cookies from a file."""
  1260. if filename is None:
  1261. if self.filename is not None:
  1262. filename = self.filename
  1263. else:
  1264. raise ValueError(http.cookiejar.MISSING_FILENAME_TEXT)
  1265. def prepare_line(line):
  1266. if line.startswith(self._HTTPONLY_PREFIX):
  1267. line = line[len(self._HTTPONLY_PREFIX):]
  1268. # comments and empty lines are fine
  1269. if line.startswith('#') or not line.strip():
  1270. return line
  1271. cookie_list = line.split('\t')
  1272. if len(cookie_list) != self._ENTRY_LEN:
  1273. raise http.cookiejar.LoadError('invalid length %d' % len(cookie_list))
  1274. cookie = self._CookieFileEntry(*cookie_list)
  1275. if cookie.expires_at and not cookie.expires_at.isdigit():
  1276. raise http.cookiejar.LoadError('invalid expires at %s' % cookie.expires_at)
  1277. return line
  1278. cf = io.StringIO()
  1279. with self.open(filename) as f:
  1280. for line in f:
  1281. try:
  1282. cf.write(prepare_line(line))
  1283. except http.cookiejar.LoadError as e:
  1284. if f'{line.strip()} '[0] in '[{"':
  1285. raise http.cookiejar.LoadError(
  1286. 'Cookies file must be Netscape formatted, not JSON. See '
  1287. 'https://github.com/ytdl-org/youtube-dl#how-do-i-pass-cookies-to-youtube-dl')
  1288. write_string(f'WARNING: skipping cookie file entry due to {e}: {line!r}\n')
  1289. continue
  1290. cf.seek(0)
  1291. self._really_load(cf, filename, ignore_discard, ignore_expires)
  1292. # Session cookies are denoted by either `expires` field set to
  1293. # an empty string or 0. MozillaCookieJar only recognizes the former
  1294. # (see [1]). So we need force the latter to be recognized as session
  1295. # cookies on our own.
  1296. # Session cookies may be important for cookies-based authentication,
  1297. # e.g. usually, when user does not check 'Remember me' check box while
  1298. # logging in on a site, some important cookies are stored as session
  1299. # cookies so that not recognizing them will result in failed login.
  1300. # 1. https://bugs.python.org/issue17164
  1301. for cookie in self:
  1302. # Treat `expires=0` cookies as session cookies
  1303. if cookie.expires == 0:
  1304. cookie.expires = None
  1305. cookie.discard = True
  1306. class YoutubeDLCookieProcessor(urllib.request.HTTPCookieProcessor):
  1307. def __init__(self, cookiejar=None):
  1308. urllib.request.HTTPCookieProcessor.__init__(self, cookiejar)
  1309. def http_response(self, request, response):
  1310. return urllib.request.HTTPCookieProcessor.http_response(self, request, response)
  1311. https_request = urllib.request.HTTPCookieProcessor.http_request
  1312. https_response = http_response
  1313. class YoutubeDLRedirectHandler(urllib.request.HTTPRedirectHandler):
  1314. """YoutubeDL redirect handler
  1315. The code is based on HTTPRedirectHandler implementation from CPython [1].
  1316. This redirect handler solves two issues:
  1317. - ensures redirect URL is always unicode under python 2
  1318. - introduces support for experimental HTTP response status code
  1319. 308 Permanent Redirect [2] used by some sites [3]
  1320. 1. https://github.com/python/cpython/blob/master/Lib/urllib/request.py
  1321. 2. https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308
  1322. 3. https://github.com/ytdl-org/youtube-dl/issues/28768
  1323. """
  1324. http_error_301 = http_error_303 = http_error_307 = http_error_308 = urllib.request.HTTPRedirectHandler.http_error_302
  1325. def redirect_request(self, req, fp, code, msg, headers, newurl):
  1326. """Return a Request or None in response to a redirect.
  1327. This is called by the http_error_30x methods when a
  1328. redirection response is received. If a redirection should
  1329. take place, return a new Request to allow http_error_30x to
  1330. perform the redirect. Otherwise, raise HTTPError if no-one
  1331. else should try to handle this url. Return None if you can't
  1332. but another Handler might.
  1333. """
  1334. m = req.get_method()
  1335. if (not (code in (301, 302, 303, 307, 308) and m in ("GET", "HEAD")
  1336. or code in (301, 302, 303) and m == "POST")):
  1337. raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp)
  1338. # Strictly (according to RFC 2616), 301 or 302 in response to
  1339. # a POST MUST NOT cause a redirection without confirmation
  1340. # from the user (of urllib.request, in this case). In practice,
  1341. # essentially all clients do redirect in this case, so we do
  1342. # the same.
  1343. # Be conciliant with URIs containing a space. This is mainly
  1344. # redundant with the more complete encoding done in http_error_302(),
  1345. # but it is kept for compatibility with other callers.
  1346. newurl = newurl.replace(' ', '%20')
  1347. CONTENT_HEADERS = ("content-length", "content-type")
  1348. # NB: don't use dict comprehension for python 2.6 compatibility
  1349. newheaders = {k: v for k, v in req.headers.items() if k.lower() not in CONTENT_HEADERS}
  1350. # A 303 must either use GET or HEAD for subsequent request
  1351. # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.4
  1352. if code == 303 and m != 'HEAD':
  1353. m = 'GET'
  1354. # 301 and 302 redirects are commonly turned into a GET from a POST
  1355. # for subsequent requests by browsers, so we'll do the same.
  1356. # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.2
  1357. # https://datatracker.ietf.org/doc/html/rfc7231#section-6.4.3
  1358. if code in (301, 302) and m == 'POST':
  1359. m = 'GET'
  1360. return urllib.request.Request(
  1361. newurl, headers=newheaders, origin_req_host=req.origin_req_host,
  1362. unverifiable=True, method=m)
  1363. def extract_timezone(date_str):
  1364. m = re.search(
  1365. r'''(?x)
  1366. ^.{8,}? # >=8 char non-TZ prefix, if present
  1367. (?P<tz>Z| # just the UTC Z, or
  1368. (?:(?<=.\b\d{4}|\b\d{2}:\d\d)| # preceded by 4 digits or hh:mm or
  1369. (?<!.\b[a-zA-Z]{3}|[a-zA-Z]{4}|..\b\d\d)) # not preceded by 3 alpha word or >= 4 alpha or 2 digits
  1370. [ ]? # optional space
  1371. (?P<sign>\+|-) # +/-
  1372. (?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2}) # hh[:]mm
  1373. $)
  1374. ''', date_str)
  1375. if not m:
  1376. timezone = datetime.timedelta()
  1377. else:
  1378. date_str = date_str[:-len(m.group('tz'))]
  1379. if not m.group('sign'):
  1380. timezone = datetime.timedelta()
  1381. else:
  1382. sign = 1 if m.group('sign') == '+' else -1
  1383. timezone = datetime.timedelta(
  1384. hours=sign * int(m.group('hours')),
  1385. minutes=sign * int(m.group('minutes')))
  1386. return timezone, date_str
  1387. def parse_iso8601(date_str, delimiter='T', timezone=None):
  1388. """ Return a UNIX timestamp from the given date """
  1389. if date_str is None:
  1390. return None
  1391. date_str = re.sub(r'\.[0-9]+', '', date_str)
  1392. if timezone is None:
  1393. timezone, date_str = extract_timezone(date_str)
  1394. with contextlib.suppress(ValueError):
  1395. date_format = f'%Y-%m-%d{delimiter}%H:%M:%S'
  1396. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  1397. return calendar.timegm(dt.timetuple())
  1398. def date_formats(day_first=True):
  1399. return DATE_FORMATS_DAY_FIRST if day_first else DATE_FORMATS_MONTH_FIRST
  1400. def unified_strdate(date_str, day_first=True):
  1401. """Return a string with the date in the format YYYYMMDD"""
  1402. if date_str is None:
  1403. return None
  1404. upload_date = None
  1405. # Replace commas
  1406. date_str = date_str.replace(',', ' ')
  1407. # Remove AM/PM + timezone
  1408. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  1409. _, date_str = extract_timezone(date_str)
  1410. for expression in date_formats(day_first):
  1411. with contextlib.suppress(ValueError):
  1412. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  1413. if upload_date is None:
  1414. timetuple = email.utils.parsedate_tz(date_str)
  1415. if timetuple:
  1416. with contextlib.suppress(ValueError):
  1417. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  1418. if upload_date is not None:
  1419. return str(upload_date)
  1420. def unified_timestamp(date_str, day_first=True):
  1421. if date_str is None:
  1422. return None
  1423. date_str = re.sub(r'[,|]', '', date_str)
  1424. pm_delta = 12 if re.search(r'(?i)PM', date_str) else 0
  1425. timezone, date_str = extract_timezone(date_str)
  1426. # Remove AM/PM + timezone
  1427. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  1428. # Remove unrecognized timezones from ISO 8601 alike timestamps
  1429. m = re.search(r'\d{1,2}:\d{1,2}(?:\.\d+)?(?P<tz>\s*[A-Z]+)$', date_str)
  1430. if m:
  1431. date_str = date_str[:-len(m.group('tz'))]
  1432. # Python only supports microseconds, so remove nanoseconds
  1433. m = re.search(r'^([0-9]{4,}-[0-9]{1,2}-[0-9]{1,2}T[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}\.[0-9]{6})[0-9]+$', date_str)
  1434. if m:
  1435. date_str = m.group(1)
  1436. for expression in date_formats(day_first):
  1437. with contextlib.suppress(ValueError):
  1438. dt = datetime.datetime.strptime(date_str, expression) - timezone + datetime.timedelta(hours=pm_delta)
  1439. return calendar.timegm(dt.timetuple())
  1440. timetuple = email.utils.parsedate_tz(date_str)
  1441. if timetuple:
  1442. return calendar.timegm(timetuple) + pm_delta * 3600
  1443. def determine_ext(url, default_ext='unknown_video'):
  1444. if url is None or '.' not in url:
  1445. return default_ext
  1446. guess = url.partition('?')[0].rpartition('.')[2]
  1447. if re.match(r'^[A-Za-z0-9]+$', guess):
  1448. return guess
  1449. # Try extract ext from URLs like http://example.com/foo/bar.mp4/?download
  1450. elif guess.rstrip('/') in KNOWN_EXTENSIONS:
  1451. return guess.rstrip('/')
  1452. else:
  1453. return default_ext
  1454. def subtitles_filename(filename, sub_lang, sub_format, expected_real_ext=None):
  1455. return replace_extension(filename, sub_lang + '.' + sub_format, expected_real_ext)
  1456. def datetime_from_str(date_str, precision='auto', format='%Y%m%d'):
  1457. R"""
  1458. Return a datetime object from a string.
  1459. Supported format:
  1460. (now|today|yesterday|DATE)([+-]\d+(microsecond|second|minute|hour|day|week|month|year)s?)?
  1461. @param format strftime format of DATE
  1462. @param precision Round the datetime object: auto|microsecond|second|minute|hour|day
  1463. auto: round to the unit provided in date_str (if applicable).
  1464. """
  1465. auto_precision = False
  1466. if precision == 'auto':
  1467. auto_precision = True
  1468. precision = 'microsecond'
  1469. today = datetime_round(datetime.datetime.utcnow(), precision)
  1470. if date_str in ('now', 'today'):
  1471. return today
  1472. if date_str == 'yesterday':
  1473. return today - datetime.timedelta(days=1)
  1474. match = re.match(
  1475. r'(?P<start>.+)(?P<sign>[+-])(?P<time>\d+)(?P<unit>microsecond|second|minute|hour|day|week|month|year)s?',
  1476. date_str)
  1477. if match is not None:
  1478. start_time = datetime_from_str(match.group('start'), precision, format)
  1479. time = int(match.group('time')) * (-1 if match.group('sign') == '-' else 1)
  1480. unit = match.group('unit')
  1481. if unit == 'month' or unit == 'year':
  1482. new_date = datetime_add_months(start_time, time * 12 if unit == 'year' else time)
  1483. unit = 'day'
  1484. else:
  1485. if unit == 'week':
  1486. unit = 'day'
  1487. time *= 7
  1488. delta = datetime.timedelta(**{unit + 's': time})
  1489. new_date = start_time + delta
  1490. if auto_precision:
  1491. return datetime_round(new_date, unit)
  1492. return new_date
  1493. return datetime_round(datetime.datetime.strptime(date_str, format), precision)
  1494. def date_from_str(date_str, format='%Y%m%d', strict=False):
  1495. R"""
  1496. Return a date object from a string using datetime_from_str
  1497. @param strict Restrict allowed patterns to "YYYYMMDD" and
  1498. (now|today|yesterday)(-\d+(day|week|month|year)s?)?
  1499. """
  1500. if strict and not re.fullmatch(r'\d{8}|(now|today|yesterday)(-\d+(day|week|month|year)s?)?', date_str):
  1501. raise ValueError(f'Invalid date format "{date_str}"')
  1502. return datetime_from_str(date_str, precision='microsecond', format=format).date()
  1503. def datetime_add_months(dt, months):
  1504. """Increment/Decrement a datetime object by months."""
  1505. month = dt.month + months - 1
  1506. year = dt.year + month // 12
  1507. month = month % 12 + 1
  1508. day = min(dt.day, calendar.monthrange(year, month)[1])
  1509. return dt.replace(year, month, day)
  1510. def datetime_round(dt, precision='day'):
  1511. """
  1512. Round a datetime object's time to a specific precision
  1513. """
  1514. if precision == 'microsecond':
  1515. return dt
  1516. unit_seconds = {
  1517. 'day': 86400,
  1518. 'hour': 3600,
  1519. 'minute': 60,
  1520. 'second': 1,
  1521. }
  1522. roundto = lambda x, n: ((x + n / 2) // n) * n
  1523. timestamp = calendar.timegm(dt.timetuple())
  1524. return datetime.datetime.utcfromtimestamp(roundto(timestamp, unit_seconds[precision]))
  1525. def hyphenate_date(date_str):
  1526. """
  1527. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  1528. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  1529. if match is not None:
  1530. return '-'.join(match.groups())
  1531. else:
  1532. return date_str
  1533. class DateRange:
  1534. """Represents a time interval between two dates"""
  1535. def __init__(self, start=None, end=None):
  1536. """start and end must be strings in the format accepted by date"""
  1537. if start is not None:
  1538. self.start = date_from_str(start, strict=True)
  1539. else:
  1540. self.start = datetime.datetime.min.date()
  1541. if end is not None:
  1542. self.end = date_from_str(end, strict=True)
  1543. else:
  1544. self.end = datetime.datetime.max.date()
  1545. if self.start > self.end:
  1546. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  1547. @classmethod
  1548. def day(cls, day):
  1549. """Returns a range that only contains the given day"""
  1550. return cls(day, day)
  1551. def __contains__(self, date):
  1552. """Check if the date is in the range"""
  1553. if not isinstance(date, datetime.date):
  1554. date = date_from_str(date)
  1555. return self.start <= date <= self.end
  1556. def __str__(self):
  1557. return f'{self.start.isoformat()} - {self.end.isoformat()}'
  1558. def __eq__(self, other):
  1559. return (isinstance(other, DateRange)
  1560. and self.start == other.start and self.end == other.end)
  1561. def platform_name():
  1562. """ Returns the platform name as a str """
  1563. write_string('DeprecationWarning: yt_dlp.utils.platform_name is deprecated, use platform.platform instead')
  1564. return platform.platform()
  1565. @functools.cache
  1566. def system_identifier():
  1567. python_implementation = platform.python_implementation()
  1568. if python_implementation == 'PyPy' and hasattr(sys, 'pypy_version_info'):
  1569. python_implementation += ' version %d.%d.%d' % sys.pypy_version_info[:3]
  1570. return 'Python %s (%s %s) - %s %s' % (
  1571. platform.python_version(),
  1572. python_implementation,
  1573. platform.architecture()[0],
  1574. platform.platform(),
  1575. format_field(join_nonempty(*platform.libc_ver(), delim=' '), None, '(%s)'),
  1576. )
  1577. @functools.cache
  1578. def get_windows_version():
  1579. ''' Get Windows version. returns () if it's not running on Windows '''
  1580. if compat_os_name == 'nt':
  1581. return version_tuple(platform.win32_ver()[1])
  1582. else:
  1583. return ()
  1584. def write_string(s, out=None, encoding=None):
  1585. assert isinstance(s, str)
  1586. out = out or sys.stderr
  1587. if compat_os_name == 'nt' and supports_terminal_sequences(out):
  1588. s = re.sub(r'([\r\n]+)', r' \1', s)
  1589. enc, buffer = None, out
  1590. if 'b' in getattr(out, 'mode', ''):
  1591. enc = encoding or preferredencoding()
  1592. elif hasattr(out, 'buffer'):
  1593. buffer = out.buffer
  1594. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  1595. buffer.write(s.encode(enc, 'ignore') if enc else s)
  1596. out.flush()
  1597. def bytes_to_intlist(bs):
  1598. if not bs:
  1599. return []
  1600. if isinstance(bs[0], int): # Python 3
  1601. return list(bs)
  1602. else:
  1603. return [ord(c) for c in bs]
  1604. def intlist_to_bytes(xs):
  1605. if not xs:
  1606. return b''
  1607. return struct.pack('%dB' % len(xs), *xs)
  1608. class LockingUnsupportedError(OSError):
  1609. msg = 'File locking is not supported'
  1610. def __init__(self):
  1611. super().__init__(self.msg)
  1612. # Cross-platform file locking
  1613. if sys.platform == 'win32':
  1614. import ctypes.wintypes
  1615. import msvcrt
  1616. class OVERLAPPED(ctypes.Structure):
  1617. _fields_ = [
  1618. ('Internal', ctypes.wintypes.LPVOID),
  1619. ('InternalHigh', ctypes.wintypes.LPVOID),
  1620. ('Offset', ctypes.wintypes.DWORD),
  1621. ('OffsetHigh', ctypes.wintypes.DWORD),
  1622. ('hEvent', ctypes.wintypes.HANDLE),
  1623. ]
  1624. kernel32 = ctypes.windll.kernel32
  1625. LockFileEx = kernel32.LockFileEx
  1626. LockFileEx.argtypes = [
  1627. ctypes.wintypes.HANDLE, # hFile
  1628. ctypes.wintypes.DWORD, # dwFlags
  1629. ctypes.wintypes.DWORD, # dwReserved
  1630. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1631. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1632. ctypes.POINTER(OVERLAPPED) # Overlapped
  1633. ]
  1634. LockFileEx.restype = ctypes.wintypes.BOOL
  1635. UnlockFileEx = kernel32.UnlockFileEx
  1636. UnlockFileEx.argtypes = [
  1637. ctypes.wintypes.HANDLE, # hFile
  1638. ctypes.wintypes.DWORD, # dwReserved
  1639. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  1640. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  1641. ctypes.POINTER(OVERLAPPED) # Overlapped
  1642. ]
  1643. UnlockFileEx.restype = ctypes.wintypes.BOOL
  1644. whole_low = 0xffffffff
  1645. whole_high = 0x7fffffff
  1646. def _lock_file(f, exclusive, block):
  1647. overlapped = OVERLAPPED()
  1648. overlapped.Offset = 0
  1649. overlapped.OffsetHigh = 0
  1650. overlapped.hEvent = 0
  1651. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  1652. if not LockFileEx(msvcrt.get_osfhandle(f.fileno()),
  1653. (0x2 if exclusive else 0x0) | (0x0 if block else 0x1),
  1654. 0, whole_low, whole_high, f._lock_file_overlapped_p):
  1655. # NB: No argument form of "ctypes.FormatError" does not work on PyPy
  1656. raise BlockingIOError(f'Locking file failed: {ctypes.FormatError(ctypes.GetLastError())!r}')
  1657. def _unlock_file(f):
  1658. assert f._lock_file_overlapped_p
  1659. handle = msvcrt.get_osfhandle(f.fileno())
  1660. if not UnlockFileEx(handle, 0, whole_low, whole_high, f._lock_file_overlapped_p):
  1661. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  1662. else:
  1663. try:
  1664. import fcntl
  1665. def _lock_file(f, exclusive, block):
  1666. flags = fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH
  1667. if not block:
  1668. flags |= fcntl.LOCK_NB
  1669. try:
  1670. fcntl.flock(f, flags)
  1671. except BlockingIOError:
  1672. raise
  1673. except OSError: # AOSP does not have flock()
  1674. fcntl.lockf(f, flags)
  1675. def _unlock_file(f):
  1676. try:
  1677. fcntl.flock(f, fcntl.LOCK_UN)
  1678. except OSError:
  1679. fcntl.lockf(f, fcntl.LOCK_UN)
  1680. except ImportError:
  1681. def _lock_file(f, exclusive, block):
  1682. raise LockingUnsupportedError()
  1683. def _unlock_file(f):
  1684. raise LockingUnsupportedError()
  1685. class locked_file:
  1686. locked = False
  1687. def __init__(self, filename, mode, block=True, encoding=None):
  1688. if mode not in {'r', 'rb', 'a', 'ab', 'w', 'wb'}:
  1689. raise NotImplementedError(mode)
  1690. self.mode, self.block = mode, block
  1691. writable = any(f in mode for f in 'wax+')
  1692. readable = any(f in mode for f in 'r+')
  1693. flags = functools.reduce(operator.ior, (
  1694. getattr(os, 'O_CLOEXEC', 0), # UNIX only
  1695. getattr(os, 'O_BINARY', 0), # Windows only
  1696. getattr(os, 'O_NOINHERIT', 0), # Windows only
  1697. os.O_CREAT if writable else 0, # O_TRUNC only after locking
  1698. os.O_APPEND if 'a' in mode else 0,
  1699. os.O_EXCL if 'x' in mode else 0,
  1700. os.O_RDONLY if not writable else os.O_RDWR if readable else os.O_WRONLY,
  1701. ))
  1702. self.f = os.fdopen(os.open(filename, flags, 0o666), mode, encoding=encoding)
  1703. def __enter__(self):
  1704. exclusive = 'r' not in self.mode
  1705. try:
  1706. _lock_file(self.f, exclusive, self.block)
  1707. self.locked = True
  1708. except OSError:
  1709. self.f.close()
  1710. raise
  1711. if 'w' in self.mode:
  1712. try:
  1713. self.f.truncate()
  1714. except OSError as e:
  1715. if e.errno not in (
  1716. errno.ESPIPE, # Illegal seek - expected for FIFO
  1717. errno.EINVAL, # Invalid argument - expected for /dev/null
  1718. ):
  1719. raise
  1720. return self
  1721. def unlock(self):
  1722. if not self.locked:
  1723. return
  1724. try:
  1725. _unlock_file(self.f)
  1726. finally:
  1727. self.locked = False
  1728. def __exit__(self, *_):
  1729. try:
  1730. self.unlock()
  1731. finally:
  1732. self.f.close()
  1733. open = __enter__
  1734. close = __exit__
  1735. def __getattr__(self, attr):
  1736. return getattr(self.f, attr)
  1737. def __iter__(self):
  1738. return iter(self.f)
  1739. @functools.cache
  1740. def get_filesystem_encoding():
  1741. encoding = sys.getfilesystemencoding()
  1742. return encoding if encoding is not None else 'utf-8'
  1743. def shell_quote(args):
  1744. quoted_args = []
  1745. encoding = get_filesystem_encoding()
  1746. for a in args:
  1747. if isinstance(a, bytes):
  1748. # We may get a filename encoded with 'encodeFilename'
  1749. a = a.decode(encoding)
  1750. quoted_args.append(compat_shlex_quote(a))
  1751. return ' '.join(quoted_args)
  1752. def smuggle_url(url, data):
  1753. """ Pass additional data in a URL for internal use. """
  1754. url, idata = unsmuggle_url(url, {})
  1755. data.update(idata)
  1756. sdata = urllib.parse.urlencode(
  1757. {'__youtubedl_smuggle': json.dumps(data)})
  1758. return url + '#' + sdata
  1759. def unsmuggle_url(smug_url, default=None):
  1760. if '#__youtubedl_smuggle' not in smug_url:
  1761. return smug_url, default
  1762. url, _, sdata = smug_url.rpartition('#')
  1763. jsond = urllib.parse.parse_qs(sdata)['__youtubedl_smuggle'][0]
  1764. data = json.loads(jsond)
  1765. return url, data
  1766. def format_decimal_suffix(num, fmt='%d%s', *, factor=1000):
  1767. """ Formats numbers with decimal sufixes like K, M, etc """
  1768. num, factor = float_or_none(num), float(factor)
  1769. if num is None or num < 0:
  1770. return None
  1771. POSSIBLE_SUFFIXES = 'kMGTPEZY'
  1772. exponent = 0 if num == 0 else min(int(math.log(num, factor)), len(POSSIBLE_SUFFIXES))
  1773. suffix = ['', *POSSIBLE_SUFFIXES][exponent]
  1774. if factor == 1024:
  1775. suffix = {'k': 'Ki', '': ''}.get(suffix, f'{suffix}i')
  1776. converted = num / (factor ** exponent)
  1777. return fmt % (converted, suffix)
  1778. def format_bytes(bytes):
  1779. return format_decimal_suffix(bytes, '%.2f%sB', factor=1024) or 'N/A'
  1780. def lookup_unit_table(unit_table, s):
  1781. units_re = '|'.join(re.escape(u) for u in unit_table)
  1782. m = re.match(
  1783. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)\b' % units_re, s)
  1784. if not m:
  1785. return None
  1786. num_str = m.group('num').replace(',', '.')
  1787. mult = unit_table[m.group('unit')]
  1788. return int(float(num_str) * mult)
  1789. def parse_filesize(s):
  1790. if s is None:
  1791. return None
  1792. # The lower-case forms are of course incorrect and unofficial,
  1793. # but we support those too
  1794. _UNIT_TABLE = {
  1795. 'B': 1,
  1796. 'b': 1,
  1797. 'bytes': 1,
  1798. 'KiB': 1024,
  1799. 'KB': 1000,
  1800. 'kB': 1024,
  1801. 'Kb': 1000,
  1802. 'kb': 1000,
  1803. 'kilobytes': 1000,
  1804. 'kibibytes': 1024,
  1805. 'MiB': 1024 ** 2,
  1806. 'MB': 1000 ** 2,
  1807. 'mB': 1024 ** 2,
  1808. 'Mb': 1000 ** 2,
  1809. 'mb': 1000 ** 2,
  1810. 'megabytes': 1000 ** 2,
  1811. 'mebibytes': 1024 ** 2,
  1812. 'GiB': 1024 ** 3,
  1813. 'GB': 1000 ** 3,
  1814. 'gB': 1024 ** 3,
  1815. 'Gb': 1000 ** 3,
  1816. 'gb': 1000 ** 3,
  1817. 'gigabytes': 1000 ** 3,
  1818. 'gibibytes': 1024 ** 3,
  1819. 'TiB': 1024 ** 4,
  1820. 'TB': 1000 ** 4,
  1821. 'tB': 1024 ** 4,
  1822. 'Tb': 1000 ** 4,
  1823. 'tb': 1000 ** 4,
  1824. 'terabytes': 1000 ** 4,
  1825. 'tebibytes': 1024 ** 4,
  1826. 'PiB': 1024 ** 5,
  1827. 'PB': 1000 ** 5,
  1828. 'pB': 1024 ** 5,
  1829. 'Pb': 1000 ** 5,
  1830. 'pb': 1000 ** 5,
  1831. 'petabytes': 1000 ** 5,
  1832. 'pebibytes': 1024 ** 5,
  1833. 'EiB': 1024 ** 6,
  1834. 'EB': 1000 ** 6,
  1835. 'eB': 1024 ** 6,
  1836. 'Eb': 1000 ** 6,
  1837. 'eb': 1000 ** 6,
  1838. 'exabytes': 1000 ** 6,
  1839. 'exbibytes': 1024 ** 6,
  1840. 'ZiB': 1024 ** 7,
  1841. 'ZB': 1000 ** 7,
  1842. 'zB': 1024 ** 7,
  1843. 'Zb': 1000 ** 7,
  1844. 'zb': 1000 ** 7,
  1845. 'zettabytes': 1000 ** 7,
  1846. 'zebibytes': 1024 ** 7,
  1847. 'YiB': 1024 ** 8,
  1848. 'YB': 1000 ** 8,
  1849. 'yB': 1024 ** 8,
  1850. 'Yb': 1000 ** 8,
  1851. 'yb': 1000 ** 8,
  1852. 'yottabytes': 1000 ** 8,
  1853. 'yobibytes': 1024 ** 8,
  1854. }
  1855. return lookup_unit_table(_UNIT_TABLE, s)
  1856. def parse_count(s):
  1857. if s is None:
  1858. return None
  1859. s = re.sub(r'^[^\d]+\s', '', s).strip()
  1860. if re.match(r'^[\d,.]+$', s):
  1861. return str_to_int(s)
  1862. _UNIT_TABLE = {
  1863. 'k': 1000,
  1864. 'K': 1000,
  1865. 'm': 1000 ** 2,
  1866. 'M': 1000 ** 2,
  1867. 'kk': 1000 ** 2,
  1868. 'KK': 1000 ** 2,
  1869. 'b': 1000 ** 3,
  1870. 'B': 1000 ** 3,
  1871. }
  1872. ret = lookup_unit_table(_UNIT_TABLE, s)
  1873. if ret is not None:
  1874. return ret
  1875. mobj = re.match(r'([\d,.]+)(?:$|\s)', s)
  1876. if mobj:
  1877. return str_to_int(mobj.group(1))
  1878. def parse_resolution(s, *, lenient=False):
  1879. if s is None:
  1880. return {}
  1881. if lenient:
  1882. mobj = re.search(r'(?P<w>\d+)\s*[xX×,]\s*(?P<h>\d+)', s)
  1883. else:
  1884. mobj = re.search(r'(?<![a-zA-Z0-9])(?P<w>\d+)\s*[xX×,]\s*(?P<h>\d+)(?![a-zA-Z0-9])', s)
  1885. if mobj:
  1886. return {
  1887. 'width': int(mobj.group('w')),
  1888. 'height': int(mobj.group('h')),
  1889. }
  1890. mobj = re.search(r'(?<![a-zA-Z0-9])(\d+)[pPiI](?![a-zA-Z0-9])', s)
  1891. if mobj:
  1892. return {'height': int(mobj.group(1))}
  1893. mobj = re.search(r'\b([48])[kK]\b', s)
  1894. if mobj:
  1895. return {'height': int(mobj.group(1)) * 540}
  1896. return {}
  1897. def parse_bitrate(s):
  1898. if not isinstance(s, str):
  1899. return
  1900. mobj = re.search(r'\b(\d+)\s*kbps', s)
  1901. if mobj:
  1902. return int(mobj.group(1))
  1903. def month_by_name(name, lang='en'):
  1904. """ Return the number of a month by (locale-independently) English name """
  1905. month_names = MONTH_NAMES.get(lang, MONTH_NAMES['en'])
  1906. try:
  1907. return month_names.index(name) + 1
  1908. except ValueError:
  1909. return None
  1910. def month_by_abbreviation(abbrev):
  1911. """ Return the number of a month by (locale-independently) English
  1912. abbreviations """
  1913. try:
  1914. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  1915. except ValueError:
  1916. return None
  1917. def fix_xml_ampersands(xml_str):
  1918. """Replace all the '&' by '&amp;' in XML"""
  1919. return re.sub(
  1920. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1921. '&amp;',
  1922. xml_str)
  1923. def setproctitle(title):
  1924. assert isinstance(title, str)
  1925. # ctypes in Jython is not complete
  1926. # http://bugs.jython.org/issue2148
  1927. if sys.platform.startswith('java'):
  1928. return
  1929. try:
  1930. libc = ctypes.cdll.LoadLibrary('libc.so.6')
  1931. except OSError:
  1932. return
  1933. except TypeError:
  1934. # LoadLibrary in Windows Python 2.7.13 only expects
  1935. # a bytestring, but since unicode_literals turns
  1936. # every string into a unicode string, it fails.
  1937. return
  1938. title_bytes = title.encode()
  1939. buf = ctypes.create_string_buffer(len(title_bytes))
  1940. buf.value = title_bytes
  1941. try:
  1942. libc.prctl(15, buf, 0, 0, 0)
  1943. except AttributeError:
  1944. return # Strange libc, just skip this
  1945. def remove_start(s, start):
  1946. return s[len(start):] if s is not None and s.startswith(start) else s
  1947. def remove_end(s, end):
  1948. return s[:-len(end)] if s is not None and s.endswith(end) else s
  1949. def remove_quotes(s):
  1950. if s is None or len(s) < 2:
  1951. return s
  1952. for quote in ('"', "'", ):
  1953. if s[0] == quote and s[-1] == quote:
  1954. return s[1:-1]
  1955. return s
  1956. def get_domain(url):
  1957. """
  1958. This implementation is inconsistent, but is kept for compatibility.
  1959. Use this only for "webpage_url_domain"
  1960. """
  1961. return remove_start(urllib.parse.urlparse(url).netloc, 'www.') or None
  1962. def url_basename(url):
  1963. path = urllib.parse.urlparse(url).path
  1964. return path.strip('/').split('/')[-1]
  1965. def base_url(url):
  1966. return re.match(r'https?://[^?#&]+/', url).group()
  1967. def urljoin(base, path):
  1968. if isinstance(path, bytes):
  1969. path = path.decode()
  1970. if not isinstance(path, str) or not path:
  1971. return None
  1972. if re.match(r'^(?:[a-zA-Z][a-zA-Z0-9+-.]*:)?//', path):
  1973. return path
  1974. if isinstance(base, bytes):
  1975. base = base.decode()
  1976. if not isinstance(base, str) or not re.match(
  1977. r'^(?:https?:)?//', base):
  1978. return None
  1979. return urllib.parse.urljoin(base, path)
  1980. class HEADRequest(urllib.request.Request):
  1981. def get_method(self):
  1982. return 'HEAD'
  1983. class PUTRequest(urllib.request.Request):
  1984. def get_method(self):
  1985. return 'PUT'
  1986. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1987. if get_attr and v is not None:
  1988. v = getattr(v, get_attr, None)
  1989. try:
  1990. return int(v) * invscale // scale
  1991. except (ValueError, TypeError, OverflowError):
  1992. return default
  1993. def str_or_none(v, default=None):
  1994. return default if v is None else str(v)
  1995. def str_to_int(int_str):
  1996. """ A more relaxed version of int_or_none """
  1997. if isinstance(int_str, int):
  1998. return int_str
  1999. elif isinstance(int_str, str):
  2000. int_str = re.sub(r'[,\.\+]', '', int_str)
  2001. return int_or_none(int_str)
  2002. def float_or_none(v, scale=1, invscale=1, default=None):
  2003. if v is None:
  2004. return default
  2005. try:
  2006. return float(v) * invscale / scale
  2007. except (ValueError, TypeError):
  2008. return default
  2009. def bool_or_none(v, default=None):
  2010. return v if isinstance(v, bool) else default
  2011. def strip_or_none(v, default=None):
  2012. return v.strip() if isinstance(v, str) else default
  2013. def url_or_none(url):
  2014. if not url or not isinstance(url, str):
  2015. return None
  2016. url = url.strip()
  2017. return url if re.match(r'^(?:(?:https?|rt(?:m(?:pt?[es]?|fp)|sp[su]?)|mms|ftps?):)?//', url) else None
  2018. def request_to_url(req):
  2019. if isinstance(req, urllib.request.Request):
  2020. return req.get_full_url()
  2021. else:
  2022. return req
  2023. def strftime_or_none(timestamp, date_format, default=None):
  2024. datetime_object = None
  2025. try:
  2026. if isinstance(timestamp, (int, float)): # unix timestamp
  2027. datetime_object = datetime.datetime.utcfromtimestamp(timestamp)
  2028. elif isinstance(timestamp, str): # assume YYYYMMDD
  2029. datetime_object = datetime.datetime.strptime(timestamp, '%Y%m%d')
  2030. return datetime_object.strftime(date_format)
  2031. except (ValueError, TypeError, AttributeError):
  2032. return default
  2033. def parse_duration(s):
  2034. if not isinstance(s, str):
  2035. return None
  2036. s = s.strip()
  2037. if not s:
  2038. return None
  2039. days, hours, mins, secs, ms = [None] * 5
  2040. m = re.match(r'''(?x)
  2041. (?P<before_secs>
  2042. (?:(?:(?P<days>[0-9]+):)?(?P<hours>[0-9]+):)?(?P<mins>[0-9]+):)?
  2043. (?P<secs>(?(before_secs)[0-9]{1,2}|[0-9]+))
  2044. (?P<ms>[.:][0-9]+)?Z?$
  2045. ''', s)
  2046. if m:
  2047. days, hours, mins, secs, ms = m.group('days', 'hours', 'mins', 'secs', 'ms')
  2048. else:
  2049. m = re.match(
  2050. r'''(?ix)(?:P?
  2051. (?:
  2052. [0-9]+\s*y(?:ears?)?,?\s*
  2053. )?
  2054. (?:
  2055. [0-9]+\s*m(?:onths?)?,?\s*
  2056. )?
  2057. (?:
  2058. [0-9]+\s*w(?:eeks?)?,?\s*
  2059. )?
  2060. (?:
  2061. (?P<days>[0-9]+)\s*d(?:ays?)?,?\s*
  2062. )?
  2063. T)?
  2064. (?:
  2065. (?P<hours>[0-9]+)\s*h(?:ours?)?,?\s*
  2066. )?
  2067. (?:
  2068. (?P<mins>[0-9]+)\s*m(?:in(?:ute)?s?)?,?\s*
  2069. )?
  2070. (?:
  2071. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*s(?:ec(?:ond)?s?)?\s*
  2072. )?Z?$''', s)
  2073. if m:
  2074. days, hours, mins, secs, ms = m.groups()
  2075. else:
  2076. m = re.match(r'(?i)(?:(?P<hours>[0-9.]+)\s*(?:hours?)|(?P<mins>[0-9.]+)\s*(?:mins?\.?|minutes?)\s*)Z?$', s)
  2077. if m:
  2078. hours, mins = m.groups()
  2079. else:
  2080. return None
  2081. if ms:
  2082. ms = ms.replace(':', '.')
  2083. return sum(float(part or 0) * mult for part, mult in (
  2084. (days, 86400), (hours, 3600), (mins, 60), (secs, 1), (ms, 1)))
  2085. def prepend_extension(filename, ext, expected_real_ext=None):
  2086. name, real_ext = os.path.splitext(filename)
  2087. return (
  2088. f'{name}.{ext}{real_ext}'
  2089. if not expected_real_ext or real_ext[1:] == expected_real_ext
  2090. else f'{filename}.{ext}')
  2091. def replace_extension(filename, ext, expected_real_ext=None):
  2092. name, real_ext = os.path.splitext(filename)
  2093. return '{}.{}'.format(
  2094. name if not expected_real_ext or real_ext[1:] == expected_real_ext else filename,
  2095. ext)
  2096. def check_executable(exe, args=[]):
  2097. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  2098. args can be a list of arguments for a short output (like -version) """
  2099. try:
  2100. Popen.run([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  2101. except OSError:
  2102. return False
  2103. return exe
  2104. def _get_exe_version_output(exe, args, *, to_screen=None):
  2105. if to_screen:
  2106. to_screen(f'Checking exe version: {shell_quote([exe] + args)}')
  2107. try:
  2108. # STDIN should be redirected too. On UNIX-like systems, ffmpeg triggers
  2109. # SIGTTOU if yt-dlp is run in the background.
  2110. # See https://github.com/ytdl-org/youtube-dl/issues/955#issuecomment-209789656
  2111. stdout, _, _ = Popen.run([encodeArgument(exe)] + args, text=True,
  2112. stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  2113. except OSError:
  2114. return False
  2115. return stdout
  2116. def detect_exe_version(output, version_re=None, unrecognized='present'):
  2117. assert isinstance(output, str)
  2118. if version_re is None:
  2119. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  2120. m = re.search(version_re, output)
  2121. if m:
  2122. return m.group(1)
  2123. else:
  2124. return unrecognized
  2125. def get_exe_version(exe, args=['--version'],
  2126. version_re=None, unrecognized='present'):
  2127. """ Returns the version of the specified executable,
  2128. or False if the executable is not present """
  2129. out = _get_exe_version_output(exe, args)
  2130. return detect_exe_version(out, version_re, unrecognized) if out else False
  2131. def frange(start=0, stop=None, step=1):
  2132. """Float range"""
  2133. if stop is None:
  2134. start, stop = 0, start
  2135. sign = [-1, 1][step > 0] if step else 0
  2136. while sign * start < sign * stop:
  2137. yield start
  2138. start += step
  2139. class LazyList(collections.abc.Sequence):
  2140. """Lazy immutable list from an iterable
  2141. Note that slices of a LazyList are lists and not LazyList"""
  2142. class IndexError(IndexError):
  2143. pass
  2144. def __init__(self, iterable, *, reverse=False, _cache=None):
  2145. self._iterable = iter(iterable)
  2146. self._cache = [] if _cache is None else _cache
  2147. self._reversed = reverse
  2148. def __iter__(self):
  2149. if self._reversed:
  2150. # We need to consume the entire iterable to iterate in reverse
  2151. yield from self.exhaust()
  2152. return
  2153. yield from self._cache
  2154. for item in self._iterable:
  2155. self._cache.append(item)
  2156. yield item
  2157. def _exhaust(self):
  2158. self._cache.extend(self._iterable)
  2159. self._iterable = [] # Discard the emptied iterable to make it pickle-able
  2160. return self._cache
  2161. def exhaust(self):
  2162. """Evaluate the entire iterable"""
  2163. return self._exhaust()[::-1 if self._reversed else 1]
  2164. @staticmethod
  2165. def _reverse_index(x):
  2166. return None if x is None else ~x
  2167. def __getitem__(self, idx):
  2168. if isinstance(idx, slice):
  2169. if self._reversed:
  2170. idx = slice(self._reverse_index(idx.start), self._reverse_index(idx.stop), -(idx.step or 1))
  2171. start, stop, step = idx.start, idx.stop, idx.step or 1
  2172. elif isinstance(idx, int):
  2173. if self._reversed:
  2174. idx = self._reverse_index(idx)
  2175. start, stop, step = idx, idx, 0
  2176. else:
  2177. raise TypeError('indices must be integers or slices')
  2178. if ((start or 0) < 0 or (stop or 0) < 0
  2179. or (start is None and step < 0)
  2180. or (stop is None and step > 0)):
  2181. # We need to consume the entire iterable to be able to slice from the end
  2182. # Obviously, never use this with infinite iterables
  2183. self._exhaust()
  2184. try:
  2185. return self._cache[idx]
  2186. except IndexError as e:
  2187. raise self.IndexError(e) from e
  2188. n = max(start or 0, stop or 0) - len(self._cache) + 1
  2189. if n > 0:
  2190. self._cache.extend(itertools.islice(self._iterable, n))
  2191. try:
  2192. return self._cache[idx]
  2193. except IndexError as e:
  2194. raise self.IndexError(e) from e
  2195. def __bool__(self):
  2196. try:
  2197. self[-1] if self._reversed else self[0]
  2198. except self.IndexError:
  2199. return False
  2200. return True
  2201. def __len__(self):
  2202. self._exhaust()
  2203. return len(self._cache)
  2204. def __reversed__(self):
  2205. return type(self)(self._iterable, reverse=not self._reversed, _cache=self._cache)
  2206. def __copy__(self):
  2207. return type(self)(self._iterable, reverse=self._reversed, _cache=self._cache)
  2208. def __repr__(self):
  2209. # repr and str should mimic a list. So we exhaust the iterable
  2210. return repr(self.exhaust())
  2211. def __str__(self):
  2212. return repr(self.exhaust())
  2213. class PagedList:
  2214. class IndexError(IndexError):
  2215. pass
  2216. def __len__(self):
  2217. # This is only useful for tests
  2218. return len(self.getslice())
  2219. def __init__(self, pagefunc, pagesize, use_cache=True):
  2220. self._pagefunc = pagefunc
  2221. self._pagesize = pagesize
  2222. self._pagecount = float('inf')
  2223. self._use_cache = use_cache
  2224. self._cache = {}
  2225. def getpage(self, pagenum):
  2226. page_results = self._cache.get(pagenum)
  2227. if page_results is None:
  2228. page_results = [] if pagenum > self._pagecount else list(self._pagefunc(pagenum))
  2229. if self._use_cache:
  2230. self._cache[pagenum] = page_results
  2231. return page_results
  2232. def getslice(self, start=0, end=None):
  2233. return list(self._getslice(start, end))
  2234. def _getslice(self, start, end):
  2235. raise NotImplementedError('This method must be implemented by subclasses')
  2236. def __getitem__(self, idx):
  2237. assert self._use_cache, 'Indexing PagedList requires cache'
  2238. if not isinstance(idx, int) or idx < 0:
  2239. raise TypeError('indices must be non-negative integers')
  2240. entries = self.getslice(idx, idx + 1)
  2241. if not entries:
  2242. raise self.IndexError()
  2243. return entries[0]
  2244. class OnDemandPagedList(PagedList):
  2245. """Download pages until a page with less than maximum results"""
  2246. def _getslice(self, start, end):
  2247. for pagenum in itertools.count(start // self._pagesize):
  2248. firstid = pagenum * self._pagesize
  2249. nextfirstid = pagenum * self._pagesize + self._pagesize
  2250. if start >= nextfirstid:
  2251. continue
  2252. startv = (
  2253. start % self._pagesize
  2254. if firstid <= start < nextfirstid
  2255. else 0)
  2256. endv = (
  2257. ((end - 1) % self._pagesize) + 1
  2258. if (end is not None and firstid <= end <= nextfirstid)
  2259. else None)
  2260. try:
  2261. page_results = self.getpage(pagenum)
  2262. except Exception:
  2263. self._pagecount = pagenum - 1
  2264. raise
  2265. if startv != 0 or endv is not None:
  2266. page_results = page_results[startv:endv]
  2267. yield from page_results
  2268. # A little optimization - if current page is not "full", ie. does
  2269. # not contain page_size videos then we can assume that this page
  2270. # is the last one - there are no more ids on further pages -
  2271. # i.e. no need to query again.
  2272. if len(page_results) + startv < self._pagesize:
  2273. break
  2274. # If we got the whole page, but the next page is not interesting,
  2275. # break out early as well
  2276. if end == nextfirstid:
  2277. break
  2278. class InAdvancePagedList(PagedList):
  2279. """PagedList with total number of pages known in advance"""
  2280. def __init__(self, pagefunc, pagecount, pagesize):
  2281. PagedList.__init__(self, pagefunc, pagesize, True)
  2282. self._pagecount = pagecount
  2283. def _getslice(self, start, end):
  2284. start_page = start // self._pagesize
  2285. end_page = self._pagecount if end is None else min(self._pagecount, end // self._pagesize + 1)
  2286. skip_elems = start - start_page * self._pagesize
  2287. only_more = None if end is None else end - start
  2288. for pagenum in range(start_page, end_page):
  2289. page_results = self.getpage(pagenum)
  2290. if skip_elems:
  2291. page_results = page_results[skip_elems:]
  2292. skip_elems = None
  2293. if only_more is not None:
  2294. if len(page_results) < only_more:
  2295. only_more -= len(page_results)
  2296. else:
  2297. yield from page_results[:only_more]
  2298. break
  2299. yield from page_results
  2300. class PlaylistEntries:
  2301. MissingEntry = object()
  2302. is_exhausted = False
  2303. def __init__(self, ydl, info_dict):
  2304. self.ydl = ydl
  2305. # _entries must be assigned now since infodict can change during iteration
  2306. entries = info_dict.get('entries')
  2307. if entries is None:
  2308. raise EntryNotInPlaylist('There are no entries')
  2309. elif isinstance(entries, list):
  2310. self.is_exhausted = True
  2311. requested_entries = info_dict.get('requested_entries')
  2312. self.is_incomplete = bool(requested_entries)
  2313. if self.is_incomplete:
  2314. assert self.is_exhausted
  2315. self._entries = [self.MissingEntry] * max(requested_entries)
  2316. for i, entry in zip(requested_entries, entries):
  2317. self._entries[i - 1] = entry
  2318. elif isinstance(entries, (list, PagedList, LazyList)):
  2319. self._entries = entries
  2320. else:
  2321. self._entries = LazyList(entries)
  2322. PLAYLIST_ITEMS_RE = re.compile(r'''(?x)
  2323. (?P<start>[+-]?\d+)?
  2324. (?P<range>[:-]
  2325. (?P<end>[+-]?\d+|inf(?:inite)?)?
  2326. (?::(?P<step>[+-]?\d+))?
  2327. )?''')
  2328. @classmethod
  2329. def parse_playlist_items(cls, string):
  2330. for segment in string.split(','):
  2331. if not segment:
  2332. raise ValueError('There is two or more consecutive commas')
  2333. mobj = cls.PLAYLIST_ITEMS_RE.fullmatch(segment)
  2334. if not mobj:
  2335. raise ValueError(f'{segment!r} is not a valid specification')
  2336. start, end, step, has_range = mobj.group('start', 'end', 'step', 'range')
  2337. if int_or_none(step) == 0:
  2338. raise ValueError(f'Step in {segment!r} cannot be zero')
  2339. yield slice(int_or_none(start), float_or_none(end), int_or_none(step)) if has_range else int(start)
  2340. def get_requested_items(self):
  2341. playlist_items = self.ydl.params.get('playlist_items')
  2342. playlist_start = self.ydl.params.get('playliststart', 1)
  2343. playlist_end = self.ydl.params.get('playlistend')
  2344. # For backwards compatibility, interpret -1 as whole list
  2345. if playlist_end in (-1, None):
  2346. playlist_end = ''
  2347. if not playlist_items:
  2348. playlist_items = f'{playlist_start}:{playlist_end}'
  2349. elif playlist_start != 1 or playlist_end:
  2350. self.ydl.report_warning('Ignoring playliststart and playlistend because playlistitems was given', only_once=True)
  2351. for index in self.parse_playlist_items(playlist_items):
  2352. for i, entry in self[index]:
  2353. yield i, entry
  2354. if not entry:
  2355. continue
  2356. try:
  2357. # TODO: Add auto-generated fields
  2358. self.ydl._match_entry(entry, incomplete=True, silent=True)
  2359. except (ExistingVideoReached, RejectedVideoReached):
  2360. return
  2361. def get_full_count(self):
  2362. if self.is_exhausted and not self.is_incomplete:
  2363. return len(self)
  2364. elif isinstance(self._entries, InAdvancePagedList):
  2365. if self._entries._pagesize == 1:
  2366. return self._entries._pagecount
  2367. @functools.cached_property
  2368. def _getter(self):
  2369. if isinstance(self._entries, list):
  2370. def get_entry(i):
  2371. try:
  2372. entry = self._entries[i]
  2373. except IndexError:
  2374. entry = self.MissingEntry
  2375. if not self.is_incomplete:
  2376. raise self.IndexError()
  2377. if entry is self.MissingEntry:
  2378. raise EntryNotInPlaylist(f'Entry {i} cannot be found')
  2379. return entry
  2380. else:
  2381. def get_entry(i):
  2382. try:
  2383. return type(self.ydl)._handle_extraction_exceptions(lambda _, i: self._entries[i])(self.ydl, i)
  2384. except (LazyList.IndexError, PagedList.IndexError):
  2385. raise self.IndexError()
  2386. return get_entry
  2387. def __getitem__(self, idx):
  2388. if isinstance(idx, int):
  2389. idx = slice(idx, idx)
  2390. # NB: PlaylistEntries[1:10] => (0, 1, ... 9)
  2391. step = 1 if idx.step is None else idx.step
  2392. if idx.start is None:
  2393. start = 0 if step > 0 else len(self) - 1
  2394. else:
  2395. start = idx.start - 1 if idx.start >= 0 else len(self) + idx.start
  2396. # NB: Do not call len(self) when idx == [:]
  2397. if idx.stop is None:
  2398. stop = 0 if step < 0 else float('inf')
  2399. else:
  2400. stop = idx.stop - 1 if idx.stop >= 0 else len(self) + idx.stop
  2401. stop += [-1, 1][step > 0]
  2402. for i in frange(start, stop, step):
  2403. if i < 0:
  2404. continue
  2405. try:
  2406. entry = self._getter(i)
  2407. except self.IndexError:
  2408. self.is_exhausted = True
  2409. if step > 0:
  2410. break
  2411. continue
  2412. yield i + 1, entry
  2413. def __len__(self):
  2414. return len(tuple(self[:]))
  2415. class IndexError(IndexError):
  2416. pass
  2417. def uppercase_escape(s):
  2418. unicode_escape = codecs.getdecoder('unicode_escape')
  2419. return re.sub(
  2420. r'\\U[0-9a-fA-F]{8}',
  2421. lambda m: unicode_escape(m.group(0))[0],
  2422. s)
  2423. def lowercase_escape(s):
  2424. unicode_escape = codecs.getdecoder('unicode_escape')
  2425. return re.sub(
  2426. r'\\u[0-9a-fA-F]{4}',
  2427. lambda m: unicode_escape(m.group(0))[0],
  2428. s)
  2429. def escape_rfc3986(s):
  2430. """Escape non-ASCII characters as suggested by RFC 3986"""
  2431. return urllib.parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  2432. def escape_url(url):
  2433. """Escape URL as suggested by RFC 3986"""
  2434. url_parsed = urllib.parse.urlparse(url)
  2435. return url_parsed._replace(
  2436. netloc=url_parsed.netloc.encode('idna').decode('ascii'),
  2437. path=escape_rfc3986(url_parsed.path),
  2438. params=escape_rfc3986(url_parsed.params),
  2439. query=escape_rfc3986(url_parsed.query),
  2440. fragment=escape_rfc3986(url_parsed.fragment)
  2441. ).geturl()
  2442. def parse_qs(url):
  2443. return urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
  2444. def read_batch_urls(batch_fd):
  2445. def fixup(url):
  2446. if not isinstance(url, str):
  2447. url = url.decode('utf-8', 'replace')
  2448. BOM_UTF8 = ('\xef\xbb\xbf', '\ufeff')
  2449. for bom in BOM_UTF8:
  2450. if url.startswith(bom):
  2451. url = url[len(bom):]
  2452. url = url.lstrip()
  2453. if not url or url.startswith(('#', ';', ']')):
  2454. return False
  2455. # "#" cannot be stripped out since it is part of the URI
  2456. # However, it can be safely stripped out if following a whitespace
  2457. return re.split(r'\s#', url, 1)[0].rstrip()
  2458. with contextlib.closing(batch_fd) as fd:
  2459. return [url for url in map(fixup, fd) if url]
  2460. def urlencode_postdata(*args, **kargs):
  2461. return urllib.parse.urlencode(*args, **kargs).encode('ascii')
  2462. def update_url_query(url, query):
  2463. if not query:
  2464. return url
  2465. parsed_url = urllib.parse.urlparse(url)
  2466. qs = urllib.parse.parse_qs(parsed_url.query)
  2467. qs.update(query)
  2468. return urllib.parse.urlunparse(parsed_url._replace(
  2469. query=urllib.parse.urlencode(qs, True)))
  2470. def update_Request(req, url=None, data=None, headers=None, query=None):
  2471. req_headers = req.headers.copy()
  2472. req_headers.update(headers or {})
  2473. req_data = data or req.data
  2474. req_url = update_url_query(url or req.get_full_url(), query)
  2475. req_get_method = req.get_method()
  2476. if req_get_method == 'HEAD':
  2477. req_type = HEADRequest
  2478. elif req_get_method == 'PUT':
  2479. req_type = PUTRequest
  2480. else:
  2481. req_type = urllib.request.Request
  2482. new_req = req_type(
  2483. req_url, data=req_data, headers=req_headers,
  2484. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  2485. if hasattr(req, 'timeout'):
  2486. new_req.timeout = req.timeout
  2487. return new_req
  2488. def _multipart_encode_impl(data, boundary):
  2489. content_type = 'multipart/form-data; boundary=%s' % boundary
  2490. out = b''
  2491. for k, v in data.items():
  2492. out += b'--' + boundary.encode('ascii') + b'\r\n'
  2493. if isinstance(k, str):
  2494. k = k.encode()
  2495. if isinstance(v, str):
  2496. v = v.encode()
  2497. # RFC 2047 requires non-ASCII field names to be encoded, while RFC 7578
  2498. # suggests sending UTF-8 directly. Firefox sends UTF-8, too
  2499. content = b'Content-Disposition: form-data; name="' + k + b'"\r\n\r\n' + v + b'\r\n'
  2500. if boundary.encode('ascii') in content:
  2501. raise ValueError('Boundary overlaps with data')
  2502. out += content
  2503. out += b'--' + boundary.encode('ascii') + b'--\r\n'
  2504. return out, content_type
  2505. def multipart_encode(data, boundary=None):
  2506. '''
  2507. Encode a dict to RFC 7578-compliant form-data
  2508. data:
  2509. A dict where keys and values can be either Unicode or bytes-like
  2510. objects.
  2511. boundary:
  2512. If specified a Unicode object, it's used as the boundary. Otherwise
  2513. a random boundary is generated.
  2514. Reference: https://tools.ietf.org/html/rfc7578
  2515. '''
  2516. has_specified_boundary = boundary is not None
  2517. while True:
  2518. if boundary is None:
  2519. boundary = '---------------' + str(random.randrange(0x0fffffff, 0xffffffff))
  2520. try:
  2521. out, content_type = _multipart_encode_impl(data, boundary)
  2522. break
  2523. except ValueError:
  2524. if has_specified_boundary:
  2525. raise
  2526. boundary = None
  2527. return out, content_type
  2528. def dict_get(d, key_or_keys, default=None, skip_false_values=True):
  2529. for val in map(d.get, variadic(key_or_keys)):
  2530. if val is not None and (val or not skip_false_values):
  2531. return val
  2532. return default
  2533. def try_call(*funcs, expected_type=None, args=[], kwargs={}):
  2534. for f in funcs:
  2535. try:
  2536. val = f(*args, **kwargs)
  2537. except (AttributeError, KeyError, TypeError, IndexError, ZeroDivisionError):
  2538. pass
  2539. else:
  2540. if expected_type is None or isinstance(val, expected_type):
  2541. return val
  2542. def try_get(src, getter, expected_type=None):
  2543. return try_call(*variadic(getter), args=(src,), expected_type=expected_type)
  2544. def filter_dict(dct, cndn=lambda _, v: v is not None):
  2545. return {k: v for k, v in dct.items() if cndn(k, v)}
  2546. def merge_dicts(*dicts):
  2547. merged = {}
  2548. for a_dict in dicts:
  2549. for k, v in a_dict.items():
  2550. if (v is not None and k not in merged
  2551. or isinstance(v, str) and merged[k] == ''):
  2552. merged[k] = v
  2553. return merged
  2554. def encode_compat_str(string, encoding=preferredencoding(), errors='strict'):
  2555. return string if isinstance(string, str) else str(string, encoding, errors)
  2556. US_RATINGS = {
  2557. 'G': 0,
  2558. 'PG': 10,
  2559. 'PG-13': 13,
  2560. 'R': 16,
  2561. 'NC': 18,
  2562. }
  2563. TV_PARENTAL_GUIDELINES = {
  2564. 'TV-Y': 0,
  2565. 'TV-Y7': 7,
  2566. 'TV-G': 0,
  2567. 'TV-PG': 0,
  2568. 'TV-14': 14,
  2569. 'TV-MA': 17,
  2570. }
  2571. def parse_age_limit(s):
  2572. # isinstance(False, int) is True. So type() must be used instead
  2573. if type(s) is int: # noqa: E721
  2574. return s if 0 <= s <= 21 else None
  2575. elif not isinstance(s, str):
  2576. return None
  2577. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  2578. if m:
  2579. return int(m.group('age'))
  2580. s = s.upper()
  2581. if s in US_RATINGS:
  2582. return US_RATINGS[s]
  2583. m = re.match(r'^TV[_-]?(%s)$' % '|'.join(k[3:] for k in TV_PARENTAL_GUIDELINES), s)
  2584. if m:
  2585. return TV_PARENTAL_GUIDELINES['TV-' + m.group(1)]
  2586. return None
  2587. def strip_jsonp(code):
  2588. return re.sub(
  2589. r'''(?sx)^
  2590. (?:window\.)?(?P<func_name>[a-zA-Z0-9_.$]*)
  2591. (?:\s*&&\s*(?P=func_name))?
  2592. \s*\(\s*(?P<callback_data>.*)\);?
  2593. \s*?(?://[^\n]*)*$''',
  2594. r'\g<callback_data>', code)
  2595. def js_to_json(code, vars={}):
  2596. # vars is a dict of var, val pairs to substitute
  2597. COMMENT_RE = r'/\*(?:(?!\*/).)*?\*/|//[^\n]*\n'
  2598. SKIP_RE = fr'\s*(?:{COMMENT_RE})?\s*'
  2599. INTEGER_TABLE = (
  2600. (fr'(?s)^(0[xX][0-9a-fA-F]+){SKIP_RE}:?$', 16),
  2601. (fr'(?s)^(0+[0-7]+){SKIP_RE}:?$', 8),
  2602. )
  2603. def fix_kv(m):
  2604. v = m.group(0)
  2605. if v in ('true', 'false', 'null'):
  2606. return v
  2607. elif v in ('undefined', 'void 0'):
  2608. return 'null'
  2609. elif v.startswith('/*') or v.startswith('//') or v.startswith('!') or v == ',':
  2610. return ""
  2611. if v[0] in ("'", '"'):
  2612. v = re.sub(r'(?s)\\.|"', lambda m: {
  2613. '"': '\\"',
  2614. "\\'": "'",
  2615. '\\\n': '',
  2616. '\\x': '\\u00',
  2617. }.get(m.group(0), m.group(0)), v[1:-1])
  2618. else:
  2619. for regex, base in INTEGER_TABLE:
  2620. im = re.match(regex, v)
  2621. if im:
  2622. i = int(im.group(1), base)
  2623. return '"%d":' % i if v.endswith(':') else '%d' % i
  2624. if v in vars:
  2625. return vars[v]
  2626. return '"%s"' % v
  2627. def create_map(mobj):
  2628. return json.dumps(dict(json.loads(js_to_json(mobj.group(1) or '[]', vars=vars))))
  2629. code = re.sub(r'new Date\((".+")\)', r'\g<1>', code)
  2630. code = re.sub(r'new Map\((\[.*?\])?\)', create_map, code)
  2631. return re.sub(r'''(?sx)
  2632. "(?:[^"\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^"\\]*"|
  2633. '(?:[^'\\]*(?:\\\\|\\['"nurtbfx/\n]))*[^'\\]*'|
  2634. {comment}|,(?={skip}[\]}}])|
  2635. void\s0|(?:(?<![0-9])[eE]|[a-df-zA-DF-Z_$])[.a-zA-Z_$0-9]*|
  2636. \b(?:0[xX][0-9a-fA-F]+|0+[0-7]+)(?:{skip}:)?|
  2637. [0-9]+(?={skip}:)|
  2638. !+
  2639. '''.format(comment=COMMENT_RE, skip=SKIP_RE), fix_kv, code)
  2640. def qualities(quality_ids):
  2641. """ Get a numeric quality value out of a list of possible values """
  2642. def q(qid):
  2643. try:
  2644. return quality_ids.index(qid)
  2645. except ValueError:
  2646. return -1
  2647. return q
  2648. POSTPROCESS_WHEN = ('pre_process', 'after_filter', 'before_dl', 'post_process', 'after_move', 'after_video', 'playlist')
  2649. DEFAULT_OUTTMPL = {
  2650. 'default': '%(title)s [%(id)s].%(ext)s',
  2651. 'chapter': '%(title)s - %(section_number)03d %(section_title)s [%(id)s].%(ext)s',
  2652. }
  2653. OUTTMPL_TYPES = {
  2654. 'chapter': None,
  2655. 'subtitle': None,
  2656. 'thumbnail': None,
  2657. 'description': 'description',
  2658. 'annotation': 'annotations.xml',
  2659. 'infojson': 'info.json',
  2660. 'link': None,
  2661. 'pl_video': None,
  2662. 'pl_thumbnail': None,
  2663. 'pl_description': 'description',
  2664. 'pl_infojson': 'info.json',
  2665. }
  2666. # As of [1] format syntax is:
  2667. # %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type
  2668. # 1. https://docs.python.org/2/library/stdtypes.html#string-formatting
  2669. STR_FORMAT_RE_TMPL = r'''(?x)
  2670. (?<!%)(?P<prefix>(?:%%)*)
  2671. %
  2672. (?P<has_key>\((?P<key>{0})\))?
  2673. (?P<format>
  2674. (?P<conversion>[#0\-+ ]+)?
  2675. (?P<min_width>\d+)?
  2676. (?P<precision>\.\d+)?
  2677. (?P<len_mod>[hlL])? # unused in python
  2678. {1} # conversion type
  2679. )
  2680. '''
  2681. STR_FORMAT_TYPES = 'diouxXeEfFgGcrs'
  2682. def limit_length(s, length):
  2683. """ Add ellipses to overly long strings """
  2684. if s is None:
  2685. return None
  2686. ELLIPSES = '...'
  2687. if len(s) > length:
  2688. return s[:length - len(ELLIPSES)] + ELLIPSES
  2689. return s
  2690. def version_tuple(v):
  2691. return tuple(int(e) for e in re.split(r'[-.]', v))
  2692. def is_outdated_version(version, limit, assume_new=True):
  2693. if not version:
  2694. return not assume_new
  2695. try:
  2696. return version_tuple(version) < version_tuple(limit)
  2697. except ValueError:
  2698. return not assume_new
  2699. def ytdl_is_updateable():
  2700. """ Returns if yt-dlp can be updated with -U """
  2701. from .update import is_non_updateable
  2702. return not is_non_updateable()
  2703. def args_to_str(args):
  2704. # Get a short string representation for a subprocess command
  2705. return ' '.join(compat_shlex_quote(a) for a in args)
  2706. def error_to_compat_str(err):
  2707. return str(err)
  2708. def error_to_str(err):
  2709. return f'{type(err).__name__}: {err}'
  2710. def mimetype2ext(mt):
  2711. if mt is None:
  2712. return None
  2713. mt, _, params = mt.partition(';')
  2714. mt = mt.strip()
  2715. FULL_MAP = {
  2716. 'audio/mp4': 'm4a',
  2717. # Per RFC 3003, audio/mpeg can be .mp1, .mp2 or .mp3. Here use .mp3 as
  2718. # it's the most popular one
  2719. 'audio/mpeg': 'mp3',
  2720. 'audio/x-wav': 'wav',
  2721. 'audio/wav': 'wav',
  2722. 'audio/wave': 'wav',
  2723. }
  2724. ext = FULL_MAP.get(mt)
  2725. if ext is not None:
  2726. return ext
  2727. SUBTYPE_MAP = {
  2728. '3gpp': '3gp',
  2729. 'smptett+xml': 'tt',
  2730. 'ttaf+xml': 'dfxp',
  2731. 'ttml+xml': 'ttml',
  2732. 'x-flv': 'flv',
  2733. 'x-mp4-fragmented': 'mp4',
  2734. 'x-ms-sami': 'sami',
  2735. 'x-ms-wmv': 'wmv',
  2736. 'mpegurl': 'm3u8',
  2737. 'x-mpegurl': 'm3u8',
  2738. 'vnd.apple.mpegurl': 'm3u8',
  2739. 'dash+xml': 'mpd',
  2740. 'f4m+xml': 'f4m',
  2741. 'hds+xml': 'f4m',
  2742. 'vnd.ms-sstr+xml': 'ism',
  2743. 'quicktime': 'mov',
  2744. 'mp2t': 'ts',
  2745. 'x-wav': 'wav',
  2746. 'filmstrip+json': 'fs',
  2747. 'svg+xml': 'svg',
  2748. }
  2749. _, _, subtype = mt.rpartition('/')
  2750. ext = SUBTYPE_MAP.get(subtype.lower())
  2751. if ext is not None:
  2752. return ext
  2753. SUFFIX_MAP = {
  2754. 'json': 'json',
  2755. 'xml': 'xml',
  2756. 'zip': 'zip',
  2757. 'gzip': 'gz',
  2758. }
  2759. _, _, suffix = subtype.partition('+')
  2760. ext = SUFFIX_MAP.get(suffix)
  2761. if ext is not None:
  2762. return ext
  2763. return subtype.replace('+', '.')
  2764. def ext2mimetype(ext_or_url):
  2765. if not ext_or_url:
  2766. return None
  2767. if '.' not in ext_or_url:
  2768. ext_or_url = f'file.{ext_or_url}'
  2769. return mimetypes.guess_type(ext_or_url)[0]
  2770. def parse_codecs(codecs_str):
  2771. # http://tools.ietf.org/html/rfc6381
  2772. if not codecs_str:
  2773. return {}
  2774. split_codecs = list(filter(None, map(
  2775. str.strip, codecs_str.strip().strip(',').split(','))))
  2776. vcodec, acodec, scodec, hdr = None, None, None, None
  2777. for full_codec in split_codecs:
  2778. parts = re.sub(r'0+(?=\d)', '', full_codec).split('.')
  2779. if parts[0] in ('avc1', 'avc2', 'avc3', 'avc4', 'vp9', 'vp8', 'hev1', 'hev2',
  2780. 'h263', 'h264', 'mp4v', 'hvc1', 'av1', 'theora', 'dvh1', 'dvhe'):
  2781. if vcodec:
  2782. continue
  2783. vcodec = full_codec
  2784. if parts[0] in ('dvh1', 'dvhe'):
  2785. hdr = 'DV'
  2786. elif parts[0] == 'av1' and traverse_obj(parts, 3) == '10':
  2787. hdr = 'HDR10'
  2788. elif parts[:2] == ['vp9', '2']:
  2789. hdr = 'HDR10'
  2790. elif parts[0] in ('flac', 'mp4a', 'opus', 'vorbis', 'mp3', 'aac',
  2791. 'ac-3', 'ec-3', 'eac3', 'dtsc', 'dtse', 'dtsh', 'dtsl'):
  2792. acodec = acodec or full_codec
  2793. elif parts[0] in ('stpp', 'wvtt'):
  2794. scodec = scodec or full_codec
  2795. else:
  2796. write_string(f'WARNING: Unknown codec {full_codec}\n')
  2797. if vcodec or acodec or scodec:
  2798. return {
  2799. 'vcodec': vcodec or 'none',
  2800. 'acodec': acodec or 'none',
  2801. 'dynamic_range': hdr,
  2802. **({'scodec': scodec} if scodec is not None else {}),
  2803. }
  2804. elif len(split_codecs) == 2:
  2805. return {
  2806. 'vcodec': split_codecs[0],
  2807. 'acodec': split_codecs[1],
  2808. }
  2809. return {}
  2810. def urlhandle_detect_ext(url_handle):
  2811. getheader = url_handle.headers.get
  2812. cd = getheader('Content-Disposition')
  2813. if cd:
  2814. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  2815. if m:
  2816. e = determine_ext(m.group('filename'), default_ext=None)
  2817. if e:
  2818. return e
  2819. return mimetype2ext(getheader('Content-Type'))
  2820. def encode_data_uri(data, mime_type):
  2821. return 'data:%s;base64,%s' % (mime_type, base64.b64encode(data).decode('ascii'))
  2822. def age_restricted(content_limit, age_limit):
  2823. """ Returns True iff the content should be blocked """
  2824. if age_limit is None: # No limit set
  2825. return False
  2826. if content_limit is None:
  2827. return False # Content available for everyone
  2828. return age_limit < content_limit
  2829. # List of known byte-order-marks (BOM)
  2830. BOMS = [
  2831. (b'\xef\xbb\xbf', 'utf-8'),
  2832. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  2833. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  2834. (b'\xff\xfe', 'utf-16-le'),
  2835. (b'\xfe\xff', 'utf-16-be'),
  2836. ]
  2837. def is_html(first_bytes):
  2838. """ Detect whether a file contains HTML by examining its first bytes. """
  2839. encoding = 'utf-8'
  2840. for bom, enc in BOMS:
  2841. while first_bytes.startswith(bom):
  2842. encoding, first_bytes = enc, first_bytes[len(bom):]
  2843. return re.match(r'^\s*<', first_bytes.decode(encoding, 'replace'))
  2844. def determine_protocol(info_dict):
  2845. protocol = info_dict.get('protocol')
  2846. if protocol is not None:
  2847. return protocol
  2848. url = sanitize_url(info_dict['url'])
  2849. if url.startswith('rtmp'):
  2850. return 'rtmp'
  2851. elif url.startswith('mms'):
  2852. return 'mms'
  2853. elif url.startswith('rtsp'):
  2854. return 'rtsp'
  2855. ext = determine_ext(url)
  2856. if ext == 'm3u8':
  2857. return 'm3u8'
  2858. elif ext == 'f4m':
  2859. return 'f4m'
  2860. return urllib.parse.urlparse(url).scheme
  2861. def render_table(header_row, data, delim=False, extra_gap=0, hide_empty=False):
  2862. """ Render a list of rows, each as a list of values.
  2863. Text after a \t will be right aligned """
  2864. def width(string):
  2865. return len(remove_terminal_sequences(string).replace('\t', ''))
  2866. def get_max_lens(table):
  2867. return [max(width(str(v)) for v in col) for col in zip(*table)]
  2868. def filter_using_list(row, filterArray):
  2869. return [col for take, col in itertools.zip_longest(filterArray, row, fillvalue=True) if take]
  2870. max_lens = get_max_lens(data) if hide_empty else []
  2871. header_row = filter_using_list(header_row, max_lens)
  2872. data = [filter_using_list(row, max_lens) for row in data]
  2873. table = [header_row] + data
  2874. max_lens = get_max_lens(table)
  2875. extra_gap += 1
  2876. if delim:
  2877. table = [header_row, [delim * (ml + extra_gap) for ml in max_lens]] + data
  2878. table[1][-1] = table[1][-1][:-extra_gap * len(delim)] # Remove extra_gap from end of delimiter
  2879. for row in table:
  2880. for pos, text in enumerate(map(str, row)):
  2881. if '\t' in text:
  2882. row[pos] = text.replace('\t', ' ' * (max_lens[pos] - width(text))) + ' ' * extra_gap
  2883. else:
  2884. row[pos] = text + ' ' * (max_lens[pos] - width(text) + extra_gap)
  2885. ret = '\n'.join(''.join(row).rstrip() for row in table)
  2886. return ret
  2887. def _match_one(filter_part, dct, incomplete):
  2888. # TODO: Generalize code with YoutubeDL._build_format_filter
  2889. STRING_OPERATORS = {
  2890. '*=': operator.contains,
  2891. '^=': lambda attr, value: attr.startswith(value),
  2892. '$=': lambda attr, value: attr.endswith(value),
  2893. '~=': lambda attr, value: re.search(value, attr),
  2894. }
  2895. COMPARISON_OPERATORS = {
  2896. **STRING_OPERATORS,
  2897. '<=': operator.le, # "<=" must be defined above "<"
  2898. '<': operator.lt,
  2899. '>=': operator.ge,
  2900. '>': operator.gt,
  2901. '=': operator.eq,
  2902. }
  2903. if isinstance(incomplete, bool):
  2904. is_incomplete = lambda _: incomplete
  2905. else:
  2906. is_incomplete = lambda k: k in incomplete
  2907. operator_rex = re.compile(r'''(?x)
  2908. (?P<key>[a-z_]+)
  2909. \s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  2910. (?:
  2911. (?P<quote>["\'])(?P<quotedstrval>.+?)(?P=quote)|
  2912. (?P<strval>.+?)
  2913. )
  2914. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  2915. m = operator_rex.fullmatch(filter_part.strip())
  2916. if m:
  2917. m = m.groupdict()
  2918. unnegated_op = COMPARISON_OPERATORS[m['op']]
  2919. if m['negation']:
  2920. op = lambda attr, value: not unnegated_op(attr, value)
  2921. else:
  2922. op = unnegated_op
  2923. comparison_value = m['quotedstrval'] or m['strval'] or m['intval']
  2924. if m['quote']:
  2925. comparison_value = comparison_value.replace(r'\%s' % m['quote'], m['quote'])
  2926. actual_value = dct.get(m['key'])
  2927. numeric_comparison = None
  2928. if isinstance(actual_value, (int, float)):
  2929. # If the original field is a string and matching comparisonvalue is
  2930. # a number we should respect the origin of the original field
  2931. # and process comparison value as a string (see
  2932. # https://github.com/ytdl-org/youtube-dl/issues/11082)
  2933. try:
  2934. numeric_comparison = int(comparison_value)
  2935. except ValueError:
  2936. numeric_comparison = parse_filesize(comparison_value)
  2937. if numeric_comparison is None:
  2938. numeric_comparison = parse_filesize(f'{comparison_value}B')
  2939. if numeric_comparison is None:
  2940. numeric_comparison = parse_duration(comparison_value)
  2941. if numeric_comparison is not None and m['op'] in STRING_OPERATORS:
  2942. raise ValueError('Operator %s only supports string values!' % m['op'])
  2943. if actual_value is None:
  2944. return is_incomplete(m['key']) or m['none_inclusive']
  2945. return op(actual_value, comparison_value if numeric_comparison is None else numeric_comparison)
  2946. UNARY_OPERATORS = {
  2947. '': lambda v: (v is True) if isinstance(v, bool) else (v is not None),
  2948. '!': lambda v: (v is False) if isinstance(v, bool) else (v is None),
  2949. }
  2950. operator_rex = re.compile(r'''(?x)
  2951. (?P<op>%s)\s*(?P<key>[a-z_]+)
  2952. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  2953. m = operator_rex.fullmatch(filter_part.strip())
  2954. if m:
  2955. op = UNARY_OPERATORS[m.group('op')]
  2956. actual_value = dct.get(m.group('key'))
  2957. if is_incomplete(m.group('key')) and actual_value is None:
  2958. return True
  2959. return op(actual_value)
  2960. raise ValueError('Invalid filter part %r' % filter_part)
  2961. def match_str(filter_str, dct, incomplete=False):
  2962. """ Filter a dictionary with a simple string syntax.
  2963. @returns Whether the filter passes
  2964. @param incomplete Set of keys that is expected to be missing from dct.
  2965. Can be True/False to indicate all/none of the keys may be missing.
  2966. All conditions on incomplete keys pass if the key is missing
  2967. """
  2968. return all(
  2969. _match_one(filter_part.replace(r'\&', '&'), dct, incomplete)
  2970. for filter_part in re.split(r'(?<!\\)&', filter_str))
  2971. def match_filter_func(filters):
  2972. if not filters:
  2973. return None
  2974. filters = set(variadic(filters))
  2975. interactive = '-' in filters
  2976. if interactive:
  2977. filters.remove('-')
  2978. def _match_func(info_dict, incomplete=False):
  2979. if not filters or any(match_str(f, info_dict, incomplete) for f in filters):
  2980. return NO_DEFAULT if interactive and not incomplete else None
  2981. else:
  2982. video_title = info_dict.get('title') or info_dict.get('id') or 'entry'
  2983. filter_str = ') | ('.join(map(str.strip, filters))
  2984. return f'{video_title} does not pass filter ({filter_str}), skipping ..'
  2985. return _match_func
  2986. class download_range_func:
  2987. def __init__(self, chapters, ranges):
  2988. self.chapters, self.ranges = chapters, ranges
  2989. def __call__(self, info_dict, ydl):
  2990. warning = ('There are no chapters matching the regex' if info_dict.get('chapters')
  2991. else 'Cannot match chapters since chapter information is unavailable')
  2992. for regex in self.chapters or []:
  2993. for i, chapter in enumerate(info_dict.get('chapters') or []):
  2994. if re.search(regex, chapter['title']):
  2995. warning = None
  2996. yield {**chapter, 'index': i}
  2997. if self.chapters and warning:
  2998. ydl.to_screen(f'[info] {info_dict["id"]}: {warning}')
  2999. yield from ({'start_time': start, 'end_time': end} for start, end in self.ranges or [])
  3000. def __eq__(self, other):
  3001. return (isinstance(other, download_range_func)
  3002. and self.chapters == other.chapters and self.ranges == other.ranges)
  3003. def parse_dfxp_time_expr(time_expr):
  3004. if not time_expr:
  3005. return
  3006. mobj = re.match(rf'^(?P<time_offset>{NUMBER_RE})s?$', time_expr)
  3007. if mobj:
  3008. return float(mobj.group('time_offset'))
  3009. mobj = re.match(r'^(\d+):(\d\d):(\d\d(?:(?:\.|:)\d+)?)$', time_expr)
  3010. if mobj:
  3011. return 3600 * int(mobj.group(1)) + 60 * int(mobj.group(2)) + float(mobj.group(3).replace(':', '.'))
  3012. def srt_subtitles_timecode(seconds):
  3013. return '%02d:%02d:%02d,%03d' % timetuple_from_msec(seconds * 1000)
  3014. def ass_subtitles_timecode(seconds):
  3015. time = timetuple_from_msec(seconds * 1000)
  3016. return '%01d:%02d:%02d.%02d' % (*time[:-1], time.milliseconds / 10)
  3017. def dfxp2srt(dfxp_data):
  3018. '''
  3019. @param dfxp_data A bytes-like object containing DFXP data
  3020. @returns A unicode object containing converted SRT data
  3021. '''
  3022. LEGACY_NAMESPACES = (
  3023. (b'http://www.w3.org/ns/ttml', [
  3024. b'http://www.w3.org/2004/11/ttaf1',
  3025. b'http://www.w3.org/2006/04/ttaf1',
  3026. b'http://www.w3.org/2006/10/ttaf1',
  3027. ]),
  3028. (b'http://www.w3.org/ns/ttml#styling', [
  3029. b'http://www.w3.org/ns/ttml#style',
  3030. ]),
  3031. )
  3032. SUPPORTED_STYLING = [
  3033. 'color',
  3034. 'fontFamily',
  3035. 'fontSize',
  3036. 'fontStyle',
  3037. 'fontWeight',
  3038. 'textDecoration'
  3039. ]
  3040. _x = functools.partial(xpath_with_ns, ns_map={
  3041. 'xml': 'http://www.w3.org/XML/1998/namespace',
  3042. 'ttml': 'http://www.w3.org/ns/ttml',
  3043. 'tts': 'http://www.w3.org/ns/ttml#styling',
  3044. })
  3045. styles = {}
  3046. default_style = {}
  3047. class TTMLPElementParser:
  3048. _out = ''
  3049. _unclosed_elements = []
  3050. _applied_styles = []
  3051. def start(self, tag, attrib):
  3052. if tag in (_x('ttml:br'), 'br'):
  3053. self._out += '\n'
  3054. else:
  3055. unclosed_elements = []
  3056. style = {}
  3057. element_style_id = attrib.get('style')
  3058. if default_style:
  3059. style.update(default_style)
  3060. if element_style_id:
  3061. style.update(styles.get(element_style_id, {}))
  3062. for prop in SUPPORTED_STYLING:
  3063. prop_val = attrib.get(_x('tts:' + prop))
  3064. if prop_val:
  3065. style[prop] = prop_val
  3066. if style:
  3067. font = ''
  3068. for k, v in sorted(style.items()):
  3069. if self._applied_styles and self._applied_styles[-1].get(k) == v:
  3070. continue
  3071. if k == 'color':
  3072. font += ' color="%s"' % v
  3073. elif k == 'fontSize':
  3074. font += ' size="%s"' % v
  3075. elif k == 'fontFamily':
  3076. font += ' face="%s"' % v
  3077. elif k == 'fontWeight' and v == 'bold':
  3078. self._out += '<b>'
  3079. unclosed_elements.append('b')
  3080. elif k == 'fontStyle' and v == 'italic':
  3081. self._out += '<i>'
  3082. unclosed_elements.append('i')
  3083. elif k == 'textDecoration' and v == 'underline':
  3084. self._out += '<u>'
  3085. unclosed_elements.append('u')
  3086. if font:
  3087. self._out += '<font' + font + '>'
  3088. unclosed_elements.append('font')
  3089. applied_style = {}
  3090. if self._applied_styles:
  3091. applied_style.update(self._applied_styles[-1])
  3092. applied_style.update(style)
  3093. self._applied_styles.append(applied_style)
  3094. self._unclosed_elements.append(unclosed_elements)
  3095. def end(self, tag):
  3096. if tag not in (_x('ttml:br'), 'br'):
  3097. unclosed_elements = self._unclosed_elements.pop()
  3098. for element in reversed(unclosed_elements):
  3099. self._out += '</%s>' % element
  3100. if unclosed_elements and self._applied_styles:
  3101. self._applied_styles.pop()
  3102. def data(self, data):
  3103. self._out += data
  3104. def close(self):
  3105. return self._out.strip()
  3106. def parse_node(node):
  3107. target = TTMLPElementParser()
  3108. parser = xml.etree.ElementTree.XMLParser(target=target)
  3109. parser.feed(xml.etree.ElementTree.tostring(node))
  3110. return parser.close()
  3111. for k, v in LEGACY_NAMESPACES:
  3112. for ns in v:
  3113. dfxp_data = dfxp_data.replace(ns, k)
  3114. dfxp = compat_etree_fromstring(dfxp_data)
  3115. out = []
  3116. paras = dfxp.findall(_x('.//ttml:p')) or dfxp.findall('.//p')
  3117. if not paras:
  3118. raise ValueError('Invalid dfxp/TTML subtitle')
  3119. repeat = False
  3120. while True:
  3121. for style in dfxp.findall(_x('.//ttml:style')):
  3122. style_id = style.get('id') or style.get(_x('xml:id'))
  3123. if not style_id:
  3124. continue
  3125. parent_style_id = style.get('style')
  3126. if parent_style_id:
  3127. if parent_style_id not in styles:
  3128. repeat = True
  3129. continue
  3130. styles[style_id] = styles[parent_style_id].copy()
  3131. for prop in SUPPORTED_STYLING:
  3132. prop_val = style.get(_x('tts:' + prop))
  3133. if prop_val:
  3134. styles.setdefault(style_id, {})[prop] = prop_val
  3135. if repeat:
  3136. repeat = False
  3137. else:
  3138. break
  3139. for p in ('body', 'div'):
  3140. ele = xpath_element(dfxp, [_x('.//ttml:' + p), './/' + p])
  3141. if ele is None:
  3142. continue
  3143. style = styles.get(ele.get('style'))
  3144. if not style:
  3145. continue
  3146. default_style.update(style)
  3147. for para, index in zip(paras, itertools.count(1)):
  3148. begin_time = parse_dfxp_time_expr(para.attrib.get('begin'))
  3149. end_time = parse_dfxp_time_expr(para.attrib.get('end'))
  3150. dur = parse_dfxp_time_expr(para.attrib.get('dur'))
  3151. if begin_time is None:
  3152. continue
  3153. if not end_time:
  3154. if not dur:
  3155. continue
  3156. end_time = begin_time + dur
  3157. out.append('%d\n%s --> %s\n%s\n\n' % (
  3158. index,
  3159. srt_subtitles_timecode(begin_time),
  3160. srt_subtitles_timecode(end_time),
  3161. parse_node(para)))
  3162. return ''.join(out)
  3163. def cli_option(params, command_option, param, separator=None):
  3164. param = params.get(param)
  3165. return ([] if param is None
  3166. else [command_option, str(param)] if separator is None
  3167. else [f'{command_option}{separator}{param}'])
  3168. def cli_bool_option(params, command_option, param, true_value='true', false_value='false', separator=None):
  3169. param = params.get(param)
  3170. assert param in (True, False, None)
  3171. return cli_option({True: true_value, False: false_value}, command_option, param, separator)
  3172. def cli_valueless_option(params, command_option, param, expected_value=True):
  3173. return [command_option] if params.get(param) == expected_value else []
  3174. def cli_configuration_args(argdict, keys, default=[], use_compat=True):
  3175. if isinstance(argdict, (list, tuple)): # for backward compatibility
  3176. if use_compat:
  3177. return argdict
  3178. else:
  3179. argdict = None
  3180. if argdict is None:
  3181. return default
  3182. assert isinstance(argdict, dict)
  3183. assert isinstance(keys, (list, tuple))
  3184. for key_list in keys:
  3185. arg_list = list(filter(
  3186. lambda x: x is not None,
  3187. [argdict.get(key.lower()) for key in variadic(key_list)]))
  3188. if arg_list:
  3189. return [arg for args in arg_list for arg in args]
  3190. return default
  3191. def _configuration_args(main_key, argdict, exe, keys=None, default=[], use_compat=True):
  3192. main_key, exe = main_key.lower(), exe.lower()
  3193. root_key = exe if main_key == exe else f'{main_key}+{exe}'
  3194. keys = [f'{root_key}{k}' for k in (keys or [''])]
  3195. if root_key in keys:
  3196. if main_key != exe:
  3197. keys.append((main_key, exe))
  3198. keys.append('default')
  3199. else:
  3200. use_compat = False
  3201. return cli_configuration_args(argdict, keys, default, use_compat)
  3202. class ISO639Utils:
  3203. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  3204. _lang_map = {
  3205. 'aa': 'aar',
  3206. 'ab': 'abk',
  3207. 'ae': 'ave',
  3208. 'af': 'afr',
  3209. 'ak': 'aka',
  3210. 'am': 'amh',
  3211. 'an': 'arg',
  3212. 'ar': 'ara',
  3213. 'as': 'asm',
  3214. 'av': 'ava',
  3215. 'ay': 'aym',
  3216. 'az': 'aze',
  3217. 'ba': 'bak',
  3218. 'be': 'bel',
  3219. 'bg': 'bul',
  3220. 'bh': 'bih',
  3221. 'bi': 'bis',
  3222. 'bm': 'bam',
  3223. 'bn': 'ben',
  3224. 'bo': 'bod',
  3225. 'br': 'bre',
  3226. 'bs': 'bos',
  3227. 'ca': 'cat',
  3228. 'ce': 'che',
  3229. 'ch': 'cha',
  3230. 'co': 'cos',
  3231. 'cr': 'cre',
  3232. 'cs': 'ces',
  3233. 'cu': 'chu',
  3234. 'cv': 'chv',
  3235. 'cy': 'cym',
  3236. 'da': 'dan',
  3237. 'de': 'deu',
  3238. 'dv': 'div',
  3239. 'dz': 'dzo',
  3240. 'ee': 'ewe',
  3241. 'el': 'ell',
  3242. 'en': 'eng',
  3243. 'eo': 'epo',
  3244. 'es': 'spa',
  3245. 'et': 'est',
  3246. 'eu': 'eus',
  3247. 'fa': 'fas',
  3248. 'ff': 'ful',
  3249. 'fi': 'fin',
  3250. 'fj': 'fij',
  3251. 'fo': 'fao',
  3252. 'fr': 'fra',
  3253. 'fy': 'fry',
  3254. 'ga': 'gle',
  3255. 'gd': 'gla',
  3256. 'gl': 'glg',
  3257. 'gn': 'grn',
  3258. 'gu': 'guj',
  3259. 'gv': 'glv',
  3260. 'ha': 'hau',
  3261. 'he': 'heb',
  3262. 'iw': 'heb', # Replaced by he in 1989 revision
  3263. 'hi': 'hin',
  3264. 'ho': 'hmo',
  3265. 'hr': 'hrv',
  3266. 'ht': 'hat',
  3267. 'hu': 'hun',
  3268. 'hy': 'hye',
  3269. 'hz': 'her',
  3270. 'ia': 'ina',
  3271. 'id': 'ind',
  3272. 'in': 'ind', # Replaced by id in 1989 revision
  3273. 'ie': 'ile',
  3274. 'ig': 'ibo',
  3275. 'ii': 'iii',
  3276. 'ik': 'ipk',
  3277. 'io': 'ido',
  3278. 'is': 'isl',
  3279. 'it': 'ita',
  3280. 'iu': 'iku',
  3281. 'ja': 'jpn',
  3282. 'jv': 'jav',
  3283. 'ka': 'kat',
  3284. 'kg': 'kon',
  3285. 'ki': 'kik',
  3286. 'kj': 'kua',
  3287. 'kk': 'kaz',
  3288. 'kl': 'kal',
  3289. 'km': 'khm',
  3290. 'kn': 'kan',
  3291. 'ko': 'kor',
  3292. 'kr': 'kau',
  3293. 'ks': 'kas',
  3294. 'ku': 'kur',
  3295. 'kv': 'kom',
  3296. 'kw': 'cor',
  3297. 'ky': 'kir',
  3298. 'la': 'lat',
  3299. 'lb': 'ltz',
  3300. 'lg': 'lug',
  3301. 'li': 'lim',
  3302. 'ln': 'lin',
  3303. 'lo': 'lao',
  3304. 'lt': 'lit',
  3305. 'lu': 'lub',
  3306. 'lv': 'lav',
  3307. 'mg': 'mlg',
  3308. 'mh': 'mah',
  3309. 'mi': 'mri',
  3310. 'mk': 'mkd',
  3311. 'ml': 'mal',
  3312. 'mn': 'mon',
  3313. 'mr': 'mar',
  3314. 'ms': 'msa',
  3315. 'mt': 'mlt',
  3316. 'my': 'mya',
  3317. 'na': 'nau',
  3318. 'nb': 'nob',
  3319. 'nd': 'nde',
  3320. 'ne': 'nep',
  3321. 'ng': 'ndo',
  3322. 'nl': 'nld',
  3323. 'nn': 'nno',
  3324. 'no': 'nor',
  3325. 'nr': 'nbl',
  3326. 'nv': 'nav',
  3327. 'ny': 'nya',
  3328. 'oc': 'oci',
  3329. 'oj': 'oji',
  3330. 'om': 'orm',
  3331. 'or': 'ori',
  3332. 'os': 'oss',
  3333. 'pa': 'pan',
  3334. 'pi': 'pli',
  3335. 'pl': 'pol',
  3336. 'ps': 'pus',
  3337. 'pt': 'por',
  3338. 'qu': 'que',
  3339. 'rm': 'roh',
  3340. 'rn': 'run',
  3341. 'ro': 'ron',
  3342. 'ru': 'rus',
  3343. 'rw': 'kin',
  3344. 'sa': 'san',
  3345. 'sc': 'srd',
  3346. 'sd': 'snd',
  3347. 'se': 'sme',
  3348. 'sg': 'sag',
  3349. 'si': 'sin',
  3350. 'sk': 'slk',
  3351. 'sl': 'slv',
  3352. 'sm': 'smo',
  3353. 'sn': 'sna',
  3354. 'so': 'som',
  3355. 'sq': 'sqi',
  3356. 'sr': 'srp',
  3357. 'ss': 'ssw',
  3358. 'st': 'sot',
  3359. 'su': 'sun',
  3360. 'sv': 'swe',
  3361. 'sw': 'swa',
  3362. 'ta': 'tam',
  3363. 'te': 'tel',
  3364. 'tg': 'tgk',
  3365. 'th': 'tha',
  3366. 'ti': 'tir',
  3367. 'tk': 'tuk',
  3368. 'tl': 'tgl',
  3369. 'tn': 'tsn',
  3370. 'to': 'ton',
  3371. 'tr': 'tur',
  3372. 'ts': 'tso',
  3373. 'tt': 'tat',
  3374. 'tw': 'twi',
  3375. 'ty': 'tah',
  3376. 'ug': 'uig',
  3377. 'uk': 'ukr',
  3378. 'ur': 'urd',
  3379. 'uz': 'uzb',
  3380. 've': 'ven',
  3381. 'vi': 'vie',
  3382. 'vo': 'vol',
  3383. 'wa': 'wln',
  3384. 'wo': 'wol',
  3385. 'xh': 'xho',
  3386. 'yi': 'yid',
  3387. 'ji': 'yid', # Replaced by yi in 1989 revision
  3388. 'yo': 'yor',
  3389. 'za': 'zha',
  3390. 'zh': 'zho',
  3391. 'zu': 'zul',
  3392. }
  3393. @classmethod
  3394. def short2long(cls, code):
  3395. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  3396. return cls._lang_map.get(code[:2])
  3397. @classmethod
  3398. def long2short(cls, code):
  3399. """Convert language code from ISO 639-2/T to ISO 639-1"""
  3400. for short_name, long_name in cls._lang_map.items():
  3401. if long_name == code:
  3402. return short_name
  3403. class ISO3166Utils:
  3404. # From http://data.okfn.org/data/core/country-list
  3405. _country_map = {
  3406. 'AF': 'Afghanistan',
  3407. 'AX': 'Åland Islands',
  3408. 'AL': 'Albania',
  3409. 'DZ': 'Algeria',
  3410. 'AS': 'American Samoa',
  3411. 'AD': 'Andorra',
  3412. 'AO': 'Angola',
  3413. 'AI': 'Anguilla',
  3414. 'AQ': 'Antarctica',
  3415. 'AG': 'Antigua and Barbuda',
  3416. 'AR': 'Argentina',
  3417. 'AM': 'Armenia',
  3418. 'AW': 'Aruba',
  3419. 'AU': 'Australia',
  3420. 'AT': 'Austria',
  3421. 'AZ': 'Azerbaijan',
  3422. 'BS': 'Bahamas',
  3423. 'BH': 'Bahrain',
  3424. 'BD': 'Bangladesh',
  3425. 'BB': 'Barbados',
  3426. 'BY': 'Belarus',
  3427. 'BE': 'Belgium',
  3428. 'BZ': 'Belize',
  3429. 'BJ': 'Benin',
  3430. 'BM': 'Bermuda',
  3431. 'BT': 'Bhutan',
  3432. 'BO': 'Bolivia, Plurinational State of',
  3433. 'BQ': 'Bonaire, Sint Eustatius and Saba',
  3434. 'BA': 'Bosnia and Herzegovina',
  3435. 'BW': 'Botswana',
  3436. 'BV': 'Bouvet Island',
  3437. 'BR': 'Brazil',
  3438. 'IO': 'British Indian Ocean Territory',
  3439. 'BN': 'Brunei Darussalam',
  3440. 'BG': 'Bulgaria',
  3441. 'BF': 'Burkina Faso',
  3442. 'BI': 'Burundi',
  3443. 'KH': 'Cambodia',
  3444. 'CM': 'Cameroon',
  3445. 'CA': 'Canada',
  3446. 'CV': 'Cape Verde',
  3447. 'KY': 'Cayman Islands',
  3448. 'CF': 'Central African Republic',
  3449. 'TD': 'Chad',
  3450. 'CL': 'Chile',
  3451. 'CN': 'China',
  3452. 'CX': 'Christmas Island',
  3453. 'CC': 'Cocos (Keeling) Islands',
  3454. 'CO': 'Colombia',
  3455. 'KM': 'Comoros',
  3456. 'CG': 'Congo',
  3457. 'CD': 'Congo, the Democratic Republic of the',
  3458. 'CK': 'Cook Islands',
  3459. 'CR': 'Costa Rica',
  3460. 'CI': 'Côte d\'Ivoire',
  3461. 'HR': 'Croatia',
  3462. 'CU': 'Cuba',
  3463. 'CW': 'Curaçao',
  3464. 'CY': 'Cyprus',
  3465. 'CZ': 'Czech Republic',
  3466. 'DK': 'Denmark',
  3467. 'DJ': 'Djibouti',
  3468. 'DM': 'Dominica',
  3469. 'DO': 'Dominican Republic',
  3470. 'EC': 'Ecuador',
  3471. 'EG': 'Egypt',
  3472. 'SV': 'El Salvador',
  3473. 'GQ': 'Equatorial Guinea',
  3474. 'ER': 'Eritrea',
  3475. 'EE': 'Estonia',
  3476. 'ET': 'Ethiopia',
  3477. 'FK': 'Falkland Islands (Malvinas)',
  3478. 'FO': 'Faroe Islands',
  3479. 'FJ': 'Fiji',
  3480. 'FI': 'Finland',
  3481. 'FR': 'France',
  3482. 'GF': 'French Guiana',
  3483. 'PF': 'French Polynesia',
  3484. 'TF': 'French Southern Territories',
  3485. 'GA': 'Gabon',
  3486. 'GM': 'Gambia',
  3487. 'GE': 'Georgia',
  3488. 'DE': 'Germany',
  3489. 'GH': 'Ghana',
  3490. 'GI': 'Gibraltar',
  3491. 'GR': 'Greece',
  3492. 'GL': 'Greenland',
  3493. 'GD': 'Grenada',
  3494. 'GP': 'Guadeloupe',
  3495. 'GU': 'Guam',
  3496. 'GT': 'Guatemala',
  3497. 'GG': 'Guernsey',
  3498. 'GN': 'Guinea',
  3499. 'GW': 'Guinea-Bissau',
  3500. 'GY': 'Guyana',
  3501. 'HT': 'Haiti',
  3502. 'HM': 'Heard Island and McDonald Islands',
  3503. 'VA': 'Holy See (Vatican City State)',
  3504. 'HN': 'Honduras',
  3505. 'HK': 'Hong Kong',
  3506. 'HU': 'Hungary',
  3507. 'IS': 'Iceland',
  3508. 'IN': 'India',
  3509. 'ID': 'Indonesia',
  3510. 'IR': 'Iran, Islamic Republic of',
  3511. 'IQ': 'Iraq',
  3512. 'IE': 'Ireland',
  3513. 'IM': 'Isle of Man',
  3514. 'IL': 'Israel',
  3515. 'IT': 'Italy',
  3516. 'JM': 'Jamaica',
  3517. 'JP': 'Japan',
  3518. 'JE': 'Jersey',
  3519. 'JO': 'Jordan',
  3520. 'KZ': 'Kazakhstan',
  3521. 'KE': 'Kenya',
  3522. 'KI': 'Kiribati',
  3523. 'KP': 'Korea, Democratic People\'s Republic of',
  3524. 'KR': 'Korea, Republic of',
  3525. 'KW': 'Kuwait',
  3526. 'KG': 'Kyrgyzstan',
  3527. 'LA': 'Lao People\'s Democratic Republic',
  3528. 'LV': 'Latvia',
  3529. 'LB': 'Lebanon',
  3530. 'LS': 'Lesotho',
  3531. 'LR': 'Liberia',
  3532. 'LY': 'Libya',
  3533. 'LI': 'Liechtenstein',
  3534. 'LT': 'Lithuania',
  3535. 'LU': 'Luxembourg',
  3536. 'MO': 'Macao',
  3537. 'MK': 'Macedonia, the Former Yugoslav Republic of',
  3538. 'MG': 'Madagascar',
  3539. 'MW': 'Malawi',
  3540. 'MY': 'Malaysia',
  3541. 'MV': 'Maldives',
  3542. 'ML': 'Mali',
  3543. 'MT': 'Malta',
  3544. 'MH': 'Marshall Islands',
  3545. 'MQ': 'Martinique',
  3546. 'MR': 'Mauritania',
  3547. 'MU': 'Mauritius',
  3548. 'YT': 'Mayotte',
  3549. 'MX': 'Mexico',
  3550. 'FM': 'Micronesia, Federated States of',
  3551. 'MD': 'Moldova, Republic of',
  3552. 'MC': 'Monaco',
  3553. 'MN': 'Mongolia',
  3554. 'ME': 'Montenegro',
  3555. 'MS': 'Montserrat',
  3556. 'MA': 'Morocco',
  3557. 'MZ': 'Mozambique',
  3558. 'MM': 'Myanmar',
  3559. 'NA': 'Namibia',
  3560. 'NR': 'Nauru',
  3561. 'NP': 'Nepal',
  3562. 'NL': 'Netherlands',
  3563. 'NC': 'New Caledonia',
  3564. 'NZ': 'New Zealand',
  3565. 'NI': 'Nicaragua',
  3566. 'NE': 'Niger',
  3567. 'NG': 'Nigeria',
  3568. 'NU': 'Niue',
  3569. 'NF': 'Norfolk Island',
  3570. 'MP': 'Northern Mariana Islands',
  3571. 'NO': 'Norway',
  3572. 'OM': 'Oman',
  3573. 'PK': 'Pakistan',
  3574. 'PW': 'Palau',
  3575. 'PS': 'Palestine, State of',
  3576. 'PA': 'Panama',
  3577. 'PG': 'Papua New Guinea',
  3578. 'PY': 'Paraguay',
  3579. 'PE': 'Peru',
  3580. 'PH': 'Philippines',
  3581. 'PN': 'Pitcairn',
  3582. 'PL': 'Poland',
  3583. 'PT': 'Portugal',
  3584. 'PR': 'Puerto Rico',
  3585. 'QA': 'Qatar',
  3586. 'RE': 'Réunion',
  3587. 'RO': 'Romania',
  3588. 'RU': 'Russian Federation',
  3589. 'RW': 'Rwanda',
  3590. 'BL': 'Saint Barthélemy',
  3591. 'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  3592. 'KN': 'Saint Kitts and Nevis',
  3593. 'LC': 'Saint Lucia',
  3594. 'MF': 'Saint Martin (French part)',
  3595. 'PM': 'Saint Pierre and Miquelon',
  3596. 'VC': 'Saint Vincent and the Grenadines',
  3597. 'WS': 'Samoa',
  3598. 'SM': 'San Marino',
  3599. 'ST': 'Sao Tome and Principe',
  3600. 'SA': 'Saudi Arabia',
  3601. 'SN': 'Senegal',
  3602. 'RS': 'Serbia',
  3603. 'SC': 'Seychelles',
  3604. 'SL': 'Sierra Leone',
  3605. 'SG': 'Singapore',
  3606. 'SX': 'Sint Maarten (Dutch part)',
  3607. 'SK': 'Slovakia',
  3608. 'SI': 'Slovenia',
  3609. 'SB': 'Solomon Islands',
  3610. 'SO': 'Somalia',
  3611. 'ZA': 'South Africa',
  3612. 'GS': 'South Georgia and the South Sandwich Islands',
  3613. 'SS': 'South Sudan',
  3614. 'ES': 'Spain',
  3615. 'LK': 'Sri Lanka',
  3616. 'SD': 'Sudan',
  3617. 'SR': 'Suriname',
  3618. 'SJ': 'Svalbard and Jan Mayen',
  3619. 'SZ': 'Swaziland',
  3620. 'SE': 'Sweden',
  3621. 'CH': 'Switzerland',
  3622. 'SY': 'Syrian Arab Republic',
  3623. 'TW': 'Taiwan, Province of China',
  3624. 'TJ': 'Tajikistan',
  3625. 'TZ': 'Tanzania, United Republic of',
  3626. 'TH': 'Thailand',
  3627. 'TL': 'Timor-Leste',
  3628. 'TG': 'Togo',
  3629. 'TK': 'Tokelau',
  3630. 'TO': 'Tonga',
  3631. 'TT': 'Trinidad and Tobago',
  3632. 'TN': 'Tunisia',
  3633. 'TR': 'Turkey',
  3634. 'TM': 'Turkmenistan',
  3635. 'TC': 'Turks and Caicos Islands',
  3636. 'TV': 'Tuvalu',
  3637. 'UG': 'Uganda',
  3638. 'UA': 'Ukraine',
  3639. 'AE': 'United Arab Emirates',
  3640. 'GB': 'United Kingdom',
  3641. 'US': 'United States',
  3642. 'UM': 'United States Minor Outlying Islands',
  3643. 'UY': 'Uruguay',
  3644. 'UZ': 'Uzbekistan',
  3645. 'VU': 'Vanuatu',
  3646. 'VE': 'Venezuela, Bolivarian Republic of',
  3647. 'VN': 'Viet Nam',
  3648. 'VG': 'Virgin Islands, British',
  3649. 'VI': 'Virgin Islands, U.S.',
  3650. 'WF': 'Wallis and Futuna',
  3651. 'EH': 'Western Sahara',
  3652. 'YE': 'Yemen',
  3653. 'ZM': 'Zambia',
  3654. 'ZW': 'Zimbabwe',
  3655. # Not ISO 3166 codes, but used for IP blocks
  3656. 'AP': 'Asia/Pacific Region',
  3657. 'EU': 'Europe',
  3658. }
  3659. @classmethod
  3660. def short2full(cls, code):
  3661. """Convert an ISO 3166-2 country code to the corresponding full name"""
  3662. return cls._country_map.get(code.upper())
  3663. class GeoUtils:
  3664. # Major IPv4 address blocks per country
  3665. _country_ip_map = {
  3666. 'AD': '46.172.224.0/19',
  3667. 'AE': '94.200.0.0/13',
  3668. 'AF': '149.54.0.0/17',
  3669. 'AG': '209.59.64.0/18',
  3670. 'AI': '204.14.248.0/21',
  3671. 'AL': '46.99.0.0/16',
  3672. 'AM': '46.70.0.0/15',
  3673. 'AO': '105.168.0.0/13',
  3674. 'AP': '182.50.184.0/21',
  3675. 'AQ': '23.154.160.0/24',
  3676. 'AR': '181.0.0.0/12',
  3677. 'AS': '202.70.112.0/20',
  3678. 'AT': '77.116.0.0/14',
  3679. 'AU': '1.128.0.0/11',
  3680. 'AW': '181.41.0.0/18',
  3681. 'AX': '185.217.4.0/22',
  3682. 'AZ': '5.197.0.0/16',
  3683. 'BA': '31.176.128.0/17',
  3684. 'BB': '65.48.128.0/17',
  3685. 'BD': '114.130.0.0/16',
  3686. 'BE': '57.0.0.0/8',
  3687. 'BF': '102.178.0.0/15',
  3688. 'BG': '95.42.0.0/15',
  3689. 'BH': '37.131.0.0/17',
  3690. 'BI': '154.117.192.0/18',
  3691. 'BJ': '137.255.0.0/16',
  3692. 'BL': '185.212.72.0/23',
  3693. 'BM': '196.12.64.0/18',
  3694. 'BN': '156.31.0.0/16',
  3695. 'BO': '161.56.0.0/16',
  3696. 'BQ': '161.0.80.0/20',
  3697. 'BR': '191.128.0.0/12',
  3698. 'BS': '24.51.64.0/18',
  3699. 'BT': '119.2.96.0/19',
  3700. 'BW': '168.167.0.0/16',
  3701. 'BY': '178.120.0.0/13',
  3702. 'BZ': '179.42.192.0/18',
  3703. 'CA': '99.224.0.0/11',
  3704. 'CD': '41.243.0.0/16',
  3705. 'CF': '197.242.176.0/21',
  3706. 'CG': '160.113.0.0/16',
  3707. 'CH': '85.0.0.0/13',
  3708. 'CI': '102.136.0.0/14',
  3709. 'CK': '202.65.32.0/19',
  3710. 'CL': '152.172.0.0/14',
  3711. 'CM': '102.244.0.0/14',
  3712. 'CN': '36.128.0.0/10',
  3713. 'CO': '181.240.0.0/12',
  3714. 'CR': '201.192.0.0/12',
  3715. 'CU': '152.206.0.0/15',
  3716. 'CV': '165.90.96.0/19',
  3717. 'CW': '190.88.128.0/17',
  3718. 'CY': '31.153.0.0/16',
  3719. 'CZ': '88.100.0.0/14',
  3720. 'DE': '53.0.0.0/8',
  3721. 'DJ': '197.241.0.0/17',
  3722. 'DK': '87.48.0.0/12',
  3723. 'DM': '192.243.48.0/20',
  3724. 'DO': '152.166.0.0/15',
  3725. 'DZ': '41.96.0.0/12',
  3726. 'EC': '186.68.0.0/15',
  3727. 'EE': '90.190.0.0/15',
  3728. 'EG': '156.160.0.0/11',
  3729. 'ER': '196.200.96.0/20',
  3730. 'ES': '88.0.0.0/11',
  3731. 'ET': '196.188.0.0/14',
  3732. 'EU': '2.16.0.0/13',
  3733. 'FI': '91.152.0.0/13',
  3734. 'FJ': '144.120.0.0/16',
  3735. 'FK': '80.73.208.0/21',
  3736. 'FM': '119.252.112.0/20',
  3737. 'FO': '88.85.32.0/19',
  3738. 'FR': '90.0.0.0/9',
  3739. 'GA': '41.158.0.0/15',
  3740. 'GB': '25.0.0.0/8',
  3741. 'GD': '74.122.88.0/21',
  3742. 'GE': '31.146.0.0/16',
  3743. 'GF': '161.22.64.0/18',
  3744. 'GG': '62.68.160.0/19',
  3745. 'GH': '154.160.0.0/12',
  3746. 'GI': '95.164.0.0/16',
  3747. 'GL': '88.83.0.0/19',
  3748. 'GM': '160.182.0.0/15',
  3749. 'GN': '197.149.192.0/18',
  3750. 'GP': '104.250.0.0/19',
  3751. 'GQ': '105.235.224.0/20',
  3752. 'GR': '94.64.0.0/13',
  3753. 'GT': '168.234.0.0/16',
  3754. 'GU': '168.123.0.0/16',
  3755. 'GW': '197.214.80.0/20',
  3756. 'GY': '181.41.64.0/18',
  3757. 'HK': '113.252.0.0/14',
  3758. 'HN': '181.210.0.0/16',
  3759. 'HR': '93.136.0.0/13',
  3760. 'HT': '148.102.128.0/17',
  3761. 'HU': '84.0.0.0/14',
  3762. 'ID': '39.192.0.0/10',
  3763. 'IE': '87.32.0.0/12',
  3764. 'IL': '79.176.0.0/13',
  3765. 'IM': '5.62.80.0/20',
  3766. 'IN': '117.192.0.0/10',
  3767. 'IO': '203.83.48.0/21',
  3768. 'IQ': '37.236.0.0/14',
  3769. 'IR': '2.176.0.0/12',
  3770. 'IS': '82.221.0.0/16',
  3771. 'IT': '79.0.0.0/10',
  3772. 'JE': '87.244.64.0/18',
  3773. 'JM': '72.27.0.0/17',
  3774. 'JO': '176.29.0.0/16',
  3775. 'JP': '133.0.0.0/8',
  3776. 'KE': '105.48.0.0/12',
  3777. 'KG': '158.181.128.0/17',
  3778. 'KH': '36.37.128.0/17',
  3779. 'KI': '103.25.140.0/22',
  3780. 'KM': '197.255.224.0/20',
  3781. 'KN': '198.167.192.0/19',
  3782. 'KP': '175.45.176.0/22',
  3783. 'KR': '175.192.0.0/10',
  3784. 'KW': '37.36.0.0/14',
  3785. 'KY': '64.96.0.0/15',
  3786. 'KZ': '2.72.0.0/13',
  3787. 'LA': '115.84.64.0/18',
  3788. 'LB': '178.135.0.0/16',
  3789. 'LC': '24.92.144.0/20',
  3790. 'LI': '82.117.0.0/19',
  3791. 'LK': '112.134.0.0/15',
  3792. 'LR': '102.183.0.0/16',
  3793. 'LS': '129.232.0.0/17',
  3794. 'LT': '78.56.0.0/13',
  3795. 'LU': '188.42.0.0/16',
  3796. 'LV': '46.109.0.0/16',
  3797. 'LY': '41.252.0.0/14',
  3798. 'MA': '105.128.0.0/11',
  3799. 'MC': '88.209.64.0/18',
  3800. 'MD': '37.246.0.0/16',
  3801. 'ME': '178.175.0.0/17',
  3802. 'MF': '74.112.232.0/21',
  3803. 'MG': '154.126.0.0/17',
  3804. 'MH': '117.103.88.0/21',
  3805. 'MK': '77.28.0.0/15',
  3806. 'ML': '154.118.128.0/18',
  3807. 'MM': '37.111.0.0/17',
  3808. 'MN': '49.0.128.0/17',
  3809. 'MO': '60.246.0.0/16',
  3810. 'MP': '202.88.64.0/20',
  3811. 'MQ': '109.203.224.0/19',
  3812. 'MR': '41.188.64.0/18',
  3813. 'MS': '208.90.112.0/22',
  3814. 'MT': '46.11.0.0/16',
  3815. 'MU': '105.16.0.0/12',
  3816. 'MV': '27.114.128.0/18',
  3817. 'MW': '102.70.0.0/15',
  3818. 'MX': '187.192.0.0/11',
  3819. 'MY': '175.136.0.0/13',
  3820. 'MZ': '197.218.0.0/15',
  3821. 'NA': '41.182.0.0/16',
  3822. 'NC': '101.101.0.0/18',
  3823. 'NE': '197.214.0.0/18',
  3824. 'NF': '203.17.240.0/22',
  3825. 'NG': '105.112.0.0/12',
  3826. 'NI': '186.76.0.0/15',
  3827. 'NL': '145.96.0.0/11',
  3828. 'NO': '84.208.0.0/13',
  3829. 'NP': '36.252.0.0/15',
  3830. 'NR': '203.98.224.0/19',
  3831. 'NU': '49.156.48.0/22',
  3832. 'NZ': '49.224.0.0/14',
  3833. 'OM': '5.36.0.0/15',
  3834. 'PA': '186.72.0.0/15',
  3835. 'PE': '186.160.0.0/14',
  3836. 'PF': '123.50.64.0/18',
  3837. 'PG': '124.240.192.0/19',
  3838. 'PH': '49.144.0.0/13',
  3839. 'PK': '39.32.0.0/11',
  3840. 'PL': '83.0.0.0/11',
  3841. 'PM': '70.36.0.0/20',
  3842. 'PR': '66.50.0.0/16',
  3843. 'PS': '188.161.0.0/16',
  3844. 'PT': '85.240.0.0/13',
  3845. 'PW': '202.124.224.0/20',
  3846. 'PY': '181.120.0.0/14',
  3847. 'QA': '37.210.0.0/15',
  3848. 'RE': '102.35.0.0/16',
  3849. 'RO': '79.112.0.0/13',
  3850. 'RS': '93.86.0.0/15',
  3851. 'RU': '5.136.0.0/13',
  3852. 'RW': '41.186.0.0/16',
  3853. 'SA': '188.48.0.0/13',
  3854. 'SB': '202.1.160.0/19',
  3855. 'SC': '154.192.0.0/11',
  3856. 'SD': '102.120.0.0/13',
  3857. 'SE': '78.64.0.0/12',
  3858. 'SG': '8.128.0.0/10',
  3859. 'SI': '188.196.0.0/14',
  3860. 'SK': '78.98.0.0/15',
  3861. 'SL': '102.143.0.0/17',
  3862. 'SM': '89.186.32.0/19',
  3863. 'SN': '41.82.0.0/15',
  3864. 'SO': '154.115.192.0/18',
  3865. 'SR': '186.179.128.0/17',
  3866. 'SS': '105.235.208.0/21',
  3867. 'ST': '197.159.160.0/19',
  3868. 'SV': '168.243.0.0/16',
  3869. 'SX': '190.102.0.0/20',
  3870. 'SY': '5.0.0.0/16',
  3871. 'SZ': '41.84.224.0/19',
  3872. 'TC': '65.255.48.0/20',
  3873. 'TD': '154.68.128.0/19',
  3874. 'TG': '196.168.0.0/14',
  3875. 'TH': '171.96.0.0/13',
  3876. 'TJ': '85.9.128.0/18',
  3877. 'TK': '27.96.24.0/21',
  3878. 'TL': '180.189.160.0/20',
  3879. 'TM': '95.85.96.0/19',
  3880. 'TN': '197.0.0.0/11',
  3881. 'TO': '175.176.144.0/21',
  3882. 'TR': '78.160.0.0/11',
  3883. 'TT': '186.44.0.0/15',
  3884. 'TV': '202.2.96.0/19',
  3885. 'TW': '120.96.0.0/11',
  3886. 'TZ': '156.156.0.0/14',
  3887. 'UA': '37.52.0.0/14',
  3888. 'UG': '102.80.0.0/13',
  3889. 'US': '6.0.0.0/8',
  3890. 'UY': '167.56.0.0/13',
  3891. 'UZ': '84.54.64.0/18',
  3892. 'VA': '212.77.0.0/19',
  3893. 'VC': '207.191.240.0/21',
  3894. 'VE': '186.88.0.0/13',
  3895. 'VG': '66.81.192.0/20',
  3896. 'VI': '146.226.0.0/16',
  3897. 'VN': '14.160.0.0/11',
  3898. 'VU': '202.80.32.0/20',
  3899. 'WF': '117.20.32.0/21',
  3900. 'WS': '202.4.32.0/19',
  3901. 'YE': '134.35.0.0/16',
  3902. 'YT': '41.242.116.0/22',
  3903. 'ZA': '41.0.0.0/11',
  3904. 'ZM': '102.144.0.0/13',
  3905. 'ZW': '102.177.192.0/18',
  3906. }
  3907. @classmethod
  3908. def random_ipv4(cls, code_or_block):
  3909. if len(code_or_block) == 2:
  3910. block = cls._country_ip_map.get(code_or_block.upper())
  3911. if not block:
  3912. return None
  3913. else:
  3914. block = code_or_block
  3915. addr, preflen = block.split('/')
  3916. addr_min = struct.unpack('!L', socket.inet_aton(addr))[0]
  3917. addr_max = addr_min | (0xffffffff >> int(preflen))
  3918. return str(socket.inet_ntoa(
  3919. struct.pack('!L', random.randint(addr_min, addr_max))))
  3920. class PerRequestProxyHandler(urllib.request.ProxyHandler):
  3921. def __init__(self, proxies=None):
  3922. # Set default handlers
  3923. for type in ('http', 'https'):
  3924. setattr(self, '%s_open' % type,
  3925. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  3926. meth(r, proxy, type))
  3927. urllib.request.ProxyHandler.__init__(self, proxies)
  3928. def proxy_open(self, req, proxy, type):
  3929. req_proxy = req.headers.get('Ytdl-request-proxy')
  3930. if req_proxy is not None:
  3931. proxy = req_proxy
  3932. del req.headers['Ytdl-request-proxy']
  3933. if proxy == '__noproxy__':
  3934. return None # No Proxy
  3935. if urllib.parse.urlparse(proxy).scheme.lower() in ('socks', 'socks4', 'socks4a', 'socks5'):
  3936. req.add_header('Ytdl-socks-proxy', proxy)
  3937. # yt-dlp's http/https handlers do wrapping the socket with socks
  3938. return None
  3939. return urllib.request.ProxyHandler.proxy_open(
  3940. self, req, proxy, type)
  3941. # Both long_to_bytes and bytes_to_long are adapted from PyCrypto, which is
  3942. # released into Public Domain
  3943. # https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Util/number.py#L387
  3944. def long_to_bytes(n, blocksize=0):
  3945. """long_to_bytes(n:long, blocksize:int) : string
  3946. Convert a long integer to a byte string.
  3947. If optional blocksize is given and greater than zero, pad the front of the
  3948. byte string with binary zeros so that the length is a multiple of
  3949. blocksize.
  3950. """
  3951. # after much testing, this algorithm was deemed to be the fastest
  3952. s = b''
  3953. n = int(n)
  3954. while n > 0:
  3955. s = struct.pack('>I', n & 0xffffffff) + s
  3956. n = n >> 32
  3957. # strip off leading zeros
  3958. for i in range(len(s)):
  3959. if s[i] != b'\000'[0]:
  3960. break
  3961. else:
  3962. # only happens when n == 0
  3963. s = b'\000'
  3964. i = 0
  3965. s = s[i:]
  3966. # add back some pad bytes. this could be done more efficiently w.r.t. the
  3967. # de-padding being done above, but sigh...
  3968. if blocksize > 0 and len(s) % blocksize:
  3969. s = (blocksize - len(s) % blocksize) * b'\000' + s
  3970. return s
  3971. def bytes_to_long(s):
  3972. """bytes_to_long(string) : long
  3973. Convert a byte string to a long integer.
  3974. This is (essentially) the inverse of long_to_bytes().
  3975. """
  3976. acc = 0
  3977. length = len(s)
  3978. if length % 4:
  3979. extra = (4 - length % 4)
  3980. s = b'\000' * extra + s
  3981. length = length + extra
  3982. for i in range(0, length, 4):
  3983. acc = (acc << 32) + struct.unpack('>I', s[i:i + 4])[0]
  3984. return acc
  3985. def ohdave_rsa_encrypt(data, exponent, modulus):
  3986. '''
  3987. Implement OHDave's RSA algorithm. See http://www.ohdave.com/rsa/
  3988. Input:
  3989. data: data to encrypt, bytes-like object
  3990. exponent, modulus: parameter e and N of RSA algorithm, both integer
  3991. Output: hex string of encrypted data
  3992. Limitation: supports one block encryption only
  3993. '''
  3994. payload = int(binascii.hexlify(data[::-1]), 16)
  3995. encrypted = pow(payload, exponent, modulus)
  3996. return '%x' % encrypted
  3997. def pkcs1pad(data, length):
  3998. """
  3999. Padding input data with PKCS#1 scheme
  4000. @param {int[]} data input data
  4001. @param {int} length target length
  4002. @returns {int[]} padded data
  4003. """
  4004. if len(data) > length - 11:
  4005. raise ValueError('Input data too long for PKCS#1 padding')
  4006. pseudo_random = [random.randint(0, 254) for _ in range(length - len(data) - 3)]
  4007. return [0, 2] + pseudo_random + [0] + data
  4008. def _base_n_table(n, table):
  4009. if not table and not n:
  4010. raise ValueError('Either table or n must be specified')
  4011. table = (table or '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')[:n]
  4012. if n and n != len(table):
  4013. raise ValueError(f'base {n} exceeds table length {len(table)}')
  4014. return table
  4015. def encode_base_n(num, n=None, table=None):
  4016. """Convert given int to a base-n string"""
  4017. table = _base_n_table(n, table)
  4018. if not num:
  4019. return table[0]
  4020. result, base = '', len(table)
  4021. while num:
  4022. result = table[num % base] + result
  4023. num = num // base
  4024. return result
  4025. def decode_base_n(string, n=None, table=None):
  4026. """Convert given base-n string to int"""
  4027. table = {char: index for index, char in enumerate(_base_n_table(n, table))}
  4028. result, base = 0, len(table)
  4029. for char in string:
  4030. result = result * base + table[char]
  4031. return result
  4032. def decode_base(value, digits):
  4033. write_string('DeprecationWarning: yt_dlp.utils.decode_base is deprecated '
  4034. 'and may be removed in a future version. Use yt_dlp.decode_base_n instead')
  4035. return decode_base_n(value, table=digits)
  4036. def decode_packed_codes(code):
  4037. mobj = re.search(PACKED_CODES_RE, code)
  4038. obfuscated_code, base, count, symbols = mobj.groups()
  4039. base = int(base)
  4040. count = int(count)
  4041. symbols = symbols.split('|')
  4042. symbol_table = {}
  4043. while count:
  4044. count -= 1
  4045. base_n_count = encode_base_n(count, base)
  4046. symbol_table[base_n_count] = symbols[count] or base_n_count
  4047. return re.sub(
  4048. r'\b(\w+)\b', lambda mobj: symbol_table[mobj.group(0)],
  4049. obfuscated_code)
  4050. def caesar(s, alphabet, shift):
  4051. if shift == 0:
  4052. return s
  4053. l = len(alphabet)
  4054. return ''.join(
  4055. alphabet[(alphabet.index(c) + shift) % l] if c in alphabet else c
  4056. for c in s)
  4057. def rot47(s):
  4058. return caesar(s, r'''!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~''', 47)
  4059. def parse_m3u8_attributes(attrib):
  4060. info = {}
  4061. for (key, val) in re.findall(r'(?P<key>[A-Z0-9-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)', attrib):
  4062. if val.startswith('"'):
  4063. val = val[1:-1]
  4064. info[key] = val
  4065. return info
  4066. def urshift(val, n):
  4067. return val >> n if val >= 0 else (val + 0x100000000) >> n
  4068. # Based on png2str() written by @gdkchan and improved by @yokrysty
  4069. # Originally posted at https://github.com/ytdl-org/youtube-dl/issues/9706
  4070. def decode_png(png_data):
  4071. # Reference: https://www.w3.org/TR/PNG/
  4072. header = png_data[8:]
  4073. if png_data[:8] != b'\x89PNG\x0d\x0a\x1a\x0a' or header[4:8] != b'IHDR':
  4074. raise OSError('Not a valid PNG file.')
  4075. int_map = {1: '>B', 2: '>H', 4: '>I'}
  4076. unpack_integer = lambda x: struct.unpack(int_map[len(x)], x)[0]
  4077. chunks = []
  4078. while header:
  4079. length = unpack_integer(header[:4])
  4080. header = header[4:]
  4081. chunk_type = header[:4]
  4082. header = header[4:]
  4083. chunk_data = header[:length]
  4084. header = header[length:]
  4085. header = header[4:] # Skip CRC
  4086. chunks.append({
  4087. 'type': chunk_type,
  4088. 'length': length,
  4089. 'data': chunk_data
  4090. })
  4091. ihdr = chunks[0]['data']
  4092. width = unpack_integer(ihdr[:4])
  4093. height = unpack_integer(ihdr[4:8])
  4094. idat = b''
  4095. for chunk in chunks:
  4096. if chunk['type'] == b'IDAT':
  4097. idat += chunk['data']
  4098. if not idat:
  4099. raise OSError('Unable to read PNG data.')
  4100. decompressed_data = bytearray(zlib.decompress(idat))
  4101. stride = width * 3
  4102. pixels = []
  4103. def _get_pixel(idx):
  4104. x = idx % stride
  4105. y = idx // stride
  4106. return pixels[y][x]
  4107. for y in range(height):
  4108. basePos = y * (1 + stride)
  4109. filter_type = decompressed_data[basePos]
  4110. current_row = []
  4111. pixels.append(current_row)
  4112. for x in range(stride):
  4113. color = decompressed_data[1 + basePos + x]
  4114. basex = y * stride + x
  4115. left = 0
  4116. up = 0
  4117. if x > 2:
  4118. left = _get_pixel(basex - 3)
  4119. if y > 0:
  4120. up = _get_pixel(basex - stride)
  4121. if filter_type == 1: # Sub
  4122. color = (color + left) & 0xff
  4123. elif filter_type == 2: # Up
  4124. color = (color + up) & 0xff
  4125. elif filter_type == 3: # Average
  4126. color = (color + ((left + up) >> 1)) & 0xff
  4127. elif filter_type == 4: # Paeth
  4128. a = left
  4129. b = up
  4130. c = 0
  4131. if x > 2 and y > 0:
  4132. c = _get_pixel(basex - stride - 3)
  4133. p = a + b - c
  4134. pa = abs(p - a)
  4135. pb = abs(p - b)
  4136. pc = abs(p - c)
  4137. if pa <= pb and pa <= pc:
  4138. color = (color + a) & 0xff
  4139. elif pb <= pc:
  4140. color = (color + b) & 0xff
  4141. else:
  4142. color = (color + c) & 0xff
  4143. current_row.append(color)
  4144. return width, height, pixels
  4145. def write_xattr(path, key, value):
  4146. # Windows: Write xattrs to NTFS Alternate Data Streams:
  4147. # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  4148. if compat_os_name == 'nt':
  4149. assert ':' not in key
  4150. assert os.path.exists(path)
  4151. try:
  4152. with open(f'{path}:{key}', 'wb') as f:
  4153. f.write(value)
  4154. except OSError as e:
  4155. raise XAttrMetadataError(e.errno, e.strerror)
  4156. return
  4157. # UNIX Method 1. Use xattrs/pyxattrs modules
  4158. setxattr = None
  4159. if getattr(xattr, '_yt_dlp__identifier', None) == 'pyxattr':
  4160. # Unicode arguments are not supported in pyxattr until version 0.5.0
  4161. # See https://github.com/ytdl-org/youtube-dl/issues/5498
  4162. if version_tuple(xattr.__version__) >= (0, 5, 0):
  4163. setxattr = xattr.set
  4164. elif xattr:
  4165. setxattr = xattr.setxattr
  4166. if setxattr:
  4167. try:
  4168. setxattr(path, key, value)
  4169. except OSError as e:
  4170. raise XAttrMetadataError(e.errno, e.strerror)
  4171. return
  4172. # UNIX Method 2. Use setfattr/xattr executables
  4173. exe = ('setfattr' if check_executable('setfattr', ['--version'])
  4174. else 'xattr' if check_executable('xattr', ['-h']) else None)
  4175. if not exe:
  4176. raise XAttrUnavailableError(
  4177. 'Couldn\'t find a tool to set the xattrs. Install either the python "xattr" or "pyxattr" modules or the '
  4178. + ('"xattr" binary' if sys.platform != 'linux' else 'GNU "attr" package (which contains the "setfattr" tool)'))
  4179. value = value.decode()
  4180. try:
  4181. _, stderr, returncode = Popen.run(
  4182. [exe, '-w', key, value, path] if exe == 'xattr' else [exe, '-n', key, '-v', value, path],
  4183. text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  4184. except OSError as e:
  4185. raise XAttrMetadataError(e.errno, e.strerror)
  4186. if returncode:
  4187. raise XAttrMetadataError(returncode, stderr)
  4188. def random_birthday(year_field, month_field, day_field):
  4189. start_date = datetime.date(1950, 1, 1)
  4190. end_date = datetime.date(1995, 12, 31)
  4191. offset = random.randint(0, (end_date - start_date).days)
  4192. random_date = start_date + datetime.timedelta(offset)
  4193. return {
  4194. year_field: str(random_date.year),
  4195. month_field: str(random_date.month),
  4196. day_field: str(random_date.day),
  4197. }
  4198. # Templates for internet shortcut files, which are plain text files.
  4199. DOT_URL_LINK_TEMPLATE = '''\
  4200. [InternetShortcut]
  4201. URL=%(url)s
  4202. '''
  4203. DOT_WEBLOC_LINK_TEMPLATE = '''\
  4204. <?xml version="1.0" encoding="UTF-8"?>
  4205. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  4206. <plist version="1.0">
  4207. <dict>
  4208. \t<key>URL</key>
  4209. \t<string>%(url)s</string>
  4210. </dict>
  4211. </plist>
  4212. '''
  4213. DOT_DESKTOP_LINK_TEMPLATE = '''\
  4214. [Desktop Entry]
  4215. Encoding=UTF-8
  4216. Name=%(filename)s
  4217. Type=Link
  4218. URL=%(url)s
  4219. Icon=text-html
  4220. '''
  4221. LINK_TEMPLATES = {
  4222. 'url': DOT_URL_LINK_TEMPLATE,
  4223. 'desktop': DOT_DESKTOP_LINK_TEMPLATE,
  4224. 'webloc': DOT_WEBLOC_LINK_TEMPLATE,
  4225. }
  4226. def iri_to_uri(iri):
  4227. """
  4228. Converts an IRI (Internationalized Resource Identifier, allowing Unicode characters) to a URI (Uniform Resource Identifier, ASCII-only).
  4229. The function doesn't add an additional layer of escaping; e.g., it doesn't escape `%3C` as `%253C`. Instead, it percent-escapes characters with an underlying UTF-8 encoding *besides* those already escaped, leaving the URI intact.
  4230. """
  4231. iri_parts = urllib.parse.urlparse(iri)
  4232. if '[' in iri_parts.netloc:
  4233. raise ValueError('IPv6 URIs are not, yet, supported.')
  4234. # Querying `.netloc`, when there's only one bracket, also raises a ValueError.
  4235. # The `safe` argument values, that the following code uses, contain the characters that should not be percent-encoded. Everything else but letters, digits and '_.-' will be percent-encoded with an underlying UTF-8 encoding. Everything already percent-encoded will be left as is.
  4236. net_location = ''
  4237. if iri_parts.username:
  4238. net_location += urllib.parse.quote(iri_parts.username, safe=r"!$%&'()*+,~")
  4239. if iri_parts.password is not None:
  4240. net_location += ':' + urllib.parse.quote(iri_parts.password, safe=r"!$%&'()*+,~")
  4241. net_location += '@'
  4242. net_location += iri_parts.hostname.encode('idna').decode() # Punycode for Unicode hostnames.
  4243. # The 'idna' encoding produces ASCII text.
  4244. if iri_parts.port is not None and iri_parts.port != 80:
  4245. net_location += ':' + str(iri_parts.port)
  4246. return urllib.parse.urlunparse(
  4247. (iri_parts.scheme,
  4248. net_location,
  4249. urllib.parse.quote_plus(iri_parts.path, safe=r"!$%&'()*+,/:;=@|~"),
  4250. # Unsure about the `safe` argument, since this is a legacy way of handling parameters.
  4251. urllib.parse.quote_plus(iri_parts.params, safe=r"!$%&'()*+,/:;=@|~"),
  4252. # Not totally sure about the `safe` argument, since the source does not explicitly mention the query URI component.
  4253. urllib.parse.quote_plus(iri_parts.query, safe=r"!$%&'()*+,/:;=?@{|}~"),
  4254. urllib.parse.quote_plus(iri_parts.fragment, safe=r"!#$%&'()*+,/:;=?@{|}~")))
  4255. # Source for `safe` arguments: https://url.spec.whatwg.org/#percent-encoded-bytes.
  4256. def to_high_limit_path(path):
  4257. if sys.platform in ['win32', 'cygwin']:
  4258. # Work around MAX_PATH limitation on Windows. The maximum allowed length for the individual path segments may still be quite limited.
  4259. return '\\\\?\\' + os.path.abspath(path)
  4260. return path
  4261. def format_field(obj, field=None, template='%s', ignore=NO_DEFAULT, default='', func=IDENTITY):
  4262. val = traverse_obj(obj, *variadic(field))
  4263. if (not val and val != 0) if ignore is NO_DEFAULT else val in variadic(ignore):
  4264. return default
  4265. return template % func(val)
  4266. def clean_podcast_url(url):
  4267. return re.sub(r'''(?x)
  4268. (?:
  4269. (?:
  4270. chtbl\.com/track|
  4271. media\.blubrry\.com| # https://create.blubrry.com/resources/podcast-media-download-statistics/getting-started/
  4272. play\.podtrac\.com
  4273. )/[^/]+|
  4274. (?:dts|www)\.podtrac\.com/(?:pts/)?redirect\.[0-9a-z]{3,4}| # http://analytics.podtrac.com/how-to-measure
  4275. flex\.acast\.com|
  4276. pd(?:
  4277. cn\.co| # https://podcorn.com/analytics-prefix/
  4278. st\.fm # https://podsights.com/docs/
  4279. )/e
  4280. )/''', '', url)
  4281. _HEX_TABLE = '0123456789abcdef'
  4282. def random_uuidv4():
  4283. return re.sub(r'[xy]', lambda x: _HEX_TABLE[random.randint(0, 15)], 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx')
  4284. def make_dir(path, to_screen=None):
  4285. try:
  4286. dn = os.path.dirname(path)
  4287. if dn and not os.path.exists(dn):
  4288. os.makedirs(dn)
  4289. return True
  4290. except OSError as err:
  4291. if callable(to_screen) is not None:
  4292. to_screen('unable to create directory ' + error_to_compat_str(err))
  4293. return False
  4294. def get_executable_path():
  4295. from .update import _get_variant_and_executable_path
  4296. return os.path.dirname(os.path.abspath(_get_variant_and_executable_path()[1]))
  4297. def load_plugins(name, suffix, namespace):
  4298. classes = {}
  4299. with contextlib.suppress(FileNotFoundError):
  4300. plugins_spec = importlib.util.spec_from_file_location(
  4301. name, os.path.join(get_executable_path(), 'ytdlp_plugins', name, '__init__.py'))
  4302. plugins = importlib.util.module_from_spec(plugins_spec)
  4303. sys.modules[plugins_spec.name] = plugins
  4304. plugins_spec.loader.exec_module(plugins)
  4305. for name in dir(plugins):
  4306. if name in namespace:
  4307. continue
  4308. if not name.endswith(suffix):
  4309. continue
  4310. klass = getattr(plugins, name)
  4311. classes[name] = namespace[name] = klass
  4312. return classes
  4313. def traverse_obj(
  4314. obj, *path_list, default=None, expected_type=None, get_all=True,
  4315. casesense=True, is_user_input=False, traverse_string=False):
  4316. ''' Traverse nested list/dict/tuple
  4317. @param path_list A list of paths which are checked one by one.
  4318. Each path is a list of keys where each key is a:
  4319. - None: Do nothing
  4320. - string: A dictionary key
  4321. - int: An index into a list
  4322. - tuple: A list of keys all of which will be traversed
  4323. - Ellipsis: Fetch all values in the object
  4324. - Function: Takes the key and value as arguments
  4325. and returns whether the key matches or not
  4326. @param default Default value to return
  4327. @param expected_type Only accept final value of this type (Can also be any callable)
  4328. @param get_all Return all the values obtained from a path or only the first one
  4329. @param casesense Whether to consider dictionary keys as case sensitive
  4330. @param is_user_input Whether the keys are generated from user input. If True,
  4331. strings are converted to int/slice if necessary
  4332. @param traverse_string Whether to traverse inside strings. If True, any
  4333. non-compatible object will also be converted into a string
  4334. # TODO: Write tests
  4335. '''
  4336. if not casesense:
  4337. _lower = lambda k: (k.lower() if isinstance(k, str) else k)
  4338. path_list = (map(_lower, variadic(path)) for path in path_list)
  4339. def _traverse_obj(obj, path, _current_depth=0):
  4340. nonlocal depth
  4341. path = tuple(variadic(path))
  4342. for i, key in enumerate(path):
  4343. if None in (key, obj):
  4344. return obj
  4345. if isinstance(key, (list, tuple)):
  4346. obj = [_traverse_obj(obj, sub_key, _current_depth) for sub_key in key]
  4347. key = ...
  4348. if key is ...:
  4349. obj = (obj.values() if isinstance(obj, dict)
  4350. else obj if isinstance(obj, (list, tuple, LazyList))
  4351. else str(obj) if traverse_string else [])
  4352. _current_depth += 1
  4353. depth = max(depth, _current_depth)
  4354. return [_traverse_obj(inner_obj, path[i + 1:], _current_depth) for inner_obj in obj]
  4355. elif callable(key):
  4356. if isinstance(obj, (list, tuple, LazyList)):
  4357. obj = enumerate(obj)
  4358. elif isinstance(obj, dict):
  4359. obj = obj.items()
  4360. else:
  4361. if not traverse_string:
  4362. return None
  4363. obj = str(obj)
  4364. _current_depth += 1
  4365. depth = max(depth, _current_depth)
  4366. return [_traverse_obj(v, path[i + 1:], _current_depth) for k, v in obj if try_call(key, args=(k, v))]
  4367. elif isinstance(obj, dict) and not (is_user_input and key == ':'):
  4368. obj = (obj.get(key) if casesense or (key in obj)
  4369. else next((v for k, v in obj.items() if _lower(k) == key), None))
  4370. else:
  4371. if is_user_input:
  4372. key = (int_or_none(key) if ':' not in key
  4373. else slice(*map(int_or_none, key.split(':'))))
  4374. if key == slice(None):
  4375. return _traverse_obj(obj, (..., *path[i + 1:]), _current_depth)
  4376. if not isinstance(key, (int, slice)):
  4377. return None
  4378. if not isinstance(obj, (list, tuple, LazyList)):
  4379. if not traverse_string:
  4380. return None
  4381. obj = str(obj)
  4382. try:
  4383. obj = obj[key]
  4384. except IndexError:
  4385. return None
  4386. return obj
  4387. if isinstance(expected_type, type):
  4388. type_test = lambda val: val if isinstance(val, expected_type) else None
  4389. else:
  4390. type_test = expected_type or IDENTITY
  4391. for path in path_list:
  4392. depth = 0
  4393. val = _traverse_obj(obj, path)
  4394. if val is not None:
  4395. if depth:
  4396. for _ in range(depth - 1):
  4397. val = itertools.chain.from_iterable(v for v in val if v is not None)
  4398. val = [v for v in map(type_test, val) if v is not None]
  4399. if val:
  4400. return val if get_all else val[0]
  4401. else:
  4402. val = type_test(val)
  4403. if val is not None:
  4404. return val
  4405. return default
  4406. def traverse_dict(dictn, keys, casesense=True):
  4407. write_string('DeprecationWarning: yt_dlp.utils.traverse_dict is deprecated '
  4408. 'and may be removed in a future version. Use yt_dlp.utils.traverse_obj instead')
  4409. return traverse_obj(dictn, keys, casesense=casesense, is_user_input=True, traverse_string=True)
  4410. def get_first(obj, keys, **kwargs):
  4411. return traverse_obj(obj, (..., *variadic(keys)), **kwargs, get_all=False)
  4412. def variadic(x, allowed_types=(str, bytes, dict)):
  4413. return x if isinstance(x, collections.abc.Iterable) and not isinstance(x, allowed_types) else (x,)
  4414. def time_seconds(**kwargs):
  4415. t = datetime.datetime.now(datetime.timezone(datetime.timedelta(**kwargs)))
  4416. return t.timestamp()
  4417. # create a JSON Web Signature (jws) with HS256 algorithm
  4418. # the resulting format is in JWS Compact Serialization
  4419. # implemented following JWT https://www.rfc-editor.org/rfc/rfc7519.html
  4420. # implemented following JWS https://www.rfc-editor.org/rfc/rfc7515.html
  4421. def jwt_encode_hs256(payload_data, key, headers={}):
  4422. header_data = {
  4423. 'alg': 'HS256',
  4424. 'typ': 'JWT',
  4425. }
  4426. if headers:
  4427. header_data.update(headers)
  4428. header_b64 = base64.b64encode(json.dumps(header_data).encode())
  4429. payload_b64 = base64.b64encode(json.dumps(payload_data).encode())
  4430. h = hmac.new(key.encode(), header_b64 + b'.' + payload_b64, hashlib.sha256)
  4431. signature_b64 = base64.b64encode(h.digest())
  4432. token = header_b64 + b'.' + payload_b64 + b'.' + signature_b64
  4433. return token
  4434. # can be extended in future to verify the signature and parse header and return the algorithm used if it's not HS256
  4435. def jwt_decode_hs256(jwt):
  4436. header_b64, payload_b64, signature_b64 = jwt.split('.')
  4437. payload_data = json.loads(base64.urlsafe_b64decode(payload_b64))
  4438. return payload_data
  4439. WINDOWS_VT_MODE = False if compat_os_name == 'nt' else None
  4440. @functools.cache
  4441. def supports_terminal_sequences(stream):
  4442. if compat_os_name == 'nt':
  4443. if not WINDOWS_VT_MODE:
  4444. return False
  4445. elif not os.getenv('TERM'):
  4446. return False
  4447. try:
  4448. return stream.isatty()
  4449. except BaseException:
  4450. return False
  4451. def windows_enable_vt_mode(): # TODO: Do this the proper way https://bugs.python.org/issue30075
  4452. if get_windows_version() < (10, 0, 10586):
  4453. return
  4454. global WINDOWS_VT_MODE
  4455. try:
  4456. Popen.run('', shell=True)
  4457. except Exception:
  4458. return
  4459. WINDOWS_VT_MODE = True
  4460. supports_terminal_sequences.cache_clear()
  4461. _terminal_sequences_re = re.compile('\033\\[[^m]+m')
  4462. def remove_terminal_sequences(string):
  4463. return _terminal_sequences_re.sub('', string)
  4464. def number_of_digits(number):
  4465. return len('%d' % number)
  4466. def join_nonempty(*values, delim='-', from_dict=None):
  4467. if from_dict is not None:
  4468. values = (traverse_obj(from_dict, variadic(v)) for v in values)
  4469. return delim.join(map(str, filter(None, values)))
  4470. def scale_thumbnails_to_max_format_width(formats, thumbnails, url_width_re):
  4471. """
  4472. Find the largest format dimensions in terms of video width and, for each thumbnail:
  4473. * Modify the URL: Match the width with the provided regex and replace with the former width
  4474. * Update dimensions
  4475. This function is useful with video services that scale the provided thumbnails on demand
  4476. """
  4477. _keys = ('width', 'height')
  4478. max_dimensions = max(
  4479. (tuple(format.get(k) or 0 for k in _keys) for format in formats),
  4480. default=(0, 0))
  4481. if not max_dimensions[0]:
  4482. return thumbnails
  4483. return [
  4484. merge_dicts(
  4485. {'url': re.sub(url_width_re, str(max_dimensions[0]), thumbnail['url'])},
  4486. dict(zip(_keys, max_dimensions)), thumbnail)
  4487. for thumbnail in thumbnails
  4488. ]
  4489. def parse_http_range(range):
  4490. """ Parse value of "Range" or "Content-Range" HTTP header into tuple. """
  4491. if not range:
  4492. return None, None, None
  4493. crg = re.search(r'bytes[ =](\d+)-(\d+)?(?:/(\d+))?', range)
  4494. if not crg:
  4495. return None, None, None
  4496. return int(crg.group(1)), int_or_none(crg.group(2)), int_or_none(crg.group(3))
  4497. def read_stdin(what):
  4498. eof = 'Ctrl+Z' if compat_os_name == 'nt' else 'Ctrl+D'
  4499. write_string(f'Reading {what} from STDIN - EOF ({eof}) to end:\n')
  4500. return sys.stdin
  4501. def determine_file_encoding(data):
  4502. """
  4503. Detect the text encoding used
  4504. @returns (encoding, bytes to skip)
  4505. """
  4506. # BOM marks are given priority over declarations
  4507. for bom, enc in BOMS:
  4508. if data.startswith(bom):
  4509. return enc, len(bom)
  4510. # Strip off all null bytes to match even when UTF-16 or UTF-32 is used.
  4511. # We ignore the endianness to get a good enough match
  4512. data = data.replace(b'\0', b'')
  4513. mobj = re.match(rb'(?m)^#\s*coding\s*:\s*(\S+)\s*$', data)
  4514. return mobj.group(1).decode() if mobj else None, 0
  4515. class Config:
  4516. own_args = None
  4517. parsed_args = None
  4518. filename = None
  4519. __initialized = False
  4520. def __init__(self, parser, label=None):
  4521. self.parser, self.label = parser, label
  4522. self._loaded_paths, self.configs = set(), []
  4523. def init(self, args=None, filename=None):
  4524. assert not self.__initialized
  4525. self.own_args, self.filename = args, filename
  4526. return self.load_configs()
  4527. def load_configs(self):
  4528. directory = ''
  4529. if self.filename:
  4530. location = os.path.realpath(self.filename)
  4531. directory = os.path.dirname(location)
  4532. if location in self._loaded_paths:
  4533. return False
  4534. self._loaded_paths.add(location)
  4535. self.__initialized = True
  4536. opts, _ = self.parser.parse_known_args(self.own_args)
  4537. self.parsed_args = self.own_args
  4538. for location in opts.config_locations or []:
  4539. if location == '-':
  4540. self.append_config(shlex.split(read_stdin('options'), comments=True), label='stdin')
  4541. continue
  4542. location = os.path.join(directory, expand_path(location))
  4543. if os.path.isdir(location):
  4544. location = os.path.join(location, 'yt-dlp.conf')
  4545. if not os.path.exists(location):
  4546. self.parser.error(f'config location {location} does not exist')
  4547. self.append_config(self.read_file(location), location)
  4548. return True
  4549. def __str__(self):
  4550. label = join_nonempty(
  4551. self.label, 'config', f'"{self.filename}"' if self.filename else '',
  4552. delim=' ')
  4553. return join_nonempty(
  4554. self.own_args is not None and f'{label[0].upper()}{label[1:]}: {self.hide_login_info(self.own_args)}',
  4555. *(f'\n{c}'.replace('\n', '\n| ')[1:] for c in self.configs),
  4556. delim='\n')
  4557. @staticmethod
  4558. def read_file(filename, default=[]):
  4559. try:
  4560. optionf = open(filename, 'rb')
  4561. except OSError:
  4562. return default # silently skip if file is not present
  4563. try:
  4564. enc, skip = determine_file_encoding(optionf.read(512))
  4565. optionf.seek(skip, io.SEEK_SET)
  4566. except OSError:
  4567. enc = None # silently skip read errors
  4568. try:
  4569. # FIXME: https://github.com/ytdl-org/youtube-dl/commit/dfe5fa49aed02cf36ba9f743b11b0903554b5e56
  4570. contents = optionf.read().decode(enc or preferredencoding())
  4571. res = shlex.split(contents, comments=True)
  4572. except Exception as err:
  4573. raise ValueError(f'Unable to parse "{filename}": {err}')
  4574. finally:
  4575. optionf.close()
  4576. return res
  4577. @staticmethod
  4578. def hide_login_info(opts):
  4579. PRIVATE_OPTS = {'-p', '--password', '-u', '--username', '--video-password', '--ap-password', '--ap-username'}
  4580. eqre = re.compile('^(?P<key>' + ('|'.join(re.escape(po) for po in PRIVATE_OPTS)) + ')=.+$')
  4581. def _scrub_eq(o):
  4582. m = eqre.match(o)
  4583. if m:
  4584. return m.group('key') + '=PRIVATE'
  4585. else:
  4586. return o
  4587. opts = list(map(_scrub_eq, opts))
  4588. for idx, opt in enumerate(opts):
  4589. if opt in PRIVATE_OPTS and idx + 1 < len(opts):
  4590. opts[idx + 1] = 'PRIVATE'
  4591. return opts
  4592. def append_config(self, *args, label=None):
  4593. config = type(self)(self.parser, label)
  4594. config._loaded_paths = self._loaded_paths
  4595. if config.init(*args):
  4596. self.configs.append(config)
  4597. @property
  4598. def all_args(self):
  4599. for config in reversed(self.configs):
  4600. yield from config.all_args
  4601. yield from self.parsed_args or []
  4602. def parse_known_args(self, **kwargs):
  4603. return self.parser.parse_known_args(self.all_args, **kwargs)
  4604. def parse_args(self):
  4605. return self.parser.parse_args(self.all_args)
  4606. class WebSocketsWrapper():
  4607. """Wraps websockets module to use in non-async scopes"""
  4608. pool = None
  4609. def __init__(self, url, headers=None, connect=True):
  4610. self.loop = asyncio.new_event_loop()
  4611. # XXX: "loop" is deprecated
  4612. self.conn = websockets.connect(
  4613. url, extra_headers=headers, ping_interval=None,
  4614. close_timeout=float('inf'), loop=self.loop, ping_timeout=float('inf'))
  4615. if connect:
  4616. self.__enter__()
  4617. atexit.register(self.__exit__, None, None, None)
  4618. def __enter__(self):
  4619. if not self.pool:
  4620. self.pool = self.run_with_loop(self.conn.__aenter__(), self.loop)
  4621. return self
  4622. def send(self, *args):
  4623. self.run_with_loop(self.pool.send(*args), self.loop)
  4624. def recv(self, *args):
  4625. return self.run_with_loop(self.pool.recv(*args), self.loop)
  4626. def __exit__(self, type, value, traceback):
  4627. try:
  4628. return self.run_with_loop(self.conn.__aexit__(type, value, traceback), self.loop)
  4629. finally:
  4630. self.loop.close()
  4631. self._cancel_all_tasks(self.loop)
  4632. # taken from https://github.com/python/cpython/blob/3.9/Lib/asyncio/runners.py with modifications
  4633. # for contributors: If there's any new library using asyncio needs to be run in non-async, move these function out of this class
  4634. @staticmethod
  4635. def run_with_loop(main, loop):
  4636. if not asyncio.iscoroutine(main):
  4637. raise ValueError(f'a coroutine was expected, got {main!r}')
  4638. try:
  4639. return loop.run_until_complete(main)
  4640. finally:
  4641. loop.run_until_complete(loop.shutdown_asyncgens())
  4642. if hasattr(loop, 'shutdown_default_executor'):
  4643. loop.run_until_complete(loop.shutdown_default_executor())
  4644. @staticmethod
  4645. def _cancel_all_tasks(loop):
  4646. to_cancel = asyncio.all_tasks(loop)
  4647. if not to_cancel:
  4648. return
  4649. for task in to_cancel:
  4650. task.cancel()
  4651. # XXX: "loop" is removed in python 3.10+
  4652. loop.run_until_complete(
  4653. asyncio.gather(*to_cancel, loop=loop, return_exceptions=True))
  4654. for task in to_cancel:
  4655. if task.cancelled():
  4656. continue
  4657. if task.exception() is not None:
  4658. loop.call_exception_handler({
  4659. 'message': 'unhandled exception during asyncio.run() shutdown',
  4660. 'exception': task.exception(),
  4661. 'task': task,
  4662. })
  4663. def merge_headers(*dicts):
  4664. """Merge dicts of http headers case insensitively, prioritizing the latter ones"""
  4665. return {k.title(): v for k, v in itertools.chain.from_iterable(map(dict.items, dicts))}
  4666. def cached_method(f):
  4667. """Cache a method"""
  4668. signature = inspect.signature(f)
  4669. @functools.wraps(f)
  4670. def wrapper(self, *args, **kwargs):
  4671. bound_args = signature.bind(self, *args, **kwargs)
  4672. bound_args.apply_defaults()
  4673. key = tuple(bound_args.arguments.values())
  4674. if not hasattr(self, '__cached_method__cache'):
  4675. self.__cached_method__cache = {}
  4676. cache = self.__cached_method__cache.setdefault(f.__name__, {})
  4677. if key not in cache:
  4678. cache[key] = f(self, *args, **kwargs)
  4679. return cache[key]
  4680. return wrapper
  4681. class classproperty:
  4682. """property access for class methods"""
  4683. def __init__(self, func):
  4684. functools.update_wrapper(self, func)
  4685. self.func = func
  4686. def __get__(self, _, cls):
  4687. return self.func(cls)
  4688. class Namespace(types.SimpleNamespace):
  4689. """Immutable namespace"""
  4690. def __iter__(self):
  4691. return iter(self.__dict__.values())
  4692. @property
  4693. def items_(self):
  4694. return self.__dict__.items()
  4695. # Deprecated
  4696. has_certifi = bool(certifi)
  4697. has_websockets = bool(websockets)