utils.py 176 KB

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