utils.py 182 KB

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