common.py 187 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979
  1. import base64
  2. import collections
  3. import functools
  4. import getpass
  5. import hashlib
  6. import http.client
  7. import http.cookiejar
  8. import http.cookies
  9. import inspect
  10. import itertools
  11. import json
  12. import math
  13. import netrc
  14. import os
  15. import random
  16. import re
  17. import subprocess
  18. import sys
  19. import time
  20. import types
  21. import urllib.parse
  22. import urllib.request
  23. import xml.etree.ElementTree
  24. from ..compat import (
  25. compat_etree_fromstring,
  26. compat_expanduser,
  27. compat_os_name,
  28. urllib_req_to_req,
  29. )
  30. from ..cookies import LenientSimpleCookie
  31. from ..downloader.f4m import get_base_url, remove_encrypted_media
  32. from ..downloader.hls import HlsFD
  33. from ..networking import HEADRequest, Request
  34. from ..networking.exceptions import (
  35. HTTPError,
  36. IncompleteRead,
  37. network_exceptions,
  38. )
  39. from ..networking.impersonate import ImpersonateTarget
  40. from ..utils import (
  41. IDENTITY,
  42. JSON_LD_RE,
  43. NO_DEFAULT,
  44. ExtractorError,
  45. FormatSorter,
  46. GeoRestrictedError,
  47. GeoUtils,
  48. LenientJSONDecoder,
  49. Popen,
  50. RegexNotFoundError,
  51. RetryManager,
  52. UnsupportedError,
  53. age_restricted,
  54. base_url,
  55. bug_reports_message,
  56. classproperty,
  57. clean_html,
  58. deprecation_warning,
  59. determine_ext,
  60. dict_get,
  61. encode_data_uri,
  62. error_to_compat_str,
  63. extract_attributes,
  64. filter_dict,
  65. fix_xml_ampersands,
  66. float_or_none,
  67. format_field,
  68. int_or_none,
  69. join_nonempty,
  70. js_to_json,
  71. mimetype2ext,
  72. netrc_from_content,
  73. orderedSet,
  74. parse_bitrate,
  75. parse_codecs,
  76. parse_duration,
  77. parse_iso8601,
  78. parse_m3u8_attributes,
  79. parse_resolution,
  80. sanitize_filename,
  81. sanitize_url,
  82. smuggle_url,
  83. str_or_none,
  84. str_to_int,
  85. strip_or_none,
  86. traverse_obj,
  87. truncate_string,
  88. try_call,
  89. try_get,
  90. unescapeHTML,
  91. unified_strdate,
  92. unified_timestamp,
  93. url_basename,
  94. url_or_none,
  95. urlhandle_detect_ext,
  96. urljoin,
  97. variadic,
  98. xpath_element,
  99. xpath_text,
  100. xpath_with_ns,
  101. )
  102. class InfoExtractor:
  103. """Information Extractor class.
  104. Information extractors are the classes that, given a URL, extract
  105. information about the video (or videos) the URL refers to. This
  106. information includes the real video URL, the video title, author and
  107. others. The information is stored in a dictionary which is then
  108. passed to the YoutubeDL. The YoutubeDL processes this
  109. information possibly downloading the video to the file system, among
  110. other possible outcomes.
  111. The type field determines the type of the result.
  112. By far the most common value (and the default if _type is missing) is
  113. "video", which indicates a single video.
  114. For a video, the dictionaries must include the following fields:
  115. id: Video identifier.
  116. title: Video title, unescaped. Set to an empty string if video has
  117. no title as opposed to "None" which signifies that the
  118. extractor failed to obtain a title
  119. Additionally, it must contain either a formats entry or a url one:
  120. formats: A list of dictionaries for each format available, ordered
  121. from worst to best quality.
  122. Potential fields:
  123. * url The mandatory URL representing the media:
  124. for plain file media - HTTP URL of this file,
  125. for RTMP - RTMP URL,
  126. for HLS - URL of the M3U8 media playlist,
  127. for HDS - URL of the F4M manifest,
  128. for DASH
  129. - HTTP URL to plain file media (in case of
  130. unfragmented media)
  131. - URL of the MPD manifest or base URL
  132. representing the media if MPD manifest
  133. is parsed from a string (in case of
  134. fragmented media)
  135. for MSS - URL of the ISM manifest.
  136. * request_data Data to send in POST request to the URL
  137. * manifest_url
  138. The URL of the manifest file in case of
  139. fragmented media:
  140. for HLS - URL of the M3U8 master playlist,
  141. for HDS - URL of the F4M manifest,
  142. for DASH - URL of the MPD manifest,
  143. for MSS - URL of the ISM manifest.
  144. * manifest_stream_number (For internal use only)
  145. The index of the stream in the manifest file
  146. * ext Will be calculated from URL if missing
  147. * format A human-readable description of the format
  148. ("mp4 container with h264/opus").
  149. Calculated from the format_id, width, height.
  150. and format_note fields if missing.
  151. * format_id A short description of the format
  152. ("mp4_h264_opus" or "19").
  153. Technically optional, but strongly recommended.
  154. * format_note Additional info about the format
  155. ("3D" or "DASH video")
  156. * width Width of the video, if known
  157. * height Height of the video, if known
  158. * aspect_ratio Aspect ratio of the video, if known
  159. Automatically calculated from width and height
  160. * resolution Textual description of width and height
  161. Automatically calculated from width and height
  162. * dynamic_range The dynamic range of the video. One of:
  163. "SDR" (None), "HDR10", "HDR10+, "HDR12", "HLG, "DV"
  164. * tbr Average bitrate of audio and video in kbps (1000 bits/sec)
  165. * abr Average audio bitrate in kbps (1000 bits/sec)
  166. * acodec Name of the audio codec in use
  167. * asr Audio sampling rate in Hertz
  168. * audio_channels Number of audio channels
  169. * vbr Average video bitrate in kbps (1000 bits/sec)
  170. * fps Frame rate
  171. * vcodec Name of the video codec in use
  172. * container Name of the container format
  173. * filesize The number of bytes, if known in advance
  174. * filesize_approx An estimate for the number of bytes
  175. * player_url SWF Player URL (used for rtmpdump).
  176. * protocol The protocol that will be used for the actual
  177. download, lower-case. One of "http", "https" or
  178. one of the protocols defined in downloader.PROTOCOL_MAP
  179. * fragment_base_url
  180. Base URL for fragments. Each fragment's path
  181. value (if present) will be relative to
  182. this URL.
  183. * fragments A list of fragments of a fragmented media.
  184. Each fragment entry must contain either an url
  185. or a path. If an url is present it should be
  186. considered by a client. Otherwise both path and
  187. fragment_base_url must be present. Here is
  188. the list of all potential fields:
  189. * "url" - fragment's URL
  190. * "path" - fragment's path relative to
  191. fragment_base_url
  192. * "duration" (optional, int or float)
  193. * "filesize" (optional, int)
  194. * is_from_start Is a live format that can be downloaded
  195. from the start. Boolean
  196. * preference Order number of this format. If this field is
  197. present and not None, the formats get sorted
  198. by this field, regardless of all other values.
  199. -1 for default (order by other properties),
  200. -2 or smaller for less than default.
  201. < -1000 to hide the format (if there is
  202. another one which is strictly better)
  203. * language Language code, e.g. "de" or "en-US".
  204. * language_preference Is this in the language mentioned in
  205. the URL?
  206. 10 if it's what the URL is about,
  207. -1 for default (don't know),
  208. -10 otherwise, other values reserved for now.
  209. * quality Order number of the video quality of this
  210. format, irrespective of the file format.
  211. -1 for default (order by other properties),
  212. -2 or smaller for less than default.
  213. * source_preference Order number for this video source
  214. (quality takes higher priority)
  215. -1 for default (order by other properties),
  216. -2 or smaller for less than default.
  217. * http_headers A dictionary of additional HTTP headers
  218. to add to the request.
  219. * stretched_ratio If given and not 1, indicates that the
  220. video's pixels are not square.
  221. width : height ratio as float.
  222. * no_resume The server does not support resuming the
  223. (HTTP or RTMP) download. Boolean.
  224. * has_drm True if the format has DRM and cannot be downloaded.
  225. 'maybe' if the format may have DRM and has to be tested before download.
  226. * extra_param_to_segment_url A query string to append to each
  227. fragment's URL, or to update each existing query string
  228. with. Only applied by the native HLS/DASH downloaders.
  229. * hls_aes A dictionary of HLS AES-128 decryption information
  230. used by the native HLS downloader to override the
  231. values in the media playlist when an '#EXT-X-KEY' tag
  232. is present in the playlist:
  233. * uri The URI from which the key will be downloaded
  234. * key The key (as hex) used to decrypt fragments.
  235. If `key` is given, any key URI will be ignored
  236. * iv The IV (as hex) used to decrypt fragments
  237. * downloader_options A dictionary of downloader options
  238. (For internal use only)
  239. * http_chunk_size Chunk size for HTTP downloads
  240. * ffmpeg_args Extra arguments for ffmpeg downloader (input)
  241. * ffmpeg_args_out Extra arguments for ffmpeg downloader (output)
  242. * is_dash_periods Whether the format is a result of merging
  243. multiple DASH periods.
  244. RTMP formats can also have the additional fields: page_url,
  245. app, play_path, tc_url, flash_version, rtmp_live, rtmp_conn,
  246. rtmp_protocol, rtmp_real_time
  247. url: Final video URL.
  248. ext: Video filename extension.
  249. format: The video format, defaults to ext (used for --get-format)
  250. player_url: SWF Player URL (used for rtmpdump).
  251. The following fields are optional:
  252. direct: True if a direct video file was given (must only be set by GenericIE)
  253. alt_title: A secondary title of the video.
  254. display_id: An alternative identifier for the video, not necessarily
  255. unique, but available before title. Typically, id is
  256. something like "4234987", title "Dancing naked mole rats",
  257. and display_id "dancing-naked-mole-rats"
  258. thumbnails: A list of dictionaries, with the following entries:
  259. * "id" (optional, string) - Thumbnail format ID
  260. * "url"
  261. * "preference" (optional, int) - quality of the image
  262. * "width" (optional, int)
  263. * "height" (optional, int)
  264. * "resolution" (optional, string "{width}x{height}",
  265. deprecated)
  266. * "filesize" (optional, int)
  267. * "http_headers" (dict) - HTTP headers for the request
  268. thumbnail: Full URL to a video thumbnail image.
  269. description: Full video description.
  270. uploader: Full name of the video uploader.
  271. license: License name the video is licensed under.
  272. creators: List of creators of the video.
  273. timestamp: UNIX timestamp of the moment the video was uploaded
  274. upload_date: Video upload date in UTC (YYYYMMDD).
  275. If not explicitly set, calculated from timestamp
  276. release_timestamp: UNIX timestamp of the moment the video was released.
  277. If it is not clear whether to use timestamp or this, use the former
  278. release_date: The date (YYYYMMDD) when the video was released in UTC.
  279. If not explicitly set, calculated from release_timestamp
  280. release_year: Year (YYYY) as integer when the video or album was released.
  281. To be used if no exact release date is known.
  282. If not explicitly set, calculated from release_date.
  283. modified_timestamp: UNIX timestamp of the moment the video was last modified.
  284. modified_date: The date (YYYYMMDD) when the video was last modified in UTC.
  285. If not explicitly set, calculated from modified_timestamp
  286. uploader_id: Nickname or id of the video uploader.
  287. uploader_url: Full URL to a personal webpage of the video uploader.
  288. channel: Full name of the channel the video is uploaded on.
  289. Note that channel fields may or may not repeat uploader
  290. fields. This depends on a particular extractor.
  291. channel_id: Id of the channel.
  292. channel_url: Full URL to a channel webpage.
  293. channel_follower_count: Number of followers of the channel.
  294. channel_is_verified: Whether the channel is verified on the platform.
  295. location: Physical location where the video was filmed.
  296. subtitles: The available subtitles as a dictionary in the format
  297. {tag: subformats}. "tag" is usually a language code, and
  298. "subformats" is a list sorted from lower to higher
  299. preference, each element is a dictionary with the "ext"
  300. entry and one of:
  301. * "data": The subtitles file contents
  302. * "url": A URL pointing to the subtitles file
  303. It can optionally also have:
  304. * "name": Name or description of the subtitles
  305. * "http_headers": A dictionary of additional HTTP headers
  306. to add to the request.
  307. "ext" will be calculated from URL if missing
  308. automatic_captions: Like 'subtitles'; contains automatically generated
  309. captions instead of normal subtitles
  310. duration: Length of the video in seconds, as an integer or float.
  311. view_count: How many users have watched the video on the platform.
  312. concurrent_view_count: How many users are currently watching the video on the platform.
  313. like_count: Number of positive ratings of the video
  314. dislike_count: Number of negative ratings of the video
  315. repost_count: Number of reposts of the video
  316. average_rating: Average rating give by users, the scale used depends on the webpage
  317. comment_count: Number of comments on the video
  318. comments: A list of comments, each with one or more of the following
  319. properties (all but one of text or html optional):
  320. * "author" - human-readable name of the comment author
  321. * "author_id" - user ID of the comment author
  322. * "author_thumbnail" - The thumbnail of the comment author
  323. * "author_url" - The url to the comment author's page
  324. * "author_is_verified" - Whether the author is verified
  325. on the platform
  326. * "author_is_uploader" - Whether the comment is made by
  327. the video uploader
  328. * "id" - Comment ID
  329. * "html" - Comment as HTML
  330. * "text" - Plain text of the comment
  331. * "timestamp" - UNIX timestamp of comment
  332. * "parent" - ID of the comment this one is replying to.
  333. Set to "root" to indicate that this is a
  334. comment to the original video.
  335. * "like_count" - Number of positive ratings of the comment
  336. * "dislike_count" - Number of negative ratings of the comment
  337. * "is_favorited" - Whether the comment is marked as
  338. favorite by the video uploader
  339. * "is_pinned" - Whether the comment is pinned to
  340. the top of the comments
  341. age_limit: Age restriction for the video, as an integer (years)
  342. webpage_url: The URL to the video webpage, if given to yt-dlp it
  343. should allow to get the same result again. (It will be set
  344. by YoutubeDL if it's missing)
  345. categories: A list of categories that the video falls in, for example
  346. ["Sports", "Berlin"]
  347. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  348. cast: A list of the video cast
  349. is_live: True, False, or None (=unknown). Whether this video is a
  350. live stream that goes on instead of a fixed-length video.
  351. was_live: True, False, or None (=unknown). Whether this video was
  352. originally a live stream.
  353. live_status: None (=unknown), 'is_live', 'is_upcoming', 'was_live', 'not_live',
  354. or 'post_live' (was live, but VOD is not yet processed)
  355. If absent, automatically set from is_live, was_live
  356. start_time: Time in seconds where the reproduction should start, as
  357. specified in the URL.
  358. end_time: Time in seconds where the reproduction should end, as
  359. specified in the URL.
  360. chapters: A list of dictionaries, with the following entries:
  361. * "start_time" - The start time of the chapter in seconds
  362. * "end_time" - The end time of the chapter in seconds
  363. * "title" (optional, string)
  364. heatmap: A list of dictionaries, with the following entries:
  365. * "start_time" - The start time of the data point in seconds
  366. * "end_time" - The end time of the data point in seconds
  367. * "value" - The normalized value of the data point (float between 0 and 1)
  368. playable_in_embed: Whether this video is allowed to play in embedded
  369. players on other sites. Can be True (=always allowed),
  370. False (=never allowed), None (=unknown), or a string
  371. specifying the criteria for embedability; e.g. 'whitelist'
  372. availability: Under what condition the video is available. One of
  373. 'private', 'premium_only', 'subscriber_only', 'needs_auth',
  374. 'unlisted' or 'public'. Use 'InfoExtractor._availability'
  375. to set it
  376. media_type: The type of media as classified by the site, e.g. "episode", "clip", "trailer"
  377. _old_archive_ids: A list of old archive ids needed for backward compatibility
  378. _format_sort_fields: A list of fields to use for sorting formats
  379. __post_extractor: A function to be called just before the metadata is
  380. written to either disk, logger or console. The function
  381. must return a dict which will be added to the info_dict.
  382. This is usefull for additional information that is
  383. time-consuming to extract. Note that the fields thus
  384. extracted will not be available to output template and
  385. match_filter. So, only "comments" and "comment_count" are
  386. currently allowed to be extracted via this method.
  387. The following fields should only be used when the video belongs to some logical
  388. chapter or section:
  389. chapter: Name or title of the chapter the video belongs to.
  390. chapter_number: Number of the chapter the video belongs to, as an integer.
  391. chapter_id: Id of the chapter the video belongs to, as a unicode string.
  392. The following fields should only be used when the video is an episode of some
  393. series, programme or podcast:
  394. series: Title of the series or programme the video episode belongs to.
  395. series_id: Id of the series or programme the video episode belongs to, as a unicode string.
  396. season: Title of the season the video episode belongs to.
  397. season_number: Number of the season the video episode belongs to, as an integer.
  398. season_id: Id of the season the video episode belongs to, as a unicode string.
  399. episode: Title of the video episode. Unlike mandatory video title field,
  400. this field should denote the exact title of the video episode
  401. without any kind of decoration.
  402. episode_number: Number of the video episode within a season, as an integer.
  403. episode_id: Id of the video episode, as a unicode string.
  404. The following fields should only be used when the media is a track or a part of
  405. a music album:
  406. track: Title of the track.
  407. track_number: Number of the track within an album or a disc, as an integer.
  408. track_id: Id of the track (useful in case of custom indexing, e.g. 6.iii),
  409. as a unicode string.
  410. artists: List of artists of the track.
  411. composers: List of composers of the piece.
  412. genres: List of genres of the track.
  413. album: Title of the album the track belongs to.
  414. album_type: Type of the album (e.g. "Demo", "Full-length", "Split", "Compilation", etc).
  415. album_artists: List of all artists appeared on the album.
  416. E.g. ["Ash Borer", "Fell Voices"] or ["Various Artists"].
  417. Useful for splits and compilations.
  418. disc_number: Number of the disc or other physical medium the track belongs to,
  419. as an integer.
  420. The following fields should only be set for clips that should be cut from the original video:
  421. section_start: Start time of the section in seconds
  422. section_end: End time of the section in seconds
  423. The following fields should only be set for storyboards:
  424. rows: Number of rows in each storyboard fragment, as an integer
  425. columns: Number of columns in each storyboard fragment, as an integer
  426. The following fields are deprecated and should not be set by new code:
  427. composer: Use "composers" instead.
  428. Composer(s) of the piece, comma-separated.
  429. artist: Use "artists" instead.
  430. Artist(s) of the track, comma-separated.
  431. genre: Use "genres" instead.
  432. Genre(s) of the track, comma-separated.
  433. album_artist: Use "album_artists" instead.
  434. All artists appeared on the album, comma-separated.
  435. creator: Use "creators" instead.
  436. The creator of the video.
  437. Unless mentioned otherwise, the fields should be Unicode strings.
  438. Unless mentioned otherwise, None is equivalent to absence of information.
  439. _type "playlist" indicates multiple videos.
  440. There must be a key "entries", which is a list, an iterable, or a PagedList
  441. object, each element of which is a valid dictionary by this specification.
  442. Additionally, playlists can have "id", "title", and any other relevant
  443. attributes with the same semantics as videos (see above).
  444. It can also have the following optional fields:
  445. playlist_count: The total number of videos in a playlist. If not given,
  446. YoutubeDL tries to calculate it from "entries"
  447. _type "multi_video" indicates that there are multiple videos that
  448. form a single show, for examples multiple acts of an opera or TV episode.
  449. It must have an entries key like a playlist and contain all the keys
  450. required for a video at the same time.
  451. _type "url" indicates that the video must be extracted from another
  452. location, possibly by a different extractor. Its only required key is:
  453. "url" - the next URL to extract.
  454. The key "ie_key" can be set to the class name (minus the trailing "IE",
  455. e.g. "Youtube") if the extractor class is known in advance.
  456. Additionally, the dictionary may have any properties of the resolved entity
  457. known in advance, for example "title" if the title of the referred video is
  458. known ahead of time.
  459. _type "url_transparent" entities have the same specification as "url", but
  460. indicate that the given additional information is more precise than the one
  461. associated with the resolved URL.
  462. This is useful when a site employs a video service that hosts the video and
  463. its technical metadata, but that video service does not embed a useful
  464. title, description etc.
  465. Subclasses of this should also be added to the list of extractors and
  466. should define _VALID_URL as a regexp or a Sequence of regexps, and
  467. re-define the _real_extract() and (optionally) _real_initialize() methods.
  468. Subclasses may also override suitable() if necessary, but ensure the function
  469. signature is preserved and that this function imports everything it needs
  470. (except other extractors), so that lazy_extractors works correctly.
  471. Subclasses can define a list of _EMBED_REGEX, which will be searched for in
  472. the HTML of Generic webpages. It may also override _extract_embed_urls
  473. or _extract_from_webpage as necessary. While these are normally classmethods,
  474. _extract_from_webpage is allowed to be an instance method.
  475. _extract_from_webpage may raise self.StopExtraction() to stop further
  476. processing of the webpage and obtain exclusive rights to it. This is useful
  477. when the extractor cannot reliably be matched using just the URL,
  478. e.g. invidious/peertube instances
  479. Embed-only extractors can be defined by setting _VALID_URL = False.
  480. To support username + password (or netrc) login, the extractor must define a
  481. _NETRC_MACHINE and re-define _perform_login(username, password) and
  482. (optionally) _initialize_pre_login() methods. The _perform_login method will
  483. be called between _initialize_pre_login and _real_initialize if credentials
  484. are passed by the user. In cases where it is necessary to have the login
  485. process as part of the extraction rather than initialization, _perform_login
  486. can be left undefined.
  487. _GEO_BYPASS attribute may be set to False in order to disable
  488. geo restriction bypass mechanisms for a particular extractor.
  489. Though it won't disable explicit geo restriction bypass based on
  490. country code provided with geo_bypass_country.
  491. _GEO_COUNTRIES attribute may contain a list of presumably geo unrestricted
  492. countries for this extractor. One of these countries will be used by
  493. geo restriction bypass mechanism right away in order to bypass
  494. geo restriction, of course, if the mechanism is not disabled.
  495. _GEO_IP_BLOCKS attribute may contain a list of presumably geo unrestricted
  496. IP blocks in CIDR notation for this extractor. One of these IP blocks
  497. will be used by geo restriction bypass mechanism similarly
  498. to _GEO_COUNTRIES.
  499. The _ENABLED attribute should be set to False for IEs that
  500. are disabled by default and must be explicitly enabled.
  501. The _WORKING attribute should be set to False for broken IEs
  502. in order to warn the users and skip the tests.
  503. """
  504. _ready = False
  505. _downloader = None
  506. _x_forwarded_for_ip = None
  507. _GEO_BYPASS = True
  508. _GEO_COUNTRIES = None
  509. _GEO_IP_BLOCKS = None
  510. _WORKING = True
  511. _ENABLED = True
  512. _NETRC_MACHINE = None
  513. IE_DESC = None
  514. SEARCH_KEY = None
  515. _VALID_URL = None
  516. _EMBED_REGEX = []
  517. def _login_hint(self, method=NO_DEFAULT, netrc=None):
  518. password_hint = f'--username and --password, --netrc-cmd, or --netrc ({netrc or self._NETRC_MACHINE}) to provide account credentials'
  519. return {
  520. None: '',
  521. 'any': f'Use --cookies, --cookies-from-browser, {password_hint}',
  522. 'password': f'Use {password_hint}',
  523. 'cookies': (
  524. 'Use --cookies-from-browser or --cookies for the authentication. '
  525. 'See https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp for how to manually pass cookies'),
  526. }[method if method is not NO_DEFAULT else 'any' if self.supports_login() else 'cookies']
  527. def __init__(self, downloader=None):
  528. """Constructor. Receives an optional downloader (a YoutubeDL instance).
  529. If a downloader is not passed during initialization,
  530. it must be set using "set_downloader()" before "extract()" is called"""
  531. self._ready = False
  532. self._x_forwarded_for_ip = None
  533. self._printed_messages = set()
  534. self.set_downloader(downloader)
  535. @classmethod
  536. def _match_valid_url(cls, url):
  537. if cls._VALID_URL is False:
  538. return None
  539. # This does not use has/getattr intentionally - we want to know whether
  540. # we have cached the regexp for *this* class, whereas getattr would also
  541. # match the superclass
  542. if '_VALID_URL_RE' not in cls.__dict__:
  543. cls._VALID_URL_RE = tuple(map(re.compile, variadic(cls._VALID_URL)))
  544. return next(filter(None, (regex.match(url) for regex in cls._VALID_URL_RE)), None)
  545. @classmethod
  546. def suitable(cls, url):
  547. """Receives a URL and returns True if suitable for this IE."""
  548. # This function must import everything it needs (except other extractors),
  549. # so that lazy_extractors works correctly
  550. return cls._match_valid_url(url) is not None
  551. @classmethod
  552. def _match_id(cls, url):
  553. return cls._match_valid_url(url).group('id')
  554. @classmethod
  555. def get_temp_id(cls, url):
  556. try:
  557. return cls._match_id(url)
  558. except (IndexError, AttributeError):
  559. return None
  560. @classmethod
  561. def working(cls):
  562. """Getter method for _WORKING."""
  563. return cls._WORKING
  564. @classmethod
  565. def supports_login(cls):
  566. return bool(cls._NETRC_MACHINE)
  567. def initialize(self):
  568. """Initializes an instance (authentication, etc)."""
  569. self._printed_messages = set()
  570. self._initialize_geo_bypass({
  571. 'countries': self._GEO_COUNTRIES,
  572. 'ip_blocks': self._GEO_IP_BLOCKS,
  573. })
  574. if not self._ready:
  575. self._initialize_pre_login()
  576. if self.supports_login():
  577. username, password = self._get_login_info()
  578. if username:
  579. self._perform_login(username, password)
  580. elif self.get_param('username') and False not in (self.IE_DESC, self._NETRC_MACHINE):
  581. self.report_warning(f'Login with password is not supported for this website. {self._login_hint("cookies")}')
  582. self._real_initialize()
  583. self._ready = True
  584. def _initialize_geo_bypass(self, geo_bypass_context):
  585. """
  586. Initialize geo restriction bypass mechanism.
  587. This method is used to initialize geo bypass mechanism based on faking
  588. X-Forwarded-For HTTP header. A random country from provided country list
  589. is selected and a random IP belonging to this country is generated. This
  590. IP will be passed as X-Forwarded-For HTTP header in all subsequent
  591. HTTP requests.
  592. This method will be used for initial geo bypass mechanism initialization
  593. during the instance initialization with _GEO_COUNTRIES and
  594. _GEO_IP_BLOCKS.
  595. You may also manually call it from extractor's code if geo bypass
  596. information is not available beforehand (e.g. obtained during
  597. extraction) or due to some other reason. In this case you should pass
  598. this information in geo bypass context passed as first argument. It may
  599. contain following fields:
  600. countries: List of geo unrestricted countries (similar
  601. to _GEO_COUNTRIES)
  602. ip_blocks: List of geo unrestricted IP blocks in CIDR notation
  603. (similar to _GEO_IP_BLOCKS)
  604. """
  605. if not self._x_forwarded_for_ip:
  606. # Geo bypass mechanism is explicitly disabled by user
  607. if not self.get_param('geo_bypass', True):
  608. return
  609. if not geo_bypass_context:
  610. geo_bypass_context = {}
  611. # Backward compatibility: previously _initialize_geo_bypass
  612. # expected a list of countries, some 3rd party code may still use
  613. # it this way
  614. if isinstance(geo_bypass_context, (list, tuple)):
  615. geo_bypass_context = {
  616. 'countries': geo_bypass_context,
  617. }
  618. # The whole point of geo bypass mechanism is to fake IP
  619. # as X-Forwarded-For HTTP header based on some IP block or
  620. # country code.
  621. # Path 1: bypassing based on IP block in CIDR notation
  622. # Explicit IP block specified by user, use it right away
  623. # regardless of whether extractor is geo bypassable or not
  624. ip_block = self.get_param('geo_bypass_ip_block', None)
  625. # Otherwise use random IP block from geo bypass context but only
  626. # if extractor is known as geo bypassable
  627. if not ip_block:
  628. ip_blocks = geo_bypass_context.get('ip_blocks')
  629. if self._GEO_BYPASS and ip_blocks:
  630. ip_block = random.choice(ip_blocks)
  631. if ip_block:
  632. self._x_forwarded_for_ip = GeoUtils.random_ipv4(ip_block)
  633. self.write_debug(f'Using fake IP {self._x_forwarded_for_ip} as X-Forwarded-For')
  634. return
  635. # Path 2: bypassing based on country code
  636. # Explicit country code specified by user, use it right away
  637. # regardless of whether extractor is geo bypassable or not
  638. country = self.get_param('geo_bypass_country', None)
  639. # Otherwise use random country code from geo bypass context but
  640. # only if extractor is known as geo bypassable
  641. if not country:
  642. countries = geo_bypass_context.get('countries')
  643. if self._GEO_BYPASS and countries:
  644. country = random.choice(countries)
  645. if country:
  646. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country)
  647. self._downloader.write_debug(
  648. f'Using fake IP {self._x_forwarded_for_ip} ({country.upper()}) as X-Forwarded-For')
  649. def extract(self, url):
  650. """Extracts URL information and returns it in list of dicts."""
  651. try:
  652. for _ in range(2):
  653. try:
  654. self.initialize()
  655. self.to_screen('Extracting URL: %s' % (
  656. url if self.get_param('verbose') else truncate_string(url, 100, 20)))
  657. ie_result = self._real_extract(url)
  658. if ie_result is None:
  659. return None
  660. if self._x_forwarded_for_ip:
  661. ie_result['__x_forwarded_for_ip'] = self._x_forwarded_for_ip
  662. subtitles = ie_result.get('subtitles') or {}
  663. if 'no-live-chat' in self.get_param('compat_opts'):
  664. for lang in ('live_chat', 'comments', 'danmaku'):
  665. subtitles.pop(lang, None)
  666. return ie_result
  667. except GeoRestrictedError as e:
  668. if self.__maybe_fake_ip_and_retry(e.countries):
  669. continue
  670. raise
  671. except UnsupportedError:
  672. raise
  673. except ExtractorError as e:
  674. e.video_id = e.video_id or self.get_temp_id(url)
  675. e.ie = e.ie or self.IE_NAME
  676. e.traceback = e.traceback or sys.exc_info()[2]
  677. raise
  678. except IncompleteRead as e:
  679. raise ExtractorError('A network error has occurred.', cause=e, expected=True, video_id=self.get_temp_id(url))
  680. except (KeyError, StopIteration) as e:
  681. raise ExtractorError('An extractor error has occurred.', cause=e, video_id=self.get_temp_id(url))
  682. def __maybe_fake_ip_and_retry(self, countries):
  683. if (not self.get_param('geo_bypass_country', None)
  684. and self._GEO_BYPASS
  685. and self.get_param('geo_bypass', True)
  686. and not self._x_forwarded_for_ip
  687. and countries):
  688. country_code = random.choice(countries)
  689. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country_code)
  690. if self._x_forwarded_for_ip:
  691. self.report_warning(
  692. 'Video is geo restricted. Retrying extraction with fake IP %s (%s) as X-Forwarded-For.'
  693. % (self._x_forwarded_for_ip, country_code.upper()))
  694. return True
  695. return False
  696. def set_downloader(self, downloader):
  697. """Sets a YoutubeDL instance as the downloader for this IE."""
  698. self._downloader = downloader
  699. @property
  700. def cache(self):
  701. return self._downloader.cache
  702. @property
  703. def cookiejar(self):
  704. return self._downloader.cookiejar
  705. def _initialize_pre_login(self):
  706. """ Initialization before login. Redefine in subclasses."""
  707. pass
  708. def _perform_login(self, username, password):
  709. """ Login with username and password. Redefine in subclasses."""
  710. pass
  711. def _real_initialize(self):
  712. """Real initialization process. Redefine in subclasses."""
  713. pass
  714. def _real_extract(self, url):
  715. """Real extraction process. Redefine in subclasses."""
  716. raise NotImplementedError('This method must be implemented by subclasses')
  717. @classmethod
  718. def ie_key(cls):
  719. """A string for getting the InfoExtractor with get_info_extractor"""
  720. return cls.__name__[:-2]
  721. @classproperty
  722. def IE_NAME(cls):
  723. return cls.__name__[:-2]
  724. @staticmethod
  725. def __can_accept_status_code(err, expected_status):
  726. assert isinstance(err, HTTPError)
  727. if expected_status is None:
  728. return False
  729. elif callable(expected_status):
  730. return expected_status(err.status) is True
  731. else:
  732. return err.status in variadic(expected_status)
  733. def _create_request(self, url_or_request, data=None, headers=None, query=None, extensions=None):
  734. if isinstance(url_or_request, urllib.request.Request):
  735. self._downloader.deprecation_warning(
  736. 'Passing a urllib.request.Request to _create_request() is deprecated. '
  737. 'Use yt_dlp.networking.common.Request instead.')
  738. url_or_request = urllib_req_to_req(url_or_request)
  739. elif not isinstance(url_or_request, Request):
  740. url_or_request = Request(url_or_request)
  741. url_or_request.update(data=data, headers=headers, query=query, extensions=extensions)
  742. return url_or_request
  743. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None,
  744. headers=None, query=None, expected_status=None, impersonate=None, require_impersonation=False):
  745. """
  746. Return the response handle.
  747. See _download_webpage docstring for arguments specification.
  748. """
  749. if not self._downloader._first_webpage_request:
  750. sleep_interval = self.get_param('sleep_interval_requests') or 0
  751. if sleep_interval > 0:
  752. self.to_screen('Sleeping %s seconds ...' % sleep_interval)
  753. time.sleep(sleep_interval)
  754. else:
  755. self._downloader._first_webpage_request = False
  756. if note is None:
  757. self.report_download_webpage(video_id)
  758. elif note is not False:
  759. if video_id is None:
  760. self.to_screen(str(note))
  761. else:
  762. self.to_screen(f'{video_id}: {note}')
  763. # Some sites check X-Forwarded-For HTTP header in order to figure out
  764. # the origin of the client behind proxy. This allows bypassing geo
  765. # restriction by faking this header's value to IP that belongs to some
  766. # geo unrestricted country. We will do so once we encounter any
  767. # geo restriction error.
  768. if self._x_forwarded_for_ip:
  769. headers = (headers or {}).copy()
  770. headers.setdefault('X-Forwarded-For', self._x_forwarded_for_ip)
  771. extensions = {}
  772. if impersonate in (True, ''):
  773. impersonate = ImpersonateTarget()
  774. requested_targets = [
  775. t if isinstance(t, ImpersonateTarget) else ImpersonateTarget.from_str(t)
  776. for t in variadic(impersonate)
  777. ] if impersonate else []
  778. available_target = next(filter(self._downloader._impersonate_target_available, requested_targets), None)
  779. if available_target:
  780. extensions['impersonate'] = available_target
  781. elif requested_targets:
  782. message = 'The extractor is attempting impersonation, but '
  783. message += (
  784. 'no impersonate target is available' if not str(impersonate)
  785. else f'none of these impersonate targets are available: "{", ".join(map(str, requested_targets))}"')
  786. info_msg = ('see https://github.com/yt-dlp/yt-dlp#impersonation '
  787. 'for information on installing the required dependencies')
  788. if require_impersonation:
  789. raise ExtractorError(f'{message}; {info_msg}', expected=True)
  790. self.report_warning(f'{message}; if you encounter errors, then {info_msg}', only_once=True)
  791. try:
  792. return self._downloader.urlopen(self._create_request(url_or_request, data, headers, query, extensions))
  793. except network_exceptions as err:
  794. if isinstance(err, HTTPError):
  795. if self.__can_accept_status_code(err, expected_status):
  796. return err.response
  797. if errnote is False:
  798. return False
  799. if errnote is None:
  800. errnote = 'Unable to download webpage'
  801. errmsg = f'{errnote}: {error_to_compat_str(err)}'
  802. if fatal:
  803. raise ExtractorError(errmsg, cause=err)
  804. else:
  805. self.report_warning(errmsg)
  806. return False
  807. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True,
  808. encoding=None, data=None, headers={}, query={}, expected_status=None,
  809. impersonate=None, require_impersonation=False):
  810. """
  811. Return a tuple (page content as string, URL handle).
  812. Arguments:
  813. url_or_request -- plain text URL as a string or
  814. a yt_dlp.networking.Request object
  815. video_id -- Video/playlist/item identifier (string)
  816. Keyword arguments:
  817. note -- note printed before downloading (string)
  818. errnote -- note printed in case of an error (string)
  819. fatal -- flag denoting whether error should be considered fatal,
  820. i.e. whether it should cause ExtractionError to be raised,
  821. otherwise a warning will be reported and extraction continued
  822. encoding -- encoding for a page content decoding, guessed automatically
  823. when not explicitly specified
  824. data -- POST data (bytes)
  825. headers -- HTTP headers (dict)
  826. query -- URL query (dict)
  827. expected_status -- allows to accept failed HTTP requests (non 2xx
  828. status code) by explicitly specifying a set of accepted status
  829. codes. Can be any of the following entities:
  830. - an integer type specifying an exact failed status code to
  831. accept
  832. - a list or a tuple of integer types specifying a list of
  833. failed status codes to accept
  834. - a callable accepting an actual failed status code and
  835. returning True if it should be accepted
  836. Note that this argument does not affect success status codes (2xx)
  837. which are always accepted.
  838. impersonate -- the impersonate target. Can be any of the following entities:
  839. - an instance of yt_dlp.networking.impersonate.ImpersonateTarget
  840. - a string in the format of CLIENT[:OS]
  841. - a list or a tuple of CLIENT[:OS] strings or ImpersonateTarget instances
  842. - a boolean value; True means any impersonate target is sufficient
  843. require_impersonation -- flag to toggle whether the request should raise an error
  844. if impersonation is not possible (bool, default: False)
  845. """
  846. # Strip hashes from the URL (#1038)
  847. if isinstance(url_or_request, str):
  848. url_or_request = url_or_request.partition('#')[0]
  849. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal, data=data,
  850. headers=headers, query=query, expected_status=expected_status,
  851. impersonate=impersonate, require_impersonation=require_impersonation)
  852. if urlh is False:
  853. assert not fatal
  854. return False
  855. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal,
  856. encoding=encoding, data=data)
  857. return (content, urlh)
  858. @staticmethod
  859. def _guess_encoding_from_content(content_type, webpage_bytes):
  860. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  861. if m:
  862. encoding = m.group(1)
  863. else:
  864. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  865. webpage_bytes[:1024])
  866. if m:
  867. encoding = m.group(1).decode('ascii')
  868. elif webpage_bytes.startswith(b'\xff\xfe'):
  869. encoding = 'utf-16'
  870. else:
  871. encoding = 'utf-8'
  872. return encoding
  873. def __check_blocked(self, content):
  874. first_block = content[:512]
  875. if ('<title>Access to this site is blocked</title>' in content
  876. and 'Websense' in first_block):
  877. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  878. blocked_iframe = self._html_search_regex(
  879. r'<iframe src="([^"]+)"', content,
  880. 'Websense information URL', default=None)
  881. if blocked_iframe:
  882. msg += ' Visit %s for more details' % blocked_iframe
  883. raise ExtractorError(msg, expected=True)
  884. if '<title>The URL you requested has been blocked</title>' in first_block:
  885. msg = (
  886. 'Access to this webpage has been blocked by Indian censorship. '
  887. 'Use a VPN or proxy server (with --proxy) to route around it.')
  888. block_msg = self._html_search_regex(
  889. r'</h1><p>(.*?)</p>',
  890. content, 'block message', default=None)
  891. if block_msg:
  892. msg += ' (Message: "%s")' % block_msg.replace('\n', ' ')
  893. raise ExtractorError(msg, expected=True)
  894. if ('<title>TTK :: Доступ к ресурсу ограничен</title>' in content
  895. and 'blocklist.rkn.gov.ru' in content):
  896. raise ExtractorError(
  897. 'Access to this webpage has been blocked by decision of the Russian government. '
  898. 'Visit http://blocklist.rkn.gov.ru/ for a block reason.',
  899. expected=True)
  900. def _request_dump_filename(self, url, video_id, data=None):
  901. if data is not None:
  902. data = hashlib.md5(data).hexdigest()
  903. basen = join_nonempty(video_id, data, url, delim='_')
  904. trim_length = self.get_param('trim_file_name') or 240
  905. if len(basen) > trim_length:
  906. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  907. basen = basen[:trim_length - len(h)] + h
  908. filename = sanitize_filename(f'{basen}.dump', restricted=True)
  909. # Working around MAX_PATH limitation on Windows (see
  910. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  911. if compat_os_name == 'nt':
  912. absfilepath = os.path.abspath(filename)
  913. if len(absfilepath) > 259:
  914. filename = fR'\\?\{absfilepath}'
  915. return filename
  916. def __decode_webpage(self, webpage_bytes, encoding, headers):
  917. if not encoding:
  918. encoding = self._guess_encoding_from_content(headers.get('Content-Type', ''), webpage_bytes)
  919. try:
  920. return webpage_bytes.decode(encoding, 'replace')
  921. except LookupError:
  922. return webpage_bytes.decode('utf-8', 'replace')
  923. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True,
  924. prefix=None, encoding=None, data=None):
  925. webpage_bytes = urlh.read()
  926. if prefix is not None:
  927. webpage_bytes = prefix + webpage_bytes
  928. if self.get_param('dump_intermediate_pages', False):
  929. self.to_screen('Dumping request to ' + urlh.url)
  930. dump = base64.b64encode(webpage_bytes).decode('ascii')
  931. self._downloader.to_screen(dump)
  932. if self.get_param('write_pages'):
  933. if isinstance(url_or_request, Request):
  934. data = self._create_request(url_or_request, data).data
  935. filename = self._request_dump_filename(urlh.url, video_id, data)
  936. self.to_screen(f'Saving request to {filename}')
  937. with open(filename, 'wb') as outf:
  938. outf.write(webpage_bytes)
  939. content = self.__decode_webpage(webpage_bytes, encoding, urlh.headers)
  940. self.__check_blocked(content)
  941. return content
  942. def __print_error(self, errnote, fatal, video_id, err):
  943. if fatal:
  944. raise ExtractorError(f'{video_id}: {errnote}', cause=err)
  945. elif errnote:
  946. self.report_warning(f'{video_id}: {errnote}: {err}')
  947. def _parse_xml(self, xml_string, video_id, transform_source=None, fatal=True, errnote=None):
  948. if transform_source:
  949. xml_string = transform_source(xml_string)
  950. try:
  951. return compat_etree_fromstring(xml_string.encode('utf-8'))
  952. except xml.etree.ElementTree.ParseError as ve:
  953. self.__print_error('Failed to parse XML' if errnote is None else errnote, fatal, video_id, ve)
  954. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True, errnote=None, **parser_kwargs):
  955. try:
  956. return json.loads(
  957. json_string, cls=LenientJSONDecoder, strict=False, transform_source=transform_source, **parser_kwargs)
  958. except ValueError as ve:
  959. self.__print_error('Failed to parse JSON' if errnote is None else errnote, fatal, video_id, ve)
  960. def _parse_socket_response_as_json(self, data, *args, **kwargs):
  961. return self._parse_json(data[data.find('{'):data.rfind('}') + 1], *args, **kwargs)
  962. def __create_download_methods(name, parser, note, errnote, return_value):
  963. def parse(ie, content, *args, errnote=errnote, **kwargs):
  964. if parser is None:
  965. return content
  966. if errnote is False:
  967. kwargs['errnote'] = errnote
  968. # parser is fetched by name so subclasses can override it
  969. return getattr(ie, parser)(content, *args, **kwargs)
  970. def download_handle(self, url_or_request, video_id, note=note, errnote=errnote, transform_source=None,
  971. fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None,
  972. impersonate=None, require_impersonation=False):
  973. res = self._download_webpage_handle(
  974. url_or_request, video_id, note=note, errnote=errnote, fatal=fatal, encoding=encoding,
  975. data=data, headers=headers, query=query, expected_status=expected_status,
  976. impersonate=impersonate, require_impersonation=require_impersonation)
  977. if res is False:
  978. return res
  979. content, urlh = res
  980. return parse(self, content, video_id, transform_source=transform_source, fatal=fatal, errnote=errnote), urlh
  981. def download_content(self, url_or_request, video_id, note=note, errnote=errnote, transform_source=None,
  982. fatal=True, encoding=None, data=None, headers={}, query={}, expected_status=None,
  983. impersonate=None, require_impersonation=False):
  984. if self.get_param('load_pages'):
  985. url_or_request = self._create_request(url_or_request, data, headers, query)
  986. filename = self._request_dump_filename(url_or_request.url, video_id, url_or_request.data)
  987. self.to_screen(f'Loading request from {filename}')
  988. try:
  989. with open(filename, 'rb') as dumpf:
  990. webpage_bytes = dumpf.read()
  991. except OSError as e:
  992. self.report_warning(f'Unable to load request from disk: {e}')
  993. else:
  994. content = self.__decode_webpage(webpage_bytes, encoding, url_or_request.headers)
  995. return parse(self, content, video_id, transform_source=transform_source, fatal=fatal, errnote=errnote)
  996. kwargs = {
  997. 'note': note,
  998. 'errnote': errnote,
  999. 'transform_source': transform_source,
  1000. 'fatal': fatal,
  1001. 'encoding': encoding,
  1002. 'data': data,
  1003. 'headers': headers,
  1004. 'query': query,
  1005. 'expected_status': expected_status,
  1006. 'impersonate': impersonate,
  1007. 'require_impersonation': require_impersonation,
  1008. }
  1009. if parser is None:
  1010. kwargs.pop('transform_source')
  1011. # The method is fetched by name so subclasses can override _download_..._handle
  1012. res = getattr(self, download_handle.__name__)(url_or_request, video_id, **kwargs)
  1013. return res if res is False else res[0]
  1014. def impersonate(func, name, return_value):
  1015. func.__name__, func.__qualname__ = name, f'InfoExtractor.{name}'
  1016. func.__doc__ = f'''
  1017. @param transform_source Apply this transformation before parsing
  1018. @returns {return_value}
  1019. See _download_webpage_handle docstring for other arguments specification
  1020. '''
  1021. impersonate(download_handle, f'_download_{name}_handle', f'({return_value}, URL handle)')
  1022. impersonate(download_content, f'_download_{name}', f'{return_value}')
  1023. return download_handle, download_content
  1024. _download_xml_handle, _download_xml = __create_download_methods(
  1025. 'xml', '_parse_xml', 'Downloading XML', 'Unable to download XML', 'xml as an xml.etree.ElementTree.Element')
  1026. _download_json_handle, _download_json = __create_download_methods(
  1027. 'json', '_parse_json', 'Downloading JSON metadata', 'Unable to download JSON metadata', 'JSON object as a dict')
  1028. _download_socket_json_handle, _download_socket_json = __create_download_methods(
  1029. 'socket_json', '_parse_socket_response_as_json', 'Polling socket', 'Unable to poll socket', 'JSON object as a dict')
  1030. __download_webpage = __create_download_methods('webpage', None, None, None, 'data of the page as a string')[1]
  1031. def _download_webpage(
  1032. self, url_or_request, video_id, note=None, errnote=None,
  1033. fatal=True, tries=1, timeout=NO_DEFAULT, *args, **kwargs):
  1034. """
  1035. Return the data of the page as a string.
  1036. Keyword arguments:
  1037. tries -- number of tries
  1038. timeout -- sleep interval between tries
  1039. See _download_webpage_handle docstring for other arguments specification.
  1040. """
  1041. R''' # NB: These are unused; should they be deprecated?
  1042. if tries != 1:
  1043. self._downloader.deprecation_warning('tries argument is deprecated in InfoExtractor._download_webpage')
  1044. if timeout is NO_DEFAULT:
  1045. timeout = 5
  1046. else:
  1047. self._downloader.deprecation_warning('timeout argument is deprecated in InfoExtractor._download_webpage')
  1048. '''
  1049. try_count = 0
  1050. while True:
  1051. try:
  1052. return self.__download_webpage(url_or_request, video_id, note, errnote, None, fatal, *args, **kwargs)
  1053. except IncompleteRead as e:
  1054. try_count += 1
  1055. if try_count >= tries:
  1056. raise e
  1057. self._sleep(timeout, video_id)
  1058. def report_warning(self, msg, video_id=None, *args, only_once=False, **kwargs):
  1059. idstr = format_field(video_id, None, '%s: ')
  1060. msg = f'[{self.IE_NAME}] {idstr}{msg}'
  1061. if only_once:
  1062. if f'WARNING: {msg}' in self._printed_messages:
  1063. return
  1064. self._printed_messages.add(f'WARNING: {msg}')
  1065. self._downloader.report_warning(msg, *args, **kwargs)
  1066. def to_screen(self, msg, *args, **kwargs):
  1067. """Print msg to screen, prefixing it with '[ie_name]'"""
  1068. self._downloader.to_screen(f'[{self.IE_NAME}] {msg}', *args, **kwargs)
  1069. def write_debug(self, msg, *args, **kwargs):
  1070. self._downloader.write_debug(f'[{self.IE_NAME}] {msg}', *args, **kwargs)
  1071. def get_param(self, name, default=None, *args, **kwargs):
  1072. if self._downloader:
  1073. return self._downloader.params.get(name, default, *args, **kwargs)
  1074. return default
  1075. def report_drm(self, video_id, partial=NO_DEFAULT):
  1076. if partial is not NO_DEFAULT:
  1077. self._downloader.deprecation_warning('InfoExtractor.report_drm no longer accepts the argument partial')
  1078. self.raise_no_formats('This video is DRM protected', expected=True, video_id=video_id)
  1079. def report_extraction(self, id_or_name):
  1080. """Report information extraction."""
  1081. self.to_screen('%s: Extracting information' % id_or_name)
  1082. def report_download_webpage(self, video_id):
  1083. """Report webpage download."""
  1084. self.to_screen('%s: Downloading webpage' % video_id)
  1085. def report_age_confirmation(self):
  1086. """Report attempt to confirm age."""
  1087. self.to_screen('Confirming age')
  1088. def report_login(self):
  1089. """Report attempt to log in."""
  1090. self.to_screen('Logging in')
  1091. def raise_login_required(
  1092. self, msg='This video is only available for registered users',
  1093. metadata_available=False, method=NO_DEFAULT):
  1094. if metadata_available and (
  1095. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1096. self.report_warning(msg)
  1097. return
  1098. msg += format_field(self._login_hint(method), None, '. %s')
  1099. raise ExtractorError(msg, expected=True)
  1100. def raise_geo_restricted(
  1101. self, msg='This video is not available from your location due to geo restriction',
  1102. countries=None, metadata_available=False):
  1103. if metadata_available and (
  1104. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1105. self.report_warning(msg)
  1106. else:
  1107. raise GeoRestrictedError(msg, countries=countries)
  1108. def raise_no_formats(self, msg, expected=False, video_id=None):
  1109. if expected and (
  1110. self.get_param('ignore_no_formats_error') or self.get_param('wait_for_video')):
  1111. self.report_warning(msg, video_id)
  1112. elif isinstance(msg, ExtractorError):
  1113. raise msg
  1114. else:
  1115. raise ExtractorError(msg, expected=expected, video_id=video_id)
  1116. # Methods for following #608
  1117. @staticmethod
  1118. def url_result(url, ie=None, video_id=None, video_title=None, *, url_transparent=False, **kwargs):
  1119. """Returns a URL that points to a page that should be processed"""
  1120. if ie is not None:
  1121. kwargs['ie_key'] = ie if isinstance(ie, str) else ie.ie_key()
  1122. if video_id is not None:
  1123. kwargs['id'] = video_id
  1124. if video_title is not None:
  1125. kwargs['title'] = video_title
  1126. return {
  1127. **kwargs,
  1128. '_type': 'url_transparent' if url_transparent else 'url',
  1129. 'url': url,
  1130. }
  1131. @classmethod
  1132. def playlist_from_matches(cls, matches, playlist_id=None, playlist_title=None,
  1133. getter=IDENTITY, ie=None, video_kwargs=None, **kwargs):
  1134. return cls.playlist_result(
  1135. (cls.url_result(m, ie, **(video_kwargs or {})) for m in orderedSet(map(getter, matches), lazy=True)),
  1136. playlist_id, playlist_title, **kwargs)
  1137. @staticmethod
  1138. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None, *, multi_video=False, **kwargs):
  1139. """Returns a playlist"""
  1140. if playlist_id:
  1141. kwargs['id'] = playlist_id
  1142. if playlist_title:
  1143. kwargs['title'] = playlist_title
  1144. if playlist_description is not None:
  1145. kwargs['description'] = playlist_description
  1146. return {
  1147. **kwargs,
  1148. '_type': 'multi_video' if multi_video else 'playlist',
  1149. 'entries': entries,
  1150. }
  1151. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  1152. """
  1153. Perform a regex search on the given string, using a single or a list of
  1154. patterns returning the first matching group.
  1155. In case of failure return a default value or raise a WARNING or a
  1156. RegexNotFoundError, depending on fatal, specifying the field name.
  1157. """
  1158. if string is None:
  1159. mobj = None
  1160. elif isinstance(pattern, (str, re.Pattern)):
  1161. mobj = re.search(pattern, string, flags)
  1162. else:
  1163. for p in pattern:
  1164. mobj = re.search(p, string, flags)
  1165. if mobj:
  1166. break
  1167. _name = self._downloader._format_err(name, self._downloader.Styles.EMPHASIS)
  1168. if mobj:
  1169. if group is None:
  1170. # return the first matching group
  1171. return next(g for g in mobj.groups() if g is not None)
  1172. elif isinstance(group, (list, tuple)):
  1173. return tuple(mobj.group(g) for g in group)
  1174. else:
  1175. return mobj.group(group)
  1176. elif default is not NO_DEFAULT:
  1177. return default
  1178. elif fatal:
  1179. raise RegexNotFoundError('Unable to extract %s' % _name)
  1180. else:
  1181. self.report_warning('unable to extract %s' % _name + bug_reports_message())
  1182. return None
  1183. def _search_json(self, start_pattern, string, name, video_id, *, end_pattern='',
  1184. contains_pattern=r'{(?s:.+)}', fatal=True, default=NO_DEFAULT, **kwargs):
  1185. """Searches string for the JSON object specified by start_pattern"""
  1186. # NB: end_pattern is only used to reduce the size of the initial match
  1187. if default is NO_DEFAULT:
  1188. default, has_default = {}, False
  1189. else:
  1190. fatal, has_default = False, True
  1191. json_string = self._search_regex(
  1192. rf'(?:{start_pattern})\s*(?P<json>{contains_pattern})\s*(?:{end_pattern})',
  1193. string, name, group='json', fatal=fatal, default=None if has_default else NO_DEFAULT)
  1194. if not json_string:
  1195. return default
  1196. _name = self._downloader._format_err(name, self._downloader.Styles.EMPHASIS)
  1197. try:
  1198. return self._parse_json(json_string, video_id, ignore_extra=True, **kwargs)
  1199. except ExtractorError as e:
  1200. if fatal:
  1201. raise ExtractorError(
  1202. f'Unable to extract {_name} - Failed to parse JSON', cause=e.cause, video_id=video_id)
  1203. elif not has_default:
  1204. self.report_warning(
  1205. f'Unable to extract {_name} - Failed to parse JSON: {e}', video_id=video_id)
  1206. return default
  1207. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  1208. """
  1209. Like _search_regex, but strips HTML tags and unescapes entities.
  1210. """
  1211. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  1212. if isinstance(res, tuple):
  1213. return tuple(map(clean_html, res))
  1214. return clean_html(res)
  1215. def _get_netrc_login_info(self, netrc_machine=None):
  1216. netrc_machine = netrc_machine or self._NETRC_MACHINE
  1217. cmd = self.get_param('netrc_cmd')
  1218. if cmd:
  1219. cmd = cmd.replace('{}', netrc_machine)
  1220. self.to_screen(f'Executing command: {cmd}')
  1221. stdout, _, ret = Popen.run(cmd, text=True, shell=True, stdout=subprocess.PIPE)
  1222. if ret != 0:
  1223. raise OSError(f'Command returned error code {ret}')
  1224. info = netrc_from_content(stdout).authenticators(netrc_machine)
  1225. elif self.get_param('usenetrc', False):
  1226. netrc_file = compat_expanduser(self.get_param('netrc_location') or '~')
  1227. if os.path.isdir(netrc_file):
  1228. netrc_file = os.path.join(netrc_file, '.netrc')
  1229. info = netrc.netrc(netrc_file).authenticators(netrc_machine)
  1230. else:
  1231. return None, None
  1232. if not info:
  1233. self.to_screen(f'No authenticators for {netrc_machine}')
  1234. return None, None
  1235. self.write_debug(f'Using netrc for {netrc_machine} authentication')
  1236. return info[0], info[2]
  1237. def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
  1238. """
  1239. Get the login info as (username, password)
  1240. First look for the manually specified credentials using username_option
  1241. and password_option as keys in params dictionary. If no such credentials
  1242. are available try the netrc_cmd if it is defined or look in the
  1243. netrc file using the netrc_machine or _NETRC_MACHINE value.
  1244. If there's no info available, return (None, None)
  1245. """
  1246. username = self.get_param(username_option)
  1247. if username is not None:
  1248. password = self.get_param(password_option)
  1249. else:
  1250. try:
  1251. username, password = self._get_netrc_login_info(netrc_machine)
  1252. except (OSError, netrc.NetrcParseError) as err:
  1253. self.report_warning(f'Failed to parse .netrc: {err}')
  1254. return None, None
  1255. return username, password
  1256. def _get_tfa_info(self, note='two-factor verification code'):
  1257. """
  1258. Get the two-factor authentication info
  1259. TODO - asking the user will be required for sms/phone verify
  1260. currently just uses the command line option
  1261. If there's no info available, return None
  1262. """
  1263. tfa = self.get_param('twofactor')
  1264. if tfa is not None:
  1265. return tfa
  1266. return getpass.getpass('Type %s and press [Return]: ' % note)
  1267. # Helper functions for extracting OpenGraph info
  1268. @staticmethod
  1269. def _og_regexes(prop):
  1270. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?)(?=\s|/?>))'
  1271. property_re = (r'(?:name|property)=(?:\'og%(sep)s%(prop)s\'|"og%(sep)s%(prop)s"|\s*og%(sep)s%(prop)s\b)'
  1272. % {'prop': re.escape(prop), 'sep': '(?:&#x3A;|[:-])'})
  1273. template = r'<meta[^>]+?%s[^>]+?%s'
  1274. return [
  1275. template % (property_re, content_re),
  1276. template % (content_re, property_re),
  1277. ]
  1278. @staticmethod
  1279. def _meta_regex(prop):
  1280. return r'''(?isx)<meta
  1281. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  1282. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  1283. def _og_search_property(self, prop, html, name=None, **kargs):
  1284. prop = variadic(prop)
  1285. if name is None:
  1286. name = 'OpenGraph %s' % prop[0]
  1287. og_regexes = []
  1288. for p in prop:
  1289. og_regexes.extend(self._og_regexes(p))
  1290. escaped = self._search_regex(og_regexes, html, name, flags=re.DOTALL, **kargs)
  1291. if escaped is None:
  1292. return None
  1293. return unescapeHTML(escaped)
  1294. def _og_search_thumbnail(self, html, **kargs):
  1295. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  1296. def _og_search_description(self, html, **kargs):
  1297. return self._og_search_property('description', html, fatal=False, **kargs)
  1298. def _og_search_title(self, html, *, fatal=False, **kargs):
  1299. return self._og_search_property('title', html, fatal=fatal, **kargs)
  1300. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  1301. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  1302. if secure:
  1303. regexes = self._og_regexes('video:secure_url') + regexes
  1304. return self._html_search_regex(regexes, html, name, **kargs)
  1305. def _og_search_url(self, html, **kargs):
  1306. return self._og_search_property('url', html, **kargs)
  1307. def _html_extract_title(self, html, name='title', *, fatal=False, **kwargs):
  1308. return self._html_search_regex(r'(?s)<title\b[^>]*>([^<]+)</title>', html, name, fatal=fatal, **kwargs)
  1309. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  1310. name = variadic(name)
  1311. if display_name is None:
  1312. display_name = name[0]
  1313. return self._html_search_regex(
  1314. [self._meta_regex(n) for n in name],
  1315. html, display_name, fatal=fatal, group='content', **kwargs)
  1316. def _dc_search_uploader(self, html):
  1317. return self._html_search_meta('dc.creator', html, 'uploader')
  1318. @staticmethod
  1319. def _rta_search(html):
  1320. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  1321. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  1322. r' content="RTA-5042-1996-1400-1577-RTA"',
  1323. html):
  1324. return 18
  1325. # And then there are the jokers who advertise that they use RTA, but actually don't.
  1326. AGE_LIMIT_MARKERS = [
  1327. r'Proudly Labeled <a href="http://www\.rtalabel\.org/" title="Restricted to Adults">RTA</a>',
  1328. r'>[^<]*you acknowledge you are at least (\d+) years old',
  1329. r'>\s*(?:18\s+U(?:\.S\.C\.|SC)\s+)?(?:§+\s*)?2257\b',
  1330. ]
  1331. age_limit = 0
  1332. for marker in AGE_LIMIT_MARKERS:
  1333. mobj = re.search(marker, html)
  1334. if mobj:
  1335. age_limit = max(age_limit, int(traverse_obj(mobj, 1, default=18)))
  1336. return age_limit
  1337. def _media_rating_search(self, html):
  1338. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  1339. rating = self._html_search_meta('rating', html)
  1340. if not rating:
  1341. return None
  1342. RATING_TABLE = {
  1343. 'safe for kids': 0,
  1344. 'general': 8,
  1345. '14 years': 14,
  1346. 'mature': 17,
  1347. 'restricted': 19,
  1348. }
  1349. return RATING_TABLE.get(rating.lower())
  1350. def _family_friendly_search(self, html):
  1351. # See http://schema.org/VideoObject
  1352. family_friendly = self._html_search_meta(
  1353. 'isFamilyFriendly', html, default=None)
  1354. if not family_friendly:
  1355. return None
  1356. RATING_TABLE = {
  1357. '1': 0,
  1358. 'true': 0,
  1359. '0': 18,
  1360. 'false': 18,
  1361. }
  1362. return RATING_TABLE.get(family_friendly.lower())
  1363. def _twitter_search_player(self, html):
  1364. return self._html_search_meta('twitter:player', html,
  1365. 'twitter card player')
  1366. def _yield_json_ld(self, html, video_id, *, fatal=True, default=NO_DEFAULT):
  1367. """Yield all json ld objects in the html"""
  1368. if default is not NO_DEFAULT:
  1369. fatal = False
  1370. for mobj in re.finditer(JSON_LD_RE, html):
  1371. json_ld_item = self._parse_json(mobj.group('json_ld'), video_id, fatal=fatal)
  1372. for json_ld in variadic(json_ld_item):
  1373. if isinstance(json_ld, dict):
  1374. yield json_ld
  1375. def _search_json_ld(self, html, video_id, expected_type=None, *, fatal=True, default=NO_DEFAULT):
  1376. """Search for a video in any json ld in the html"""
  1377. if default is not NO_DEFAULT:
  1378. fatal = False
  1379. info = self._json_ld(
  1380. list(self._yield_json_ld(html, video_id, fatal=fatal, default=default)),
  1381. video_id, fatal=fatal, expected_type=expected_type)
  1382. if info:
  1383. return info
  1384. if default is not NO_DEFAULT:
  1385. return default
  1386. elif fatal:
  1387. raise RegexNotFoundError('Unable to extract JSON-LD')
  1388. else:
  1389. self.report_warning('unable to extract JSON-LD %s' % bug_reports_message())
  1390. return {}
  1391. def _json_ld(self, json_ld, video_id, fatal=True, expected_type=None):
  1392. if isinstance(json_ld, str):
  1393. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  1394. if not json_ld:
  1395. return {}
  1396. info = {}
  1397. INTERACTION_TYPE_MAP = {
  1398. 'CommentAction': 'comment',
  1399. 'AgreeAction': 'like',
  1400. 'DisagreeAction': 'dislike',
  1401. 'LikeAction': 'like',
  1402. 'DislikeAction': 'dislike',
  1403. 'ListenAction': 'view',
  1404. 'WatchAction': 'view',
  1405. 'ViewAction': 'view',
  1406. }
  1407. def is_type(e, *expected_types):
  1408. type = variadic(traverse_obj(e, '@type'))
  1409. return any(x in type for x in expected_types)
  1410. def extract_interaction_type(e):
  1411. interaction_type = e.get('interactionType')
  1412. if isinstance(interaction_type, dict):
  1413. interaction_type = interaction_type.get('@type')
  1414. return str_or_none(interaction_type)
  1415. def extract_interaction_statistic(e):
  1416. interaction_statistic = e.get('interactionStatistic')
  1417. if isinstance(interaction_statistic, dict):
  1418. interaction_statistic = [interaction_statistic]
  1419. if not isinstance(interaction_statistic, list):
  1420. return
  1421. for is_e in interaction_statistic:
  1422. if not is_type(is_e, 'InteractionCounter'):
  1423. continue
  1424. interaction_type = extract_interaction_type(is_e)
  1425. if not interaction_type:
  1426. continue
  1427. # For interaction count some sites provide string instead of
  1428. # an integer (as per spec) with non digit characters (e.g. ",")
  1429. # so extracting count with more relaxed str_to_int
  1430. interaction_count = str_to_int(is_e.get('userInteractionCount'))
  1431. if interaction_count is None:
  1432. continue
  1433. count_kind = INTERACTION_TYPE_MAP.get(interaction_type.split('/')[-1])
  1434. if not count_kind:
  1435. continue
  1436. count_key = '%s_count' % count_kind
  1437. if info.get(count_key) is not None:
  1438. continue
  1439. info[count_key] = interaction_count
  1440. def extract_chapter_information(e):
  1441. chapters = [{
  1442. 'title': part.get('name'),
  1443. 'start_time': part.get('startOffset'),
  1444. 'end_time': part.get('endOffset'),
  1445. } for part in variadic(e.get('hasPart') or []) if part.get('@type') == 'Clip']
  1446. for idx, (last_c, current_c, next_c) in enumerate(zip(
  1447. [{'end_time': 0}] + chapters, chapters, chapters[1:])):
  1448. current_c['end_time'] = current_c['end_time'] or next_c['start_time']
  1449. current_c['start_time'] = current_c['start_time'] or last_c['end_time']
  1450. if None in current_c.values():
  1451. self.report_warning(f'Chapter {idx} contains broken data. Not extracting chapters')
  1452. return
  1453. if chapters:
  1454. chapters[-1]['end_time'] = chapters[-1]['end_time'] or info['duration']
  1455. info['chapters'] = chapters
  1456. def extract_video_object(e):
  1457. author = e.get('author')
  1458. info.update({
  1459. 'url': url_or_none(e.get('contentUrl')),
  1460. 'ext': mimetype2ext(e.get('encodingFormat')),
  1461. 'title': unescapeHTML(e.get('name')),
  1462. 'description': unescapeHTML(e.get('description')),
  1463. 'thumbnails': [{'url': unescapeHTML(url)}
  1464. for url in variadic(traverse_obj(e, 'thumbnailUrl', 'thumbnailURL'))
  1465. if url_or_none(url)],
  1466. 'duration': parse_duration(e.get('duration')),
  1467. 'timestamp': unified_timestamp(e.get('uploadDate')),
  1468. # author can be an instance of 'Organization' or 'Person' types.
  1469. # both types can have 'name' property(inherited from 'Thing' type). [1]
  1470. # however some websites are using 'Text' type instead.
  1471. # 1. https://schema.org/VideoObject
  1472. 'uploader': author.get('name') if isinstance(author, dict) else author if isinstance(author, str) else None,
  1473. 'artist': traverse_obj(e, ('byArtist', 'name'), expected_type=str),
  1474. 'filesize': int_or_none(float_or_none(e.get('contentSize'))),
  1475. 'tbr': int_or_none(e.get('bitrate')),
  1476. 'width': int_or_none(e.get('width')),
  1477. 'height': int_or_none(e.get('height')),
  1478. 'view_count': int_or_none(e.get('interactionCount')),
  1479. 'tags': try_call(lambda: e.get('keywords').split(',')),
  1480. })
  1481. if is_type(e, 'AudioObject'):
  1482. info.update({
  1483. 'vcodec': 'none',
  1484. 'abr': int_or_none(e.get('bitrate')),
  1485. })
  1486. extract_interaction_statistic(e)
  1487. extract_chapter_information(e)
  1488. def traverse_json_ld(json_ld, at_top_level=True):
  1489. for e in variadic(json_ld):
  1490. if not isinstance(e, dict):
  1491. continue
  1492. if at_top_level and '@context' not in e:
  1493. continue
  1494. if at_top_level and set(e.keys()) == {'@context', '@graph'}:
  1495. traverse_json_ld(e['@graph'], at_top_level=False)
  1496. continue
  1497. if expected_type is not None and not is_type(e, expected_type):
  1498. continue
  1499. rating = traverse_obj(e, ('aggregateRating', 'ratingValue'), expected_type=float_or_none)
  1500. if rating is not None:
  1501. info['average_rating'] = rating
  1502. if is_type(e, 'TVEpisode', 'Episode'):
  1503. episode_name = unescapeHTML(e.get('name'))
  1504. info.update({
  1505. 'episode': episode_name,
  1506. 'episode_number': int_or_none(e.get('episodeNumber')),
  1507. 'description': unescapeHTML(e.get('description')),
  1508. })
  1509. if not info.get('title') and episode_name:
  1510. info['title'] = episode_name
  1511. part_of_season = e.get('partOfSeason')
  1512. if is_type(part_of_season, 'TVSeason', 'Season', 'CreativeWorkSeason'):
  1513. info.update({
  1514. 'season': unescapeHTML(part_of_season.get('name')),
  1515. 'season_number': int_or_none(part_of_season.get('seasonNumber')),
  1516. })
  1517. part_of_series = e.get('partOfSeries') or e.get('partOfTVSeries')
  1518. if is_type(part_of_series, 'TVSeries', 'Series', 'CreativeWorkSeries'):
  1519. info['series'] = unescapeHTML(part_of_series.get('name'))
  1520. elif is_type(e, 'Movie'):
  1521. info.update({
  1522. 'title': unescapeHTML(e.get('name')),
  1523. 'description': unescapeHTML(e.get('description')),
  1524. 'duration': parse_duration(e.get('duration')),
  1525. 'timestamp': unified_timestamp(e.get('dateCreated')),
  1526. })
  1527. elif is_type(e, 'Article', 'NewsArticle'):
  1528. info.update({
  1529. 'timestamp': parse_iso8601(e.get('datePublished')),
  1530. 'title': unescapeHTML(e.get('headline')),
  1531. 'description': unescapeHTML(e.get('articleBody') or e.get('description')),
  1532. })
  1533. if is_type(traverse_obj(e, ('video', 0)), 'VideoObject'):
  1534. extract_video_object(e['video'][0])
  1535. elif is_type(traverse_obj(e, ('subjectOf', 0)), 'VideoObject'):
  1536. extract_video_object(e['subjectOf'][0])
  1537. elif is_type(e, 'VideoObject', 'AudioObject'):
  1538. extract_video_object(e)
  1539. if expected_type is None:
  1540. continue
  1541. else:
  1542. break
  1543. video = e.get('video')
  1544. if is_type(video, 'VideoObject'):
  1545. extract_video_object(video)
  1546. if expected_type is None:
  1547. continue
  1548. else:
  1549. break
  1550. traverse_json_ld(json_ld)
  1551. return filter_dict(info)
  1552. def _search_nextjs_data(self, webpage, video_id, *, fatal=True, default=NO_DEFAULT, **kw):
  1553. if default == '{}':
  1554. self._downloader.deprecation_warning('using `default=\'{}\'` is deprecated, use `default={}` instead')
  1555. default = {}
  1556. if default is not NO_DEFAULT:
  1557. fatal = False
  1558. return self._search_json(
  1559. r'<script[^>]+id=[\'"]__NEXT_DATA__[\'"][^>]*>', webpage, 'next.js data',
  1560. video_id, end_pattern='</script>', fatal=fatal, default=default, **kw)
  1561. def _search_nuxt_data(self, webpage, video_id, context_name='__NUXT__', *, fatal=True, traverse=('data', 0)):
  1562. """Parses Nuxt.js metadata. This works as long as the function __NUXT__ invokes is a pure function"""
  1563. rectx = re.escape(context_name)
  1564. FUNCTION_RE = r'\(function\((?P<arg_keys>.*?)\){.*?\breturn\s+(?P<js>{.*?})\s*;?\s*}\((?P<arg_vals>.*?)\)'
  1565. js, arg_keys, arg_vals = self._search_regex(
  1566. (rf'<script>\s*window\.{rectx}={FUNCTION_RE}\s*\)\s*;?\s*</script>', rf'{rectx}\(.*?{FUNCTION_RE}'),
  1567. webpage, context_name, group=('js', 'arg_keys', 'arg_vals'),
  1568. default=NO_DEFAULT if fatal else (None, None, None))
  1569. if js is None:
  1570. return {}
  1571. args = dict(zip(arg_keys.split(','), map(json.dumps, self._parse_json(
  1572. f'[{arg_vals}]', video_id, transform_source=js_to_json, fatal=fatal) or ())))
  1573. ret = self._parse_json(js, video_id, transform_source=functools.partial(js_to_json, vars=args), fatal=fatal)
  1574. return traverse_obj(ret, traverse) or {}
  1575. @staticmethod
  1576. def _hidden_inputs(html):
  1577. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  1578. hidden_inputs = {}
  1579. for input in re.findall(r'(?i)(<input[^>]+>)', html):
  1580. attrs = extract_attributes(input)
  1581. if not input:
  1582. continue
  1583. if attrs.get('type') not in ('hidden', 'submit'):
  1584. continue
  1585. name = attrs.get('name') or attrs.get('id')
  1586. value = attrs.get('value')
  1587. if name and value is not None:
  1588. hidden_inputs[name] = value
  1589. return hidden_inputs
  1590. def _form_hidden_inputs(self, form_id, html):
  1591. form = self._search_regex(
  1592. r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  1593. html, '%s form' % form_id, group='form')
  1594. return self._hidden_inputs(form)
  1595. @classproperty(cache=True)
  1596. def FormatSort(cls):
  1597. class FormatSort(FormatSorter):
  1598. def __init__(ie, *args, **kwargs):
  1599. super().__init__(ie._downloader, *args, **kwargs)
  1600. deprecation_warning(
  1601. 'yt_dlp.InfoExtractor.FormatSort is deprecated and may be removed in the future. '
  1602. 'Use yt_dlp.utils.FormatSorter instead')
  1603. return FormatSort
  1604. def _sort_formats(self, formats, field_preference=[]):
  1605. if not field_preference:
  1606. self._downloader.deprecation_warning(
  1607. 'yt_dlp.InfoExtractor._sort_formats is deprecated and is no longer required')
  1608. return
  1609. self._downloader.deprecation_warning(
  1610. 'yt_dlp.InfoExtractor._sort_formats is deprecated and no longer works as expected. '
  1611. 'Return _format_sort_fields in the info_dict instead')
  1612. if formats:
  1613. formats[0]['__sort_fields'] = field_preference
  1614. def _check_formats(self, formats, video_id):
  1615. if formats:
  1616. formats[:] = filter(
  1617. lambda f: self._is_valid_url(
  1618. f['url'], video_id,
  1619. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  1620. formats)
  1621. @staticmethod
  1622. def _remove_duplicate_formats(formats):
  1623. format_urls = set()
  1624. unique_formats = []
  1625. for f in formats:
  1626. if f['url'] not in format_urls:
  1627. format_urls.add(f['url'])
  1628. unique_formats.append(f)
  1629. formats[:] = unique_formats
  1630. def _is_valid_url(self, url, video_id, item='video', headers={}):
  1631. url = self._proto_relative_url(url, scheme='http:')
  1632. # For now assume non HTTP(S) URLs always valid
  1633. if not (url.startswith('http://') or url.startswith('https://')):
  1634. return True
  1635. try:
  1636. self._request_webpage(url, video_id, 'Checking %s URL' % item, headers=headers)
  1637. return True
  1638. except ExtractorError as e:
  1639. self.to_screen(
  1640. '%s: %s URL is invalid, skipping: %s'
  1641. % (video_id, item, error_to_compat_str(e.cause)))
  1642. return False
  1643. def http_scheme(self):
  1644. """ Either "http:" or "https:", depending on the user's preferences """
  1645. return (
  1646. 'http:'
  1647. if self.get_param('prefer_insecure', False)
  1648. else 'https:')
  1649. def _proto_relative_url(self, url, scheme=None):
  1650. scheme = scheme or self.http_scheme()
  1651. assert scheme.endswith(':')
  1652. return sanitize_url(url, scheme=scheme[:-1])
  1653. def _sleep(self, timeout, video_id, msg_template=None):
  1654. if msg_template is None:
  1655. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  1656. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  1657. self.to_screen(msg)
  1658. time.sleep(timeout)
  1659. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, quality=None, f4m_id=None,
  1660. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1661. fatal=True, m3u8_id=None, data=None, headers={}, query={}):
  1662. if self.get_param('ignore_no_formats_error'):
  1663. fatal = False
  1664. res = self._download_xml_handle(
  1665. manifest_url, video_id, 'Downloading f4m manifest',
  1666. 'Unable to download f4m manifest',
  1667. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  1668. # (see https://github.com/ytdl-org/youtube-dl/issues/6215#issuecomment-121704244)
  1669. transform_source=transform_source,
  1670. fatal=fatal, data=data, headers=headers, query=query)
  1671. if res is False:
  1672. return []
  1673. manifest, urlh = res
  1674. manifest_url = urlh.url
  1675. return self._parse_f4m_formats(
  1676. manifest, manifest_url, video_id, preference=preference, quality=quality, f4m_id=f4m_id,
  1677. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  1678. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, quality=None, f4m_id=None,
  1679. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1680. fatal=True, m3u8_id=None):
  1681. if not isinstance(manifest, xml.etree.ElementTree.Element) and not fatal:
  1682. return []
  1683. # currently yt-dlp cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  1684. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  1685. if akamai_pv is not None and ';' in akamai_pv.text:
  1686. playerVerificationChallenge = akamai_pv.text.split(';')[0]
  1687. if playerVerificationChallenge.strip() != '':
  1688. return []
  1689. formats = []
  1690. manifest_version = '1.0'
  1691. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  1692. if not media_nodes:
  1693. manifest_version = '2.0'
  1694. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  1695. # Remove unsupported DRM protected media from final formats
  1696. # rendition (see https://github.com/ytdl-org/youtube-dl/issues/8573).
  1697. media_nodes = remove_encrypted_media(media_nodes)
  1698. if not media_nodes:
  1699. return formats
  1700. manifest_base_url = get_base_url(manifest)
  1701. bootstrap_info = xpath_element(
  1702. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  1703. 'bootstrap info', default=None)
  1704. vcodec = None
  1705. mime_type = xpath_text(
  1706. manifest, ['{http://ns.adobe.com/f4m/1.0}mimeType', '{http://ns.adobe.com/f4m/2.0}mimeType'],
  1707. 'base URL', default=None)
  1708. if mime_type and mime_type.startswith('audio/'):
  1709. vcodec = 'none'
  1710. for i, media_el in enumerate(media_nodes):
  1711. tbr = int_or_none(media_el.attrib.get('bitrate'))
  1712. width = int_or_none(media_el.attrib.get('width'))
  1713. height = int_or_none(media_el.attrib.get('height'))
  1714. format_id = join_nonempty(f4m_id, tbr or i)
  1715. # If <bootstrapInfo> is present, the specified f4m is a
  1716. # stream-level manifest, and only set-level manifests may refer to
  1717. # external resources. See section 11.4 and section 4 of F4M spec
  1718. if bootstrap_info is None:
  1719. media_url = None
  1720. # @href is introduced in 2.0, see section 11.6 of F4M spec
  1721. if manifest_version == '2.0':
  1722. media_url = media_el.attrib.get('href')
  1723. if media_url is None:
  1724. media_url = media_el.attrib.get('url')
  1725. if not media_url:
  1726. continue
  1727. manifest_url = (
  1728. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  1729. else ((manifest_base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  1730. # If media_url is itself a f4m manifest do the recursive extraction
  1731. # since bitrates in parent manifest (this one) and media_url manifest
  1732. # may differ leading to inability to resolve the format by requested
  1733. # bitrate in f4m downloader
  1734. ext = determine_ext(manifest_url)
  1735. if ext == 'f4m':
  1736. f4m_formats = self._extract_f4m_formats(
  1737. manifest_url, video_id, preference=preference, quality=quality, f4m_id=f4m_id,
  1738. transform_source=transform_source, fatal=fatal)
  1739. # Sometimes stream-level manifest contains single media entry that
  1740. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  1741. # At the same time parent's media entry in set-level manifest may
  1742. # contain it. We will copy it from parent in such cases.
  1743. if len(f4m_formats) == 1:
  1744. f = f4m_formats[0]
  1745. f.update({
  1746. 'tbr': f.get('tbr') or tbr,
  1747. 'width': f.get('width') or width,
  1748. 'height': f.get('height') or height,
  1749. 'format_id': f.get('format_id') if not tbr else format_id,
  1750. 'vcodec': vcodec,
  1751. })
  1752. formats.extend(f4m_formats)
  1753. continue
  1754. elif ext == 'm3u8':
  1755. formats.extend(self._extract_m3u8_formats(
  1756. manifest_url, video_id, 'mp4', preference=preference,
  1757. quality=quality, m3u8_id=m3u8_id, fatal=fatal))
  1758. continue
  1759. formats.append({
  1760. 'format_id': format_id,
  1761. 'url': manifest_url,
  1762. 'manifest_url': manifest_url,
  1763. 'ext': 'flv' if bootstrap_info is not None else None,
  1764. 'protocol': 'f4m',
  1765. 'tbr': tbr,
  1766. 'width': width,
  1767. 'height': height,
  1768. 'vcodec': vcodec,
  1769. 'preference': preference,
  1770. 'quality': quality,
  1771. })
  1772. return formats
  1773. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, quality=None, m3u8_id=None):
  1774. return {
  1775. 'format_id': join_nonempty(m3u8_id, 'meta'),
  1776. 'url': m3u8_url,
  1777. 'ext': ext,
  1778. 'protocol': 'm3u8',
  1779. 'preference': preference - 100 if preference else -100,
  1780. 'quality': quality,
  1781. 'resolution': 'multiple',
  1782. 'format_note': 'Quality selection URL',
  1783. }
  1784. def _report_ignoring_subs(self, name):
  1785. self.report_warning(bug_reports_message(
  1786. f'Ignoring subtitle tracks found in the {name} manifest; '
  1787. 'if any subtitle tracks are missing,'
  1788. ), only_once=True)
  1789. def _extract_m3u8_formats(self, *args, **kwargs):
  1790. fmts, subs = self._extract_m3u8_formats_and_subtitles(*args, **kwargs)
  1791. if subs:
  1792. self._report_ignoring_subs('HLS')
  1793. return fmts
  1794. def _extract_m3u8_formats_and_subtitles(
  1795. self, m3u8_url, video_id, ext=None, entry_protocol='m3u8_native',
  1796. preference=None, quality=None, m3u8_id=None, note=None,
  1797. errnote=None, fatal=True, live=False, data=None, headers={},
  1798. query={}):
  1799. if self.get_param('ignore_no_formats_error'):
  1800. fatal = False
  1801. if not m3u8_url:
  1802. if errnote is not False:
  1803. errnote = errnote or 'Failed to obtain m3u8 URL'
  1804. if fatal:
  1805. raise ExtractorError(errnote, video_id=video_id)
  1806. self.report_warning(f'{errnote}{bug_reports_message()}')
  1807. return [], {}
  1808. res = self._download_webpage_handle(
  1809. m3u8_url, video_id,
  1810. note='Downloading m3u8 information' if note is None else note,
  1811. errnote='Failed to download m3u8 information' if errnote is None else errnote,
  1812. fatal=fatal, data=data, headers=headers, query=query)
  1813. if res is False:
  1814. return [], {}
  1815. m3u8_doc, urlh = res
  1816. m3u8_url = urlh.url
  1817. return self._parse_m3u8_formats_and_subtitles(
  1818. m3u8_doc, m3u8_url, ext=ext, entry_protocol=entry_protocol,
  1819. preference=preference, quality=quality, m3u8_id=m3u8_id,
  1820. note=note, errnote=errnote, fatal=fatal, live=live, data=data,
  1821. headers=headers, query=query, video_id=video_id)
  1822. def _parse_m3u8_formats_and_subtitles(
  1823. self, m3u8_doc, m3u8_url=None, ext=None, entry_protocol='m3u8_native',
  1824. preference=None, quality=None, m3u8_id=None, live=False, note=None,
  1825. errnote=None, fatal=True, data=None, headers={}, query={},
  1826. video_id=None):
  1827. formats, subtitles = [], {}
  1828. has_drm = HlsFD._has_drm(m3u8_doc)
  1829. def format_url(url):
  1830. return url if re.match(r'^https?://', url) else urllib.parse.urljoin(m3u8_url, url)
  1831. if self.get_param('hls_split_discontinuity', False):
  1832. def _extract_m3u8_playlist_indices(manifest_url=None, m3u8_doc=None):
  1833. if not m3u8_doc:
  1834. if not manifest_url:
  1835. return []
  1836. m3u8_doc = self._download_webpage(
  1837. manifest_url, video_id, fatal=fatal, data=data, headers=headers,
  1838. note=False, errnote='Failed to download m3u8 playlist information')
  1839. if m3u8_doc is False:
  1840. return []
  1841. return range(1 + sum(line.startswith('#EXT-X-DISCONTINUITY') for line in m3u8_doc.splitlines()))
  1842. else:
  1843. def _extract_m3u8_playlist_indices(*args, **kwargs):
  1844. return [None]
  1845. # References:
  1846. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-21
  1847. # 2. https://github.com/ytdl-org/youtube-dl/issues/12211
  1848. # 3. https://github.com/ytdl-org/youtube-dl/issues/18923
  1849. # We should try extracting formats only from master playlists [1, 4.3.4],
  1850. # i.e. playlists that describe available qualities. On the other hand
  1851. # media playlists [1, 4.3.3] should be returned as is since they contain
  1852. # just the media without qualities renditions.
  1853. # Fortunately, master playlist can be easily distinguished from media
  1854. # playlist based on particular tags availability. As of [1, 4.3.3, 4.3.4]
  1855. # master playlist tags MUST NOT appear in a media playlist and vice versa.
  1856. # As of [1, 4.3.3.1] #EXT-X-TARGETDURATION tag is REQUIRED for every
  1857. # media playlist and MUST NOT appear in master playlist thus we can
  1858. # clearly detect media playlist with this criterion.
  1859. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1860. formats = [{
  1861. 'format_id': join_nonempty(m3u8_id, idx),
  1862. 'format_index': idx,
  1863. 'url': m3u8_url or encode_data_uri(m3u8_doc.encode('utf-8'), 'application/x-mpegurl'),
  1864. 'ext': ext,
  1865. 'protocol': entry_protocol,
  1866. 'preference': preference,
  1867. 'quality': quality,
  1868. 'has_drm': has_drm,
  1869. } for idx in _extract_m3u8_playlist_indices(m3u8_doc=m3u8_doc)]
  1870. return formats, subtitles
  1871. groups = {}
  1872. last_stream_inf = {}
  1873. def extract_media(x_media_line):
  1874. media = parse_m3u8_attributes(x_media_line)
  1875. # As per [1, 4.3.4.1] TYPE, GROUP-ID and NAME are REQUIRED
  1876. media_type, group_id, name = media.get('TYPE'), media.get('GROUP-ID'), media.get('NAME')
  1877. if not (media_type and group_id and name):
  1878. return
  1879. groups.setdefault(group_id, []).append(media)
  1880. # <https://tools.ietf.org/html/rfc8216#section-4.3.4.1>
  1881. if media_type == 'SUBTITLES':
  1882. # According to RFC 8216 §4.3.4.2.1, URI is REQUIRED in the
  1883. # EXT-X-MEDIA tag if the media type is SUBTITLES.
  1884. # However, lack of URI has been spotted in the wild.
  1885. # e.g. NebulaIE; see https://github.com/yt-dlp/yt-dlp/issues/339
  1886. if not media.get('URI'):
  1887. return
  1888. url = format_url(media['URI'])
  1889. sub_info = {
  1890. 'url': url,
  1891. 'ext': determine_ext(url),
  1892. }
  1893. if sub_info['ext'] == 'm3u8':
  1894. # Per RFC 8216 §3.1, the only possible subtitle format m3u8
  1895. # files may contain is WebVTT:
  1896. # <https://tools.ietf.org/html/rfc8216#section-3.1>
  1897. sub_info['ext'] = 'vtt'
  1898. sub_info['protocol'] = 'm3u8_native'
  1899. lang = media.get('LANGUAGE') or 'und'
  1900. subtitles.setdefault(lang, []).append(sub_info)
  1901. if media_type not in ('VIDEO', 'AUDIO'):
  1902. return
  1903. media_url = media.get('URI')
  1904. if media_url:
  1905. manifest_url = format_url(media_url)
  1906. formats.extend({
  1907. 'format_id': join_nonempty(m3u8_id, group_id, name, idx),
  1908. 'format_note': name,
  1909. 'format_index': idx,
  1910. 'url': manifest_url,
  1911. 'manifest_url': m3u8_url,
  1912. 'language': media.get('LANGUAGE'),
  1913. 'ext': ext,
  1914. 'protocol': entry_protocol,
  1915. 'preference': preference,
  1916. 'quality': quality,
  1917. 'has_drm': has_drm,
  1918. 'vcodec': 'none' if media_type == 'AUDIO' else None,
  1919. } for idx in _extract_m3u8_playlist_indices(manifest_url))
  1920. def build_stream_name():
  1921. # Despite specification does not mention NAME attribute for
  1922. # EXT-X-STREAM-INF tag it still sometimes may be present (see [1]
  1923. # or vidio test in TestInfoExtractor.test_parse_m3u8_formats)
  1924. # 1. http://www.vidio.com/watch/165683-dj_ambred-booyah-live-2015
  1925. stream_name = last_stream_inf.get('NAME')
  1926. if stream_name:
  1927. return stream_name
  1928. # If there is no NAME in EXT-X-STREAM-INF it will be obtained
  1929. # from corresponding rendition group
  1930. stream_group_id = last_stream_inf.get('VIDEO')
  1931. if not stream_group_id:
  1932. return
  1933. stream_group = groups.get(stream_group_id)
  1934. if not stream_group:
  1935. return stream_group_id
  1936. rendition = stream_group[0]
  1937. return rendition.get('NAME') or stream_group_id
  1938. # parse EXT-X-MEDIA tags before EXT-X-STREAM-INF in order to have the
  1939. # chance to detect video only formats when EXT-X-STREAM-INF tags
  1940. # precede EXT-X-MEDIA tags in HLS manifest such as [3].
  1941. for line in m3u8_doc.splitlines():
  1942. if line.startswith('#EXT-X-MEDIA:'):
  1943. extract_media(line)
  1944. for line in m3u8_doc.splitlines():
  1945. if line.startswith('#EXT-X-STREAM-INF:'):
  1946. last_stream_inf = parse_m3u8_attributes(line)
  1947. elif line.startswith('#') or not line.strip():
  1948. continue
  1949. else:
  1950. tbr = float_or_none(
  1951. last_stream_inf.get('AVERAGE-BANDWIDTH')
  1952. or last_stream_inf.get('BANDWIDTH'), scale=1000)
  1953. manifest_url = format_url(line.strip())
  1954. for idx in _extract_m3u8_playlist_indices(manifest_url):
  1955. format_id = [m3u8_id, None, idx]
  1956. # Bandwidth of live streams may differ over time thus making
  1957. # format_id unpredictable. So it's better to keep provided
  1958. # format_id intact.
  1959. if not live:
  1960. stream_name = build_stream_name()
  1961. format_id[1] = stream_name or '%d' % (tbr or len(formats))
  1962. f = {
  1963. 'format_id': join_nonempty(*format_id),
  1964. 'format_index': idx,
  1965. 'url': manifest_url,
  1966. 'manifest_url': m3u8_url,
  1967. 'tbr': tbr,
  1968. 'ext': ext,
  1969. 'fps': float_or_none(last_stream_inf.get('FRAME-RATE')),
  1970. 'protocol': entry_protocol,
  1971. 'preference': preference,
  1972. 'quality': quality,
  1973. 'has_drm': has_drm,
  1974. }
  1975. resolution = last_stream_inf.get('RESOLUTION')
  1976. if resolution:
  1977. mobj = re.search(r'(?P<width>\d+)[xX](?P<height>\d+)', resolution)
  1978. if mobj:
  1979. f['width'] = int(mobj.group('width'))
  1980. f['height'] = int(mobj.group('height'))
  1981. # Unified Streaming Platform
  1982. mobj = re.search(
  1983. r'audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?', f['url'])
  1984. if mobj:
  1985. abr, vbr = mobj.groups()
  1986. abr, vbr = float_or_none(abr, 1000), float_or_none(vbr, 1000)
  1987. f.update({
  1988. 'vbr': vbr,
  1989. 'abr': abr,
  1990. })
  1991. codecs = parse_codecs(last_stream_inf.get('CODECS'))
  1992. f.update(codecs)
  1993. audio_group_id = last_stream_inf.get('AUDIO')
  1994. # As per [1, 4.3.4.1.1] any EXT-X-STREAM-INF tag which
  1995. # references a rendition group MUST have a CODECS attribute.
  1996. # However, this is not always respected. E.g. [2]
  1997. # contains EXT-X-STREAM-INF tag which references AUDIO
  1998. # rendition group but does not have CODECS and despite
  1999. # referencing an audio group it represents a complete
  2000. # (with audio and video) format. So, for such cases we will
  2001. # ignore references to rendition groups and treat them
  2002. # as complete formats.
  2003. if audio_group_id and codecs and f.get('vcodec') != 'none':
  2004. audio_group = groups.get(audio_group_id)
  2005. if audio_group and audio_group[0].get('URI'):
  2006. # TODO: update acodec for audio only formats with
  2007. # the same GROUP-ID
  2008. f['acodec'] = 'none'
  2009. if not f.get('ext'):
  2010. f['ext'] = 'm4a' if f.get('vcodec') == 'none' else 'mp4'
  2011. formats.append(f)
  2012. # for DailyMotion
  2013. progressive_uri = last_stream_inf.get('PROGRESSIVE-URI')
  2014. if progressive_uri:
  2015. http_f = f.copy()
  2016. del http_f['manifest_url']
  2017. http_f.update({
  2018. 'format_id': f['format_id'].replace('hls-', 'http-'),
  2019. 'protocol': 'http',
  2020. 'url': progressive_uri,
  2021. })
  2022. formats.append(http_f)
  2023. last_stream_inf = {}
  2024. return formats, subtitles
  2025. def _extract_m3u8_vod_duration(
  2026. self, m3u8_vod_url, video_id, note=None, errnote=None, data=None, headers={}, query={}):
  2027. m3u8_vod = self._download_webpage(
  2028. m3u8_vod_url, video_id,
  2029. note='Downloading m3u8 VOD manifest' if note is None else note,
  2030. errnote='Failed to download VOD manifest' if errnote is None else errnote,
  2031. fatal=False, data=data, headers=headers, query=query)
  2032. return self._parse_m3u8_vod_duration(m3u8_vod or '', video_id)
  2033. def _parse_m3u8_vod_duration(self, m3u8_vod, video_id):
  2034. if '#EXT-X-ENDLIST' not in m3u8_vod:
  2035. return None
  2036. return int(sum(
  2037. float(line[len('#EXTINF:'):].split(',')[0])
  2038. for line in m3u8_vod.splitlines() if line.startswith('#EXTINF:'))) or None
  2039. def _extract_mpd_vod_duration(
  2040. self, mpd_url, video_id, note=None, errnote=None, data=None, headers={}, query={}):
  2041. mpd_doc = self._download_xml(
  2042. mpd_url, video_id,
  2043. note='Downloading MPD VOD manifest' if note is None else note,
  2044. errnote='Failed to download VOD manifest' if errnote is None else errnote,
  2045. fatal=False, data=data, headers=headers, query=query)
  2046. if not isinstance(mpd_doc, xml.etree.ElementTree.Element):
  2047. return None
  2048. return int_or_none(parse_duration(mpd_doc.get('mediaPresentationDuration')))
  2049. @staticmethod
  2050. def _xpath_ns(path, namespace=None):
  2051. if not namespace:
  2052. return path
  2053. out = []
  2054. for c in path.split('/'):
  2055. if not c or c == '.':
  2056. out.append(c)
  2057. else:
  2058. out.append('{%s}%s' % (namespace, c))
  2059. return '/'.join(out)
  2060. def _extract_smil_formats_and_subtitles(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  2061. if self.get_param('ignore_no_formats_error'):
  2062. fatal = False
  2063. res = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  2064. if res is False:
  2065. assert not fatal
  2066. return [], {}
  2067. smil, urlh = res
  2068. return self._parse_smil_formats_and_subtitles(smil, urlh.url, video_id, f4m_params=f4m_params,
  2069. namespace=self._parse_smil_namespace(smil))
  2070. def _extract_smil_formats(self, *args, **kwargs):
  2071. fmts, subs = self._extract_smil_formats_and_subtitles(*args, **kwargs)
  2072. if subs:
  2073. self._report_ignoring_subs('SMIL')
  2074. return fmts
  2075. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  2076. res = self._download_smil(smil_url, video_id, fatal=fatal)
  2077. if res is False:
  2078. return {}
  2079. smil, urlh = res
  2080. smil_url = urlh.url
  2081. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  2082. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  2083. return self._download_xml_handle(
  2084. smil_url, video_id, 'Downloading SMIL file',
  2085. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  2086. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  2087. namespace = self._parse_smil_namespace(smil)
  2088. formats, subtitles = self._parse_smil_formats_and_subtitles(
  2089. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  2090. video_id = os.path.splitext(url_basename(smil_url))[0]
  2091. title = None
  2092. description = None
  2093. upload_date = None
  2094. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  2095. name = meta.attrib.get('name')
  2096. content = meta.attrib.get('content')
  2097. if not name or not content:
  2098. continue
  2099. if not title and name == 'title':
  2100. title = content
  2101. elif not description and name in ('description', 'abstract'):
  2102. description = content
  2103. elif not upload_date and name == 'date':
  2104. upload_date = unified_strdate(content)
  2105. thumbnails = [{
  2106. 'id': image.get('type'),
  2107. 'url': image.get('src'),
  2108. 'width': int_or_none(image.get('width')),
  2109. 'height': int_or_none(image.get('height')),
  2110. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  2111. return {
  2112. 'id': video_id,
  2113. 'title': title or video_id,
  2114. 'description': description,
  2115. 'upload_date': upload_date,
  2116. 'thumbnails': thumbnails,
  2117. 'formats': formats,
  2118. 'subtitles': subtitles,
  2119. }
  2120. def _parse_smil_namespace(self, smil):
  2121. return self._search_regex(
  2122. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  2123. def _parse_smil_formats(self, *args, **kwargs):
  2124. fmts, subs = self._parse_smil_formats_and_subtitles(*args, **kwargs)
  2125. if subs:
  2126. self._report_ignoring_subs('SMIL')
  2127. return fmts
  2128. def _parse_smil_formats_and_subtitles(
  2129. self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  2130. base = smil_url
  2131. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  2132. b = meta.get('base') or meta.get('httpBase')
  2133. if b:
  2134. base = b
  2135. break
  2136. formats, subtitles = [], {}
  2137. rtmp_count = 0
  2138. http_count = 0
  2139. m3u8_count = 0
  2140. imgs_count = 0
  2141. srcs = set()
  2142. media = itertools.chain.from_iterable(
  2143. smil.findall(self._xpath_ns(arg, namespace))
  2144. for arg in ['.//video', './/audio', './/media'])
  2145. for medium in media:
  2146. src = medium.get('src')
  2147. if not src or src in srcs:
  2148. continue
  2149. srcs.add(src)
  2150. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  2151. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  2152. width = int_or_none(medium.get('width'))
  2153. height = int_or_none(medium.get('height'))
  2154. proto = medium.get('proto')
  2155. ext = medium.get('ext')
  2156. src_ext = determine_ext(src, default_ext=None) or ext or urlhandle_detect_ext(
  2157. self._request_webpage(HEADRequest(src), video_id, note='Requesting extension info', fatal=False))
  2158. streamer = medium.get('streamer') or base
  2159. if proto == 'rtmp' or streamer.startswith('rtmp'):
  2160. rtmp_count += 1
  2161. formats.append({
  2162. 'url': streamer,
  2163. 'play_path': src,
  2164. 'ext': 'flv',
  2165. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  2166. 'tbr': bitrate,
  2167. 'filesize': filesize,
  2168. 'width': width,
  2169. 'height': height,
  2170. })
  2171. if transform_rtmp_url:
  2172. streamer, src = transform_rtmp_url(streamer, src)
  2173. formats[-1].update({
  2174. 'url': streamer,
  2175. 'play_path': src,
  2176. })
  2177. continue
  2178. src_url = src if src.startswith('http') else urllib.parse.urljoin(base, src)
  2179. src_url = src_url.strip()
  2180. if proto == 'm3u8' or src_ext == 'm3u8':
  2181. m3u8_formats, m3u8_subs = self._extract_m3u8_formats_and_subtitles(
  2182. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  2183. self._merge_subtitles(m3u8_subs, target=subtitles)
  2184. if len(m3u8_formats) == 1:
  2185. m3u8_count += 1
  2186. m3u8_formats[0].update({
  2187. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  2188. 'tbr': bitrate,
  2189. 'width': width,
  2190. 'height': height,
  2191. })
  2192. formats.extend(m3u8_formats)
  2193. elif src_ext == 'f4m':
  2194. f4m_url = src_url
  2195. if not f4m_params:
  2196. f4m_params = {
  2197. 'hdcore': '3.2.0',
  2198. 'plugin': 'flowplayer-3.2.0.1',
  2199. }
  2200. f4m_url += '&' if '?' in f4m_url else '?'
  2201. f4m_url += urllib.parse.urlencode(f4m_params)
  2202. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  2203. elif src_ext == 'mpd':
  2204. mpd_formats, mpd_subs = self._extract_mpd_formats_and_subtitles(
  2205. src_url, video_id, mpd_id='dash', fatal=False)
  2206. formats.extend(mpd_formats)
  2207. self._merge_subtitles(mpd_subs, target=subtitles)
  2208. elif re.search(r'\.ism/[Mm]anifest', src_url):
  2209. ism_formats, ism_subs = self._extract_ism_formats_and_subtitles(
  2210. src_url, video_id, ism_id='mss', fatal=False)
  2211. formats.extend(ism_formats)
  2212. self._merge_subtitles(ism_subs, target=subtitles)
  2213. elif src_url.startswith('http') and self._is_valid_url(src, video_id):
  2214. http_count += 1
  2215. formats.append({
  2216. 'url': src_url,
  2217. 'ext': ext or src_ext or 'flv',
  2218. 'format_id': 'http-%d' % (bitrate or http_count),
  2219. 'tbr': bitrate,
  2220. 'filesize': filesize,
  2221. 'width': width,
  2222. 'height': height,
  2223. })
  2224. for medium in smil.findall(self._xpath_ns('.//imagestream', namespace)):
  2225. src = medium.get('src')
  2226. if not src or src in srcs:
  2227. continue
  2228. srcs.add(src)
  2229. imgs_count += 1
  2230. formats.append({
  2231. 'format_id': 'imagestream-%d' % (imgs_count),
  2232. 'url': src,
  2233. 'ext': mimetype2ext(medium.get('type')),
  2234. 'acodec': 'none',
  2235. 'vcodec': 'none',
  2236. 'width': int_or_none(medium.get('width')),
  2237. 'height': int_or_none(medium.get('height')),
  2238. 'format_note': 'SMIL storyboards',
  2239. })
  2240. smil_subs = self._parse_smil_subtitles(smil, namespace=namespace)
  2241. self._merge_subtitles(smil_subs, target=subtitles)
  2242. return formats, subtitles
  2243. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  2244. urls = []
  2245. subtitles = {}
  2246. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  2247. src = textstream.get('src')
  2248. if not src or src in urls:
  2249. continue
  2250. urls.append(src)
  2251. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  2252. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  2253. subtitles.setdefault(lang, []).append({
  2254. 'url': src,
  2255. 'ext': ext,
  2256. })
  2257. return subtitles
  2258. def _extract_xspf_playlist(self, xspf_url, playlist_id, fatal=True):
  2259. res = self._download_xml_handle(
  2260. xspf_url, playlist_id, 'Downloading xpsf playlist',
  2261. 'Unable to download xspf manifest', fatal=fatal)
  2262. if res is False:
  2263. return []
  2264. xspf, urlh = res
  2265. xspf_url = urlh.url
  2266. return self._parse_xspf(
  2267. xspf, playlist_id, xspf_url=xspf_url,
  2268. xspf_base_url=base_url(xspf_url))
  2269. def _parse_xspf(self, xspf_doc, playlist_id, xspf_url=None, xspf_base_url=None):
  2270. NS_MAP = {
  2271. 'xspf': 'http://xspf.org/ns/0/',
  2272. 's1': 'http://static.streamone.nl/player/ns/0',
  2273. }
  2274. entries = []
  2275. for track in xspf_doc.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  2276. title = xpath_text(
  2277. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  2278. description = xpath_text(
  2279. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  2280. thumbnail = xpath_text(
  2281. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  2282. duration = float_or_none(
  2283. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  2284. formats = []
  2285. for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP)):
  2286. format_url = urljoin(xspf_base_url, location.text)
  2287. if not format_url:
  2288. continue
  2289. formats.append({
  2290. 'url': format_url,
  2291. 'manifest_url': xspf_url,
  2292. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  2293. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  2294. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  2295. })
  2296. entries.append({
  2297. 'id': playlist_id,
  2298. 'title': title,
  2299. 'description': description,
  2300. 'thumbnail': thumbnail,
  2301. 'duration': duration,
  2302. 'formats': formats,
  2303. })
  2304. return entries
  2305. def _extract_mpd_formats(self, *args, **kwargs):
  2306. fmts, subs = self._extract_mpd_formats_and_subtitles(*args, **kwargs)
  2307. if subs:
  2308. self._report_ignoring_subs('DASH')
  2309. return fmts
  2310. def _extract_mpd_formats_and_subtitles(self, *args, **kwargs):
  2311. periods = self._extract_mpd_periods(*args, **kwargs)
  2312. return self._merge_mpd_periods(periods)
  2313. def _extract_mpd_periods(
  2314. self, mpd_url, video_id, mpd_id=None, note=None, errnote=None,
  2315. fatal=True, data=None, headers={}, query={}):
  2316. if self.get_param('ignore_no_formats_error'):
  2317. fatal = False
  2318. res = self._download_xml_handle(
  2319. mpd_url, video_id,
  2320. note='Downloading MPD manifest' if note is None else note,
  2321. errnote='Failed to download MPD manifest' if errnote is None else errnote,
  2322. fatal=fatal, data=data, headers=headers, query=query)
  2323. if res is False:
  2324. return []
  2325. mpd_doc, urlh = res
  2326. if mpd_doc is None:
  2327. return []
  2328. # We could have been redirected to a new url when we retrieved our mpd file.
  2329. mpd_url = urlh.url
  2330. mpd_base_url = base_url(mpd_url)
  2331. return self._parse_mpd_periods(mpd_doc, mpd_id, mpd_base_url, mpd_url)
  2332. def _parse_mpd_formats(self, *args, **kwargs):
  2333. fmts, subs = self._parse_mpd_formats_and_subtitles(*args, **kwargs)
  2334. if subs:
  2335. self._report_ignoring_subs('DASH')
  2336. return fmts
  2337. def _parse_mpd_formats_and_subtitles(self, *args, **kwargs):
  2338. periods = self._parse_mpd_periods(*args, **kwargs)
  2339. return self._merge_mpd_periods(periods)
  2340. def _merge_mpd_periods(self, periods):
  2341. """
  2342. Combine all formats and subtitles from an MPD manifest into a single list,
  2343. by concatenate streams with similar formats.
  2344. """
  2345. formats, subtitles = {}, {}
  2346. for period in periods:
  2347. for f in period['formats']:
  2348. assert 'is_dash_periods' not in f, 'format already processed'
  2349. f['is_dash_periods'] = True
  2350. format_key = tuple(v for k, v in f.items() if k not in (
  2351. ('format_id', 'fragments', 'manifest_stream_number')))
  2352. if format_key not in formats:
  2353. formats[format_key] = f
  2354. elif 'fragments' in f:
  2355. formats[format_key].setdefault('fragments', []).extend(f['fragments'])
  2356. if subtitles and period['subtitles']:
  2357. self.report_warning(bug_reports_message(
  2358. 'Found subtitles in multiple periods in the DASH manifest; '
  2359. 'if part of the subtitles are missing,'
  2360. ), only_once=True)
  2361. for sub_lang, sub_info in period['subtitles'].items():
  2362. subtitles.setdefault(sub_lang, []).extend(sub_info)
  2363. return list(formats.values()), subtitles
  2364. def _parse_mpd_periods(self, mpd_doc, mpd_id=None, mpd_base_url='', mpd_url=None):
  2365. """
  2366. Parse formats from MPD manifest.
  2367. References:
  2368. 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
  2369. http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
  2370. 2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
  2371. """
  2372. if not self.get_param('dynamic_mpd', True):
  2373. if mpd_doc.get('type') == 'dynamic':
  2374. return [], {}
  2375. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  2376. def _add_ns(path):
  2377. return self._xpath_ns(path, namespace)
  2378. def is_drm_protected(element):
  2379. return element.find(_add_ns('ContentProtection')) is not None
  2380. def extract_multisegment_info(element, ms_parent_info):
  2381. ms_info = ms_parent_info.copy()
  2382. # As per [1, 5.3.9.2.2] SegmentList and SegmentTemplate share some
  2383. # common attributes and elements. We will only extract relevant
  2384. # for us.
  2385. def extract_common(source):
  2386. segment_timeline = source.find(_add_ns('SegmentTimeline'))
  2387. if segment_timeline is not None:
  2388. s_e = segment_timeline.findall(_add_ns('S'))
  2389. if s_e:
  2390. ms_info['total_number'] = 0
  2391. ms_info['s'] = []
  2392. for s in s_e:
  2393. r = int(s.get('r', 0))
  2394. ms_info['total_number'] += 1 + r
  2395. ms_info['s'].append({
  2396. 't': int(s.get('t', 0)),
  2397. # @d is mandatory (see [1, 5.3.9.6.2, Table 17, page 60])
  2398. 'd': int(s.attrib['d']),
  2399. 'r': r,
  2400. })
  2401. start_number = source.get('startNumber')
  2402. if start_number:
  2403. ms_info['start_number'] = int(start_number)
  2404. timescale = source.get('timescale')
  2405. if timescale:
  2406. ms_info['timescale'] = int(timescale)
  2407. segment_duration = source.get('duration')
  2408. if segment_duration:
  2409. ms_info['segment_duration'] = float(segment_duration)
  2410. def extract_Initialization(source):
  2411. initialization = source.find(_add_ns('Initialization'))
  2412. if initialization is not None:
  2413. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  2414. segment_list = element.find(_add_ns('SegmentList'))
  2415. if segment_list is not None:
  2416. extract_common(segment_list)
  2417. extract_Initialization(segment_list)
  2418. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  2419. if segment_urls_e:
  2420. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  2421. else:
  2422. segment_template = element.find(_add_ns('SegmentTemplate'))
  2423. if segment_template is not None:
  2424. extract_common(segment_template)
  2425. media = segment_template.get('media')
  2426. if media:
  2427. ms_info['media'] = media
  2428. initialization = segment_template.get('initialization')
  2429. if initialization:
  2430. ms_info['initialization'] = initialization
  2431. else:
  2432. extract_Initialization(segment_template)
  2433. return ms_info
  2434. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  2435. stream_numbers = collections.defaultdict(int)
  2436. for period_idx, period in enumerate(mpd_doc.findall(_add_ns('Period'))):
  2437. period_entry = {
  2438. 'id': period.get('id', f'period-{period_idx}'),
  2439. 'formats': [],
  2440. 'subtitles': collections.defaultdict(list),
  2441. }
  2442. period_duration = parse_duration(period.get('duration')) or mpd_duration
  2443. period_ms_info = extract_multisegment_info(period, {
  2444. 'start_number': 1,
  2445. 'timescale': 1,
  2446. })
  2447. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  2448. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  2449. for representation in adaptation_set.findall(_add_ns('Representation')):
  2450. representation_attrib = adaptation_set.attrib.copy()
  2451. representation_attrib.update(representation.attrib)
  2452. # According to [1, 5.3.7.2, Table 9, page 41], @mimeType is mandatory
  2453. mime_type = representation_attrib['mimeType']
  2454. content_type = representation_attrib.get('contentType', mime_type.split('/')[0])
  2455. codec_str = representation_attrib.get('codecs', '')
  2456. # Some kind of binary subtitle found in some youtube livestreams
  2457. if mime_type == 'application/x-rawcc':
  2458. codecs = {'scodec': codec_str}
  2459. else:
  2460. codecs = parse_codecs(codec_str)
  2461. if content_type not in ('video', 'audio', 'text'):
  2462. if mime_type == 'image/jpeg':
  2463. content_type = mime_type
  2464. elif codecs.get('vcodec', 'none') != 'none':
  2465. content_type = 'video'
  2466. elif codecs.get('acodec', 'none') != 'none':
  2467. content_type = 'audio'
  2468. elif codecs.get('scodec', 'none') != 'none':
  2469. content_type = 'text'
  2470. elif mimetype2ext(mime_type) in ('tt', 'dfxp', 'ttml', 'xml', 'json'):
  2471. content_type = 'text'
  2472. else:
  2473. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  2474. continue
  2475. base_url = ''
  2476. for element in (representation, adaptation_set, period, mpd_doc):
  2477. base_url_e = element.find(_add_ns('BaseURL'))
  2478. if try_call(lambda: base_url_e.text) is not None:
  2479. base_url = base_url_e.text + base_url
  2480. if re.match(r'^https?://', base_url):
  2481. break
  2482. if mpd_base_url and base_url.startswith('/'):
  2483. base_url = urllib.parse.urljoin(mpd_base_url, base_url)
  2484. elif mpd_base_url and not re.match(r'^https?://', base_url):
  2485. if not mpd_base_url.endswith('/'):
  2486. mpd_base_url += '/'
  2487. base_url = mpd_base_url + base_url
  2488. representation_id = representation_attrib.get('id')
  2489. lang = representation_attrib.get('lang')
  2490. url_el = representation.find(_add_ns('BaseURL'))
  2491. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  2492. bandwidth = int_or_none(representation_attrib.get('bandwidth'))
  2493. if representation_id is not None:
  2494. format_id = representation_id
  2495. else:
  2496. format_id = content_type
  2497. if mpd_id:
  2498. format_id = mpd_id + '-' + format_id
  2499. if content_type in ('video', 'audio'):
  2500. f = {
  2501. 'format_id': format_id,
  2502. 'manifest_url': mpd_url,
  2503. 'ext': mimetype2ext(mime_type),
  2504. 'width': int_or_none(representation_attrib.get('width')),
  2505. 'height': int_or_none(representation_attrib.get('height')),
  2506. 'tbr': float_or_none(bandwidth, 1000),
  2507. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  2508. 'fps': int_or_none(representation_attrib.get('frameRate')),
  2509. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  2510. 'format_note': 'DASH %s' % content_type,
  2511. 'filesize': filesize,
  2512. 'container': mimetype2ext(mime_type) + '_dash',
  2513. **codecs
  2514. }
  2515. elif content_type == 'text':
  2516. f = {
  2517. 'ext': mimetype2ext(mime_type),
  2518. 'manifest_url': mpd_url,
  2519. 'filesize': filesize,
  2520. }
  2521. elif content_type == 'image/jpeg':
  2522. # See test case in VikiIE
  2523. # https://www.viki.com/videos/1175236v-choosing-spouse-by-lottery-episode-1
  2524. f = {
  2525. 'format_id': format_id,
  2526. 'ext': 'mhtml',
  2527. 'manifest_url': mpd_url,
  2528. 'format_note': 'DASH storyboards (jpeg)',
  2529. 'acodec': 'none',
  2530. 'vcodec': 'none',
  2531. }
  2532. if is_drm_protected(adaptation_set) or is_drm_protected(representation):
  2533. f['has_drm'] = True
  2534. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  2535. def prepare_template(template_name, identifiers):
  2536. tmpl = representation_ms_info[template_name]
  2537. if representation_id is not None:
  2538. tmpl = tmpl.replace('$RepresentationID$', representation_id)
  2539. # First of, % characters outside $...$ templates
  2540. # must be escaped by doubling for proper processing
  2541. # by % operator string formatting used further (see
  2542. # https://github.com/ytdl-org/youtube-dl/issues/16867).
  2543. t = ''
  2544. in_template = False
  2545. for c in tmpl:
  2546. t += c
  2547. if c == '$':
  2548. in_template = not in_template
  2549. elif c == '%' and not in_template:
  2550. t += c
  2551. # Next, $...$ templates are translated to their
  2552. # %(...) counterparts to be used with % operator
  2553. t = re.sub(r'\$(%s)\$' % '|'.join(identifiers), r'%(\1)d', t)
  2554. t = re.sub(r'\$(%s)%%([^$]+)\$' % '|'.join(identifiers), r'%(\1)\2', t)
  2555. t.replace('$$', '$')
  2556. return t
  2557. # @initialization is a regular template like @media one
  2558. # so it should be handled just the same way (see
  2559. # https://github.com/ytdl-org/youtube-dl/issues/11605)
  2560. if 'initialization' in representation_ms_info:
  2561. initialization_template = prepare_template(
  2562. 'initialization',
  2563. # As per [1, 5.3.9.4.2, Table 15, page 54] $Number$ and
  2564. # $Time$ shall not be included for @initialization thus
  2565. # only $Bandwidth$ remains
  2566. ('Bandwidth', ))
  2567. representation_ms_info['initialization_url'] = initialization_template % {
  2568. 'Bandwidth': bandwidth,
  2569. }
  2570. def location_key(location):
  2571. return 'url' if re.match(r'^https?://', location) else 'path'
  2572. if 'segment_urls' not in representation_ms_info and 'media' in representation_ms_info:
  2573. media_template = prepare_template('media', ('Number', 'Bandwidth', 'Time'))
  2574. media_location_key = location_key(media_template)
  2575. # As per [1, 5.3.9.4.4, Table 16, page 55] $Number$ and $Time$
  2576. # can't be used at the same time
  2577. if '%(Number' in media_template and 's' not in representation_ms_info:
  2578. segment_duration = None
  2579. if 'total_number' not in representation_ms_info and 'segment_duration' in representation_ms_info:
  2580. segment_duration = float_or_none(representation_ms_info['segment_duration'], representation_ms_info['timescale'])
  2581. representation_ms_info['total_number'] = int(math.ceil(
  2582. float_or_none(period_duration, segment_duration, default=0)))
  2583. representation_ms_info['fragments'] = [{
  2584. media_location_key: media_template % {
  2585. 'Number': segment_number,
  2586. 'Bandwidth': bandwidth,
  2587. },
  2588. 'duration': segment_duration,
  2589. } for segment_number in range(
  2590. representation_ms_info['start_number'],
  2591. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  2592. else:
  2593. # $Number*$ or $Time$ in media template with S list available
  2594. # Example $Number*$: http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg
  2595. # Example $Time$: https://play.arkena.com/embed/avp/v2/player/media/b41dda37-d8e7-4d3f-b1b5-9a9db578bdfe/1/129411
  2596. representation_ms_info['fragments'] = []
  2597. segment_time = 0
  2598. segment_d = None
  2599. segment_number = representation_ms_info['start_number']
  2600. def add_segment_url():
  2601. segment_url = media_template % {
  2602. 'Time': segment_time,
  2603. 'Bandwidth': bandwidth,
  2604. 'Number': segment_number,
  2605. }
  2606. representation_ms_info['fragments'].append({
  2607. media_location_key: segment_url,
  2608. 'duration': float_or_none(segment_d, representation_ms_info['timescale']),
  2609. })
  2610. for num, s in enumerate(representation_ms_info['s']):
  2611. segment_time = s.get('t') or segment_time
  2612. segment_d = s['d']
  2613. add_segment_url()
  2614. segment_number += 1
  2615. for r in range(s.get('r', 0)):
  2616. segment_time += segment_d
  2617. add_segment_url()
  2618. segment_number += 1
  2619. segment_time += segment_d
  2620. elif 'segment_urls' in representation_ms_info and 's' in representation_ms_info:
  2621. # No media template,
  2622. # e.g. https://www.youtube.com/watch?v=iXZV5uAYMJI
  2623. # or any YouTube dashsegments video
  2624. fragments = []
  2625. segment_index = 0
  2626. timescale = representation_ms_info['timescale']
  2627. for s in representation_ms_info['s']:
  2628. duration = float_or_none(s['d'], timescale)
  2629. for r in range(s.get('r', 0) + 1):
  2630. segment_uri = representation_ms_info['segment_urls'][segment_index]
  2631. fragments.append({
  2632. location_key(segment_uri): segment_uri,
  2633. 'duration': duration,
  2634. })
  2635. segment_index += 1
  2636. representation_ms_info['fragments'] = fragments
  2637. elif 'segment_urls' in representation_ms_info:
  2638. # Segment URLs with no SegmentTimeline
  2639. # E.g. https://www.seznam.cz/zpravy/clanek/cesko-zasahne-vitr-o-sile-vichrice-muze-byt-i-zivotu-nebezpecny-39091
  2640. # https://github.com/ytdl-org/youtube-dl/pull/14844
  2641. fragments = []
  2642. segment_duration = float_or_none(
  2643. representation_ms_info['segment_duration'],
  2644. representation_ms_info['timescale']) if 'segment_duration' in representation_ms_info else None
  2645. for segment_url in representation_ms_info['segment_urls']:
  2646. fragment = {
  2647. location_key(segment_url): segment_url,
  2648. }
  2649. if segment_duration:
  2650. fragment['duration'] = segment_duration
  2651. fragments.append(fragment)
  2652. representation_ms_info['fragments'] = fragments
  2653. # If there is a fragments key available then we correctly recognized fragmented media.
  2654. # Otherwise we will assume unfragmented media with direct access. Technically, such
  2655. # assumption is not necessarily correct since we may simply have no support for
  2656. # some forms of fragmented media renditions yet, but for now we'll use this fallback.
  2657. if 'fragments' in representation_ms_info:
  2658. f.update({
  2659. # NB: mpd_url may be empty when MPD manifest is parsed from a string
  2660. 'url': mpd_url or base_url,
  2661. 'fragment_base_url': base_url,
  2662. 'fragments': [],
  2663. 'protocol': 'http_dash_segments' if mime_type != 'image/jpeg' else 'mhtml',
  2664. })
  2665. if 'initialization_url' in representation_ms_info:
  2666. initialization_url = representation_ms_info['initialization_url']
  2667. if not f.get('url'):
  2668. f['url'] = initialization_url
  2669. f['fragments'].append({location_key(initialization_url): initialization_url})
  2670. f['fragments'].extend(representation_ms_info['fragments'])
  2671. if not period_duration:
  2672. period_duration = try_get(
  2673. representation_ms_info,
  2674. lambda r: sum(frag['duration'] for frag in r['fragments']), float)
  2675. else:
  2676. # Assuming direct URL to unfragmented media.
  2677. f['url'] = base_url
  2678. if content_type in ('video', 'audio', 'image/jpeg'):
  2679. f['manifest_stream_number'] = stream_numbers[f['url']]
  2680. stream_numbers[f['url']] += 1
  2681. period_entry['formats'].append(f)
  2682. elif content_type == 'text':
  2683. period_entry['subtitles'][lang or 'und'].append(f)
  2684. yield period_entry
  2685. def _extract_ism_formats(self, *args, **kwargs):
  2686. fmts, subs = self._extract_ism_formats_and_subtitles(*args, **kwargs)
  2687. if subs:
  2688. self._report_ignoring_subs('ISM')
  2689. return fmts
  2690. def _extract_ism_formats_and_subtitles(self, ism_url, video_id, ism_id=None, note=None, errnote=None, fatal=True, data=None, headers={}, query={}):
  2691. if self.get_param('ignore_no_formats_error'):
  2692. fatal = False
  2693. res = self._download_xml_handle(
  2694. ism_url, video_id,
  2695. note='Downloading ISM manifest' if note is None else note,
  2696. errnote='Failed to download ISM manifest' if errnote is None else errnote,
  2697. fatal=fatal, data=data, headers=headers, query=query)
  2698. if res is False:
  2699. return [], {}
  2700. ism_doc, urlh = res
  2701. if ism_doc is None:
  2702. return [], {}
  2703. return self._parse_ism_formats_and_subtitles(ism_doc, urlh.url, ism_id)
  2704. def _parse_ism_formats_and_subtitles(self, ism_doc, ism_url, ism_id=None):
  2705. """
  2706. Parse formats from ISM manifest.
  2707. References:
  2708. 1. [MS-SSTR]: Smooth Streaming Protocol,
  2709. https://msdn.microsoft.com/en-us/library/ff469518.aspx
  2710. """
  2711. if ism_doc.get('IsLive') == 'TRUE':
  2712. return [], {}
  2713. duration = int(ism_doc.attrib['Duration'])
  2714. timescale = int_or_none(ism_doc.get('TimeScale')) or 10000000
  2715. formats = []
  2716. subtitles = {}
  2717. for stream in ism_doc.findall('StreamIndex'):
  2718. stream_type = stream.get('Type')
  2719. if stream_type not in ('video', 'audio', 'text'):
  2720. continue
  2721. url_pattern = stream.attrib['Url']
  2722. stream_timescale = int_or_none(stream.get('TimeScale')) or timescale
  2723. stream_name = stream.get('Name')
  2724. stream_language = stream.get('Language', 'und')
  2725. for track in stream.findall('QualityLevel'):
  2726. KNOWN_TAGS = {'255': 'AACL', '65534': 'EC-3'}
  2727. fourcc = track.get('FourCC') or KNOWN_TAGS.get(track.get('AudioTag'))
  2728. # TODO: add support for WVC1 and WMAP
  2729. if fourcc not in ('H264', 'AVC1', 'AACL', 'TTML', 'EC-3'):
  2730. self.report_warning('%s is not a supported codec' % fourcc)
  2731. continue
  2732. tbr = int(track.attrib['Bitrate']) // 1000
  2733. # [1] does not mention Width and Height attributes. However,
  2734. # they're often present while MaxWidth and MaxHeight are
  2735. # missing, so should be used as fallbacks
  2736. width = int_or_none(track.get('MaxWidth') or track.get('Width'))
  2737. height = int_or_none(track.get('MaxHeight') or track.get('Height'))
  2738. sampling_rate = int_or_none(track.get('SamplingRate'))
  2739. track_url_pattern = re.sub(r'{[Bb]itrate}', track.attrib['Bitrate'], url_pattern)
  2740. track_url_pattern = urllib.parse.urljoin(ism_url, track_url_pattern)
  2741. fragments = []
  2742. fragment_ctx = {
  2743. 'time': 0,
  2744. }
  2745. stream_fragments = stream.findall('c')
  2746. for stream_fragment_index, stream_fragment in enumerate(stream_fragments):
  2747. fragment_ctx['time'] = int_or_none(stream_fragment.get('t')) or fragment_ctx['time']
  2748. fragment_repeat = int_or_none(stream_fragment.get('r')) or 1
  2749. fragment_ctx['duration'] = int_or_none(stream_fragment.get('d'))
  2750. if not fragment_ctx['duration']:
  2751. try:
  2752. next_fragment_time = int(stream_fragment[stream_fragment_index + 1].attrib['t'])
  2753. except IndexError:
  2754. next_fragment_time = duration
  2755. fragment_ctx['duration'] = (next_fragment_time - fragment_ctx['time']) / fragment_repeat
  2756. for _ in range(fragment_repeat):
  2757. fragments.append({
  2758. 'url': re.sub(r'{start[ _]time}', str(fragment_ctx['time']), track_url_pattern),
  2759. 'duration': fragment_ctx['duration'] / stream_timescale,
  2760. })
  2761. fragment_ctx['time'] += fragment_ctx['duration']
  2762. if stream_type == 'text':
  2763. subtitles.setdefault(stream_language, []).append({
  2764. 'ext': 'ismt',
  2765. 'protocol': 'ism',
  2766. 'url': ism_url,
  2767. 'manifest_url': ism_url,
  2768. 'fragments': fragments,
  2769. '_download_params': {
  2770. 'stream_type': stream_type,
  2771. 'duration': duration,
  2772. 'timescale': stream_timescale,
  2773. 'fourcc': fourcc,
  2774. 'language': stream_language,
  2775. 'codec_private_data': track.get('CodecPrivateData'),
  2776. }
  2777. })
  2778. elif stream_type in ('video', 'audio'):
  2779. formats.append({
  2780. 'format_id': join_nonempty(ism_id, stream_name, tbr),
  2781. 'url': ism_url,
  2782. 'manifest_url': ism_url,
  2783. 'ext': 'ismv' if stream_type == 'video' else 'isma',
  2784. 'width': width,
  2785. 'height': height,
  2786. 'tbr': tbr,
  2787. 'asr': sampling_rate,
  2788. 'vcodec': 'none' if stream_type == 'audio' else fourcc,
  2789. 'acodec': 'none' if stream_type == 'video' else fourcc,
  2790. 'protocol': 'ism',
  2791. 'fragments': fragments,
  2792. 'has_drm': ism_doc.find('Protection') is not None,
  2793. 'language': stream_language,
  2794. 'audio_channels': int_or_none(track.get('Channels')),
  2795. '_download_params': {
  2796. 'stream_type': stream_type,
  2797. 'duration': duration,
  2798. 'timescale': stream_timescale,
  2799. 'width': width or 0,
  2800. 'height': height or 0,
  2801. 'fourcc': fourcc,
  2802. 'language': stream_language,
  2803. 'codec_private_data': track.get('CodecPrivateData'),
  2804. 'sampling_rate': sampling_rate,
  2805. 'channels': int_or_none(track.get('Channels', 2)),
  2806. 'bits_per_sample': int_or_none(track.get('BitsPerSample', 16)),
  2807. 'nal_unit_length_field': int_or_none(track.get('NALUnitLengthField', 4)),
  2808. },
  2809. })
  2810. return formats, subtitles
  2811. def _parse_html5_media_entries(self, base_url, webpage, video_id, m3u8_id=None, m3u8_entry_protocol='m3u8_native', mpd_id=None, preference=None, quality=None):
  2812. def absolute_url(item_url):
  2813. return urljoin(base_url, item_url)
  2814. def parse_content_type(content_type):
  2815. if not content_type:
  2816. return {}
  2817. ctr = re.search(r'(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?', content_type)
  2818. if ctr:
  2819. mimetype, codecs = ctr.groups()
  2820. f = parse_codecs(codecs)
  2821. f['ext'] = mimetype2ext(mimetype)
  2822. return f
  2823. return {}
  2824. def _media_formats(src, cur_media_type, type_info=None):
  2825. type_info = type_info or {}
  2826. full_url = absolute_url(src)
  2827. ext = type_info.get('ext') or determine_ext(full_url)
  2828. if ext == 'm3u8':
  2829. is_plain_url = False
  2830. formats = self._extract_m3u8_formats(
  2831. full_url, video_id, ext='mp4',
  2832. entry_protocol=m3u8_entry_protocol, m3u8_id=m3u8_id,
  2833. preference=preference, quality=quality, fatal=False)
  2834. elif ext == 'mpd':
  2835. is_plain_url = False
  2836. formats = self._extract_mpd_formats(
  2837. full_url, video_id, mpd_id=mpd_id, fatal=False)
  2838. else:
  2839. is_plain_url = True
  2840. formats = [{
  2841. 'url': full_url,
  2842. 'vcodec': 'none' if cur_media_type == 'audio' else None,
  2843. 'ext': ext,
  2844. }]
  2845. return is_plain_url, formats
  2846. entries = []
  2847. # amp-video and amp-audio are very similar to their HTML5 counterparts
  2848. # so we will include them right here (see
  2849. # https://www.ampproject.org/docs/reference/components/amp-video)
  2850. # For dl8-* tags see https://delight-vr.com/documentation/dl8-video/
  2851. _MEDIA_TAG_NAME_RE = r'(?:(?:amp|dl8(?:-live)?)-)?(video|audio)'
  2852. media_tags = [(media_tag, media_tag_name, media_type, '')
  2853. for media_tag, media_tag_name, media_type
  2854. in re.findall(r'(?s)(<(%s)[^>]*/>)' % _MEDIA_TAG_NAME_RE, webpage)]
  2855. media_tags.extend(re.findall(
  2856. # We only allow video|audio followed by a whitespace or '>'.
  2857. # Allowing more characters may end up in significant slow down (see
  2858. # https://github.com/ytdl-org/youtube-dl/issues/11979,
  2859. # e.g. http://www.porntrex.com/maps/videositemap.xml).
  2860. r'(?s)(<(?P<tag>%s)(?:\s+[^>]*)?>)(.*?)</(?P=tag)>' % _MEDIA_TAG_NAME_RE, webpage))
  2861. for media_tag, _, media_type, media_content in media_tags:
  2862. media_info = {
  2863. 'formats': [],
  2864. 'subtitles': {},
  2865. }
  2866. media_attributes = extract_attributes(media_tag)
  2867. src = strip_or_none(dict_get(media_attributes, ('src', 'data-video-src', 'data-src', 'data-source')))
  2868. if src:
  2869. f = parse_content_type(media_attributes.get('type'))
  2870. _, formats = _media_formats(src, media_type, f)
  2871. media_info['formats'].extend(formats)
  2872. media_info['thumbnail'] = absolute_url(media_attributes.get('poster'))
  2873. if media_content:
  2874. for source_tag in re.findall(r'<source[^>]+>', media_content):
  2875. s_attr = extract_attributes(source_tag)
  2876. # data-video-src and data-src are non standard but seen
  2877. # several times in the wild
  2878. src = strip_or_none(dict_get(s_attr, ('src', 'data-video-src', 'data-src', 'data-source')))
  2879. if not src:
  2880. continue
  2881. f = parse_content_type(s_attr.get('type'))
  2882. is_plain_url, formats = _media_formats(src, media_type, f)
  2883. if is_plain_url:
  2884. # width, height, res, label and title attributes are
  2885. # all not standard but seen several times in the wild
  2886. labels = [
  2887. s_attr.get(lbl)
  2888. for lbl in ('label', 'title')
  2889. if str_or_none(s_attr.get(lbl))
  2890. ]
  2891. width = int_or_none(s_attr.get('width'))
  2892. height = (int_or_none(s_attr.get('height'))
  2893. or int_or_none(s_attr.get('res')))
  2894. if not width or not height:
  2895. for lbl in labels:
  2896. resolution = parse_resolution(lbl)
  2897. if not resolution:
  2898. continue
  2899. width = width or resolution.get('width')
  2900. height = height or resolution.get('height')
  2901. for lbl in labels:
  2902. tbr = parse_bitrate(lbl)
  2903. if tbr:
  2904. break
  2905. else:
  2906. tbr = None
  2907. f.update({
  2908. 'width': width,
  2909. 'height': height,
  2910. 'tbr': tbr,
  2911. 'format_id': s_attr.get('label') or s_attr.get('title'),
  2912. })
  2913. f.update(formats[0])
  2914. media_info['formats'].append(f)
  2915. else:
  2916. media_info['formats'].extend(formats)
  2917. for track_tag in re.findall(r'<track[^>]+>', media_content):
  2918. track_attributes = extract_attributes(track_tag)
  2919. kind = track_attributes.get('kind')
  2920. if not kind or kind in ('subtitles', 'captions'):
  2921. src = strip_or_none(track_attributes.get('src'))
  2922. if not src:
  2923. continue
  2924. lang = track_attributes.get('srclang') or track_attributes.get('lang') or track_attributes.get('label')
  2925. media_info['subtitles'].setdefault(lang, []).append({
  2926. 'url': absolute_url(src),
  2927. })
  2928. for f in media_info['formats']:
  2929. f.setdefault('http_headers', {})['Referer'] = base_url
  2930. if media_info['formats'] or media_info['subtitles']:
  2931. entries.append(media_info)
  2932. return entries
  2933. def _extract_akamai_formats(self, *args, **kwargs):
  2934. fmts, subs = self._extract_akamai_formats_and_subtitles(*args, **kwargs)
  2935. if subs:
  2936. self._report_ignoring_subs('akamai')
  2937. return fmts
  2938. def _extract_akamai_formats_and_subtitles(self, manifest_url, video_id, hosts={}):
  2939. signed = 'hdnea=' in manifest_url
  2940. if not signed:
  2941. # https://learn.akamai.com/en-us/webhelp/media-services-on-demand/stream-packaging-user-guide/GUID-BE6C0F73-1E06-483B-B0EA-57984B91B7F9.html
  2942. manifest_url = re.sub(
  2943. r'(?:b=[\d,-]+|(?:__a__|attributes)=off|__b__=\d+)&?',
  2944. '', manifest_url).strip('?')
  2945. formats = []
  2946. subtitles = {}
  2947. hdcore_sign = 'hdcore=3.7.0'
  2948. f4m_url = re.sub(r'(https?://[^/]+)/i/', r'\1/z/', manifest_url).replace('/master.m3u8', '/manifest.f4m')
  2949. hds_host = hosts.get('hds')
  2950. if hds_host:
  2951. f4m_url = re.sub(r'(https?://)[^/]+', r'\1' + hds_host, f4m_url)
  2952. if 'hdcore=' not in f4m_url:
  2953. f4m_url += ('&' if '?' in f4m_url else '?') + hdcore_sign
  2954. f4m_formats = self._extract_f4m_formats(
  2955. f4m_url, video_id, f4m_id='hds', fatal=False)
  2956. for entry in f4m_formats:
  2957. entry.update({'extra_param_to_segment_url': hdcore_sign})
  2958. formats.extend(f4m_formats)
  2959. m3u8_url = re.sub(r'(https?://[^/]+)/z/', r'\1/i/', manifest_url).replace('/manifest.f4m', '/master.m3u8')
  2960. hls_host = hosts.get('hls')
  2961. if hls_host:
  2962. m3u8_url = re.sub(r'(https?://)[^/]+', r'\1' + hls_host, m3u8_url)
  2963. m3u8_formats, m3u8_subtitles = self._extract_m3u8_formats_and_subtitles(
  2964. m3u8_url, video_id, 'mp4', 'm3u8_native',
  2965. m3u8_id='hls', fatal=False)
  2966. formats.extend(m3u8_formats)
  2967. subtitles = self._merge_subtitles(subtitles, m3u8_subtitles)
  2968. http_host = hosts.get('http')
  2969. if http_host and m3u8_formats and not signed:
  2970. REPL_REGEX = r'https?://[^/]+/i/([^,]+),([^/]+),([^/]+)\.csmil/.+'
  2971. qualities = re.match(REPL_REGEX, m3u8_url).group(2).split(',')
  2972. qualities_length = len(qualities)
  2973. if len(m3u8_formats) in (qualities_length, qualities_length + 1):
  2974. i = 0
  2975. for f in m3u8_formats:
  2976. if f['vcodec'] != 'none':
  2977. for protocol in ('http', 'https'):
  2978. http_f = f.copy()
  2979. del http_f['manifest_url']
  2980. http_url = re.sub(
  2981. REPL_REGEX, protocol + fr'://{http_host}/\g<1>{qualities[i]}\3', f['url'])
  2982. http_f.update({
  2983. 'format_id': http_f['format_id'].replace('hls-', protocol + '-'),
  2984. 'url': http_url,
  2985. 'protocol': protocol,
  2986. })
  2987. formats.append(http_f)
  2988. i += 1
  2989. return formats, subtitles
  2990. def _extract_wowza_formats(self, url, video_id, m3u8_entry_protocol='m3u8_native', skip_protocols=[]):
  2991. query = urllib.parse.urlparse(url).query
  2992. url = re.sub(r'/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)', '', url)
  2993. mobj = re.search(
  2994. r'(?:(?:http|rtmp|rtsp)(?P<s>s)?:)?(?P<url>//[^?]+)', url)
  2995. url_base = mobj.group('url')
  2996. http_base_url = '%s%s:%s' % ('http', mobj.group('s') or '', url_base)
  2997. formats = []
  2998. def manifest_url(manifest):
  2999. m_url = f'{http_base_url}/{manifest}'
  3000. if query:
  3001. m_url += '?%s' % query
  3002. return m_url
  3003. if 'm3u8' not in skip_protocols:
  3004. formats.extend(self._extract_m3u8_formats(
  3005. manifest_url('playlist.m3u8'), video_id, 'mp4',
  3006. m3u8_entry_protocol, m3u8_id='hls', fatal=False))
  3007. if 'f4m' not in skip_protocols:
  3008. formats.extend(self._extract_f4m_formats(
  3009. manifest_url('manifest.f4m'),
  3010. video_id, f4m_id='hds', fatal=False))
  3011. if 'dash' not in skip_protocols:
  3012. formats.extend(self._extract_mpd_formats(
  3013. manifest_url('manifest.mpd'),
  3014. video_id, mpd_id='dash', fatal=False))
  3015. if re.search(r'(?:/smil:|\.smil)', url_base):
  3016. if 'smil' not in skip_protocols:
  3017. rtmp_formats = self._extract_smil_formats(
  3018. manifest_url('jwplayer.smil'),
  3019. video_id, fatal=False)
  3020. for rtmp_format in rtmp_formats:
  3021. rtsp_format = rtmp_format.copy()
  3022. rtsp_format['url'] = '%s/%s' % (rtmp_format['url'], rtmp_format['play_path'])
  3023. del rtsp_format['play_path']
  3024. del rtsp_format['ext']
  3025. rtsp_format.update({
  3026. 'url': rtsp_format['url'].replace('rtmp://', 'rtsp://'),
  3027. 'format_id': rtmp_format['format_id'].replace('rtmp', 'rtsp'),
  3028. 'protocol': 'rtsp',
  3029. })
  3030. formats.extend([rtmp_format, rtsp_format])
  3031. else:
  3032. for protocol in ('rtmp', 'rtsp'):
  3033. if protocol not in skip_protocols:
  3034. formats.append({
  3035. 'url': f'{protocol}:{url_base}',
  3036. 'format_id': protocol,
  3037. 'protocol': protocol,
  3038. })
  3039. return formats
  3040. def _find_jwplayer_data(self, webpage, video_id=None, transform_source=js_to_json):
  3041. return self._search_json(
  3042. r'''(?<!-)\bjwplayer\s*\(\s*(?P<q>'|")(?!(?P=q)).+(?P=q)\s*\)(?:(?!</script>).)*?\.\s*(?:setup\s*\(|(?P<load>load)\s*\(\s*\[)''',
  3043. webpage, 'JWPlayer data', video_id,
  3044. # must be a {...} or sequence, ending
  3045. contains_pattern=r'\{(?s:.*)}(?(load)(?:\s*,\s*\{(?s:.*)})*)', end_pattern=r'(?(load)\]|\))',
  3046. transform_source=transform_source, default=None)
  3047. def _extract_jwplayer_data(self, webpage, video_id, *args, transform_source=js_to_json, **kwargs):
  3048. jwplayer_data = self._find_jwplayer_data(
  3049. webpage, video_id, transform_source=transform_source)
  3050. return self._parse_jwplayer_data(
  3051. jwplayer_data, video_id, *args, **kwargs)
  3052. def _parse_jwplayer_data(self, jwplayer_data, video_id=None, require_title=True,
  3053. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  3054. entries = []
  3055. if not isinstance(jwplayer_data, dict):
  3056. return entries
  3057. playlist_items = jwplayer_data.get('playlist')
  3058. # JWPlayer backward compatibility: single playlist item/flattened playlists
  3059. # https://github.com/jwplayer/jwplayer/blob/v7.7.0/src/js/playlist/playlist.js#L10
  3060. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/api/config.js#L81-L96
  3061. if not isinstance(playlist_items, list):
  3062. playlist_items = (playlist_items or jwplayer_data, )
  3063. for video_data in playlist_items:
  3064. if not isinstance(video_data, dict):
  3065. continue
  3066. # JWPlayer backward compatibility: flattened sources
  3067. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/playlist/item.js#L29-L35
  3068. if 'sources' not in video_data:
  3069. video_data['sources'] = [video_data]
  3070. this_video_id = video_id or video_data['mediaid']
  3071. formats = self._parse_jwplayer_formats(
  3072. video_data['sources'], video_id=this_video_id, m3u8_id=m3u8_id,
  3073. mpd_id=mpd_id, rtmp_params=rtmp_params, base_url=base_url)
  3074. subtitles = {}
  3075. for track in traverse_obj(video_data, (
  3076. 'tracks', lambda _, v: v['kind'].lower() in ('captions', 'subtitles'))):
  3077. track_url = urljoin(base_url, track.get('file'))
  3078. if not track_url:
  3079. continue
  3080. subtitles.setdefault(track.get('label') or 'en', []).append({
  3081. 'url': self._proto_relative_url(track_url)
  3082. })
  3083. entry = {
  3084. 'id': this_video_id,
  3085. 'title': unescapeHTML(video_data['title'] if require_title else video_data.get('title')),
  3086. 'description': clean_html(video_data.get('description')),
  3087. 'thumbnail': urljoin(base_url, self._proto_relative_url(video_data.get('image'))),
  3088. 'timestamp': int_or_none(video_data.get('pubdate')),
  3089. 'duration': float_or_none(jwplayer_data.get('duration') or video_data.get('duration')),
  3090. 'subtitles': subtitles,
  3091. 'alt_title': clean_html(video_data.get('subtitle')), # attributes used e.g. by Tele5 ...
  3092. 'genre': clean_html(video_data.get('genre')),
  3093. 'channel': clean_html(dict_get(video_data, ('category', 'channel'))),
  3094. 'season_number': int_or_none(video_data.get('season')),
  3095. 'episode_number': int_or_none(video_data.get('episode')),
  3096. 'release_year': int_or_none(video_data.get('releasedate')),
  3097. 'age_limit': int_or_none(video_data.get('age_restriction')),
  3098. }
  3099. # https://github.com/jwplayer/jwplayer/blob/master/src/js/utils/validator.js#L32
  3100. if len(formats) == 1 and re.search(r'^(?:http|//).*(?:youtube\.com|youtu\.be)/.+', formats[0]['url']):
  3101. entry.update({
  3102. '_type': 'url_transparent',
  3103. 'url': formats[0]['url'],
  3104. })
  3105. else:
  3106. entry['formats'] = formats
  3107. entries.append(entry)
  3108. if len(entries) == 1:
  3109. return entries[0]
  3110. else:
  3111. return self.playlist_result(entries)
  3112. def _parse_jwplayer_formats(self, jwplayer_sources_data, video_id=None,
  3113. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  3114. urls = set()
  3115. formats = []
  3116. for source in jwplayer_sources_data:
  3117. if not isinstance(source, dict):
  3118. continue
  3119. source_url = urljoin(
  3120. base_url, self._proto_relative_url(source.get('file')))
  3121. if not source_url or source_url in urls:
  3122. continue
  3123. urls.add(source_url)
  3124. source_type = source.get('type') or ''
  3125. ext = mimetype2ext(source_type) or determine_ext(source_url)
  3126. if source_type == 'hls' or ext == 'm3u8' or 'format=m3u8-aapl' in source_url:
  3127. formats.extend(self._extract_m3u8_formats(
  3128. source_url, video_id, 'mp4', entry_protocol='m3u8_native',
  3129. m3u8_id=m3u8_id, fatal=False))
  3130. elif source_type == 'dash' or ext == 'mpd' or 'format=mpd-time-csf' in source_url:
  3131. formats.extend(self._extract_mpd_formats(
  3132. source_url, video_id, mpd_id=mpd_id, fatal=False))
  3133. elif ext == 'smil':
  3134. formats.extend(self._extract_smil_formats(
  3135. source_url, video_id, fatal=False))
  3136. # https://github.com/jwplayer/jwplayer/blob/master/src/js/providers/default.js#L67
  3137. elif source_type.startswith('audio') or ext in (
  3138. 'oga', 'aac', 'mp3', 'mpeg', 'vorbis'):
  3139. formats.append({
  3140. 'url': source_url,
  3141. 'vcodec': 'none',
  3142. 'ext': ext,
  3143. })
  3144. else:
  3145. format_id = str_or_none(source.get('label'))
  3146. height = int_or_none(source.get('height'))
  3147. if height is None and format_id:
  3148. # Often no height is provided but there is a label in
  3149. # format like "1080p", "720p SD", or 1080.
  3150. height = parse_resolution(format_id).get('height')
  3151. a_format = {
  3152. 'url': source_url,
  3153. 'width': int_or_none(source.get('width')),
  3154. 'height': height,
  3155. 'tbr': int_or_none(source.get('bitrate'), scale=1000),
  3156. 'filesize': int_or_none(source.get('filesize')),
  3157. 'ext': ext,
  3158. 'format_id': format_id
  3159. }
  3160. if source_url.startswith('rtmp'):
  3161. a_format['ext'] = 'flv'
  3162. # See com/longtailvideo/jwplayer/media/RTMPMediaProvider.as
  3163. # of jwplayer.flash.swf
  3164. rtmp_url_parts = re.split(
  3165. r'((?:mp4|mp3|flv):)', source_url, maxsplit=1)
  3166. if len(rtmp_url_parts) == 3:
  3167. rtmp_url, prefix, play_path = rtmp_url_parts
  3168. a_format.update({
  3169. 'url': rtmp_url,
  3170. 'play_path': prefix + play_path,
  3171. })
  3172. if rtmp_params:
  3173. a_format.update(rtmp_params)
  3174. formats.append(a_format)
  3175. return formats
  3176. def _live_title(self, name):
  3177. self._downloader.deprecation_warning('yt_dlp.InfoExtractor._live_title is deprecated and does not work as expected')
  3178. return name
  3179. def _int(self, v, name, fatal=False, **kwargs):
  3180. res = int_or_none(v, **kwargs)
  3181. if res is None:
  3182. msg = f'Failed to extract {name}: Could not parse value {v!r}'
  3183. if fatal:
  3184. raise ExtractorError(msg)
  3185. else:
  3186. self.report_warning(msg)
  3187. return res
  3188. def _float(self, v, name, fatal=False, **kwargs):
  3189. res = float_or_none(v, **kwargs)
  3190. if res is None:
  3191. msg = f'Failed to extract {name}: Could not parse value {v!r}'
  3192. if fatal:
  3193. raise ExtractorError(msg)
  3194. else:
  3195. self.report_warning(msg)
  3196. return res
  3197. def _set_cookie(self, domain, name, value, expire_time=None, port=None,
  3198. path='/', secure=False, discard=False, rest={}, **kwargs):
  3199. cookie = http.cookiejar.Cookie(
  3200. 0, name, value, port, port is not None, domain, True,
  3201. domain.startswith('.'), path, True, secure, expire_time,
  3202. discard, None, None, rest)
  3203. self.cookiejar.set_cookie(cookie)
  3204. def _get_cookies(self, url):
  3205. """ Return a http.cookies.SimpleCookie with the cookies for the url """
  3206. return LenientSimpleCookie(self._downloader.cookiejar.get_cookie_header(url))
  3207. def _apply_first_set_cookie_header(self, url_handle, cookie):
  3208. """
  3209. Apply first Set-Cookie header instead of the last. Experimental.
  3210. Some sites (e.g. [1-3]) may serve two cookies under the same name
  3211. in Set-Cookie header and expect the first (old) one to be set rather
  3212. than second (new). However, as of RFC6265 the newer one cookie
  3213. should be set into cookie store what actually happens.
  3214. We will workaround this issue by resetting the cookie to
  3215. the first one manually.
  3216. 1. https://new.vk.com/
  3217. 2. https://github.com/ytdl-org/youtube-dl/issues/9841#issuecomment-227871201
  3218. 3. https://learning.oreilly.com/
  3219. """
  3220. for header, cookies in url_handle.headers.items():
  3221. if header.lower() != 'set-cookie':
  3222. continue
  3223. cookies = cookies.encode('iso-8859-1').decode('utf-8')
  3224. cookie_value = re.search(
  3225. r'%s=(.+?);.*?\b[Dd]omain=(.+?)(?:[,;]|$)' % cookie, cookies)
  3226. if cookie_value:
  3227. value, domain = cookie_value.groups()
  3228. self._set_cookie(domain, cookie, value)
  3229. break
  3230. @classmethod
  3231. def get_testcases(cls, include_onlymatching=False):
  3232. # Do not look in super classes
  3233. t = vars(cls).get('_TEST')
  3234. if t:
  3235. assert not hasattr(cls, '_TESTS'), f'{cls.ie_key()}IE has _TEST and _TESTS'
  3236. tests = [t]
  3237. else:
  3238. tests = vars(cls).get('_TESTS', [])
  3239. for t in tests:
  3240. if not include_onlymatching and t.get('only_matching', False):
  3241. continue
  3242. t['name'] = cls.ie_key()
  3243. yield t
  3244. if getattr(cls, '__wrapped__', None):
  3245. yield from cls.__wrapped__.get_testcases(include_onlymatching)
  3246. @classmethod
  3247. def get_webpage_testcases(cls):
  3248. tests = vars(cls).get('_WEBPAGE_TESTS', [])
  3249. for t in tests:
  3250. t['name'] = cls.ie_key()
  3251. yield t
  3252. if getattr(cls, '__wrapped__', None):
  3253. yield from cls.__wrapped__.get_webpage_testcases()
  3254. @classproperty(cache=True)
  3255. def age_limit(cls):
  3256. """Get age limit from the testcases"""
  3257. return max(traverse_obj(
  3258. (*cls.get_testcases(include_onlymatching=False), *cls.get_webpage_testcases()),
  3259. (..., (('playlist', 0), None), 'info_dict', 'age_limit')) or [0])
  3260. @classproperty(cache=True)
  3261. def _RETURN_TYPE(cls):
  3262. """What the extractor returns: "video", "playlist", "any", or None (Unknown)"""
  3263. tests = tuple(cls.get_testcases(include_onlymatching=False))
  3264. if not tests:
  3265. return None
  3266. elif not any(k.startswith('playlist') for test in tests for k in test):
  3267. return 'video'
  3268. elif all(any(k.startswith('playlist') for k in test) for test in tests):
  3269. return 'playlist'
  3270. return 'any'
  3271. @classmethod
  3272. def is_single_video(cls, url):
  3273. """Returns whether the URL is of a single video, None if unknown"""
  3274. if cls.suitable(url):
  3275. return {'video': True, 'playlist': False}.get(cls._RETURN_TYPE)
  3276. @classmethod
  3277. def is_suitable(cls, age_limit):
  3278. """Test whether the extractor is generally suitable for the given age limit"""
  3279. return not age_restricted(cls.age_limit, age_limit)
  3280. @classmethod
  3281. def description(cls, *, markdown=True, search_examples=None):
  3282. """Description of the extractor"""
  3283. desc = ''
  3284. if cls._NETRC_MACHINE:
  3285. if markdown:
  3286. desc += f' [*{cls._NETRC_MACHINE}*](## "netrc machine")'
  3287. else:
  3288. desc += f' [{cls._NETRC_MACHINE}]'
  3289. if cls.IE_DESC is False:
  3290. desc += ' [HIDDEN]'
  3291. elif cls.IE_DESC:
  3292. desc += f' {cls.IE_DESC}'
  3293. if cls.SEARCH_KEY:
  3294. desc += f'{";" if cls.IE_DESC else ""} "{cls.SEARCH_KEY}:" prefix'
  3295. if search_examples:
  3296. _COUNTS = ('', '5', '10', 'all')
  3297. desc += f' (e.g. "{cls.SEARCH_KEY}{random.choice(_COUNTS)}:{random.choice(search_examples)}")'
  3298. if not cls.working():
  3299. desc += ' (**Currently broken**)' if markdown else ' (Currently broken)'
  3300. # Escape emojis. Ref: https://github.com/github/markup/issues/1153
  3301. name = (' - **%s**' % re.sub(r':(\w+:)', ':\u200B\\g<1>', cls.IE_NAME)) if markdown else cls.IE_NAME
  3302. return f'{name}:{desc}' if desc else name
  3303. def extract_subtitles(self, *args, **kwargs):
  3304. if (self.get_param('writesubtitles', False)
  3305. or self.get_param('listsubtitles')):
  3306. return self._get_subtitles(*args, **kwargs)
  3307. return {}
  3308. def _get_subtitles(self, *args, **kwargs):
  3309. raise NotImplementedError('This method must be implemented by subclasses')
  3310. class CommentsDisabled(Exception):
  3311. """Raise in _get_comments if comments are disabled for the video"""
  3312. def extract_comments(self, *args, **kwargs):
  3313. if not self.get_param('getcomments'):
  3314. return None
  3315. generator = self._get_comments(*args, **kwargs)
  3316. def extractor():
  3317. comments = []
  3318. interrupted = True
  3319. try:
  3320. while True:
  3321. comments.append(next(generator))
  3322. except StopIteration:
  3323. interrupted = False
  3324. except KeyboardInterrupt:
  3325. self.to_screen('Interrupted by user')
  3326. except self.CommentsDisabled:
  3327. return {'comments': None, 'comment_count': None}
  3328. except Exception as e:
  3329. if self.get_param('ignoreerrors') is not True:
  3330. raise
  3331. self._downloader.report_error(e)
  3332. comment_count = len(comments)
  3333. self.to_screen(f'Extracted {comment_count} comments')
  3334. return {
  3335. 'comments': comments,
  3336. 'comment_count': None if interrupted else comment_count
  3337. }
  3338. return extractor
  3339. def _get_comments(self, *args, **kwargs):
  3340. raise NotImplementedError('This method must be implemented by subclasses')
  3341. @staticmethod
  3342. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  3343. """ Merge subtitle items for one language. Items with duplicated URLs/data
  3344. will be dropped. """
  3345. list1_data = {(item.get('url'), item.get('data')) for item in subtitle_list1}
  3346. ret = list(subtitle_list1)
  3347. ret.extend(item for item in subtitle_list2 if (item.get('url'), item.get('data')) not in list1_data)
  3348. return ret
  3349. @classmethod
  3350. def _merge_subtitles(cls, *dicts, target=None):
  3351. """ Merge subtitle dictionaries, language by language. """
  3352. if target is None:
  3353. target = {}
  3354. for d in dicts:
  3355. for lang, subs in d.items():
  3356. target[lang] = cls._merge_subtitle_items(target.get(lang, []), subs)
  3357. return target
  3358. def extract_automatic_captions(self, *args, **kwargs):
  3359. if (self.get_param('writeautomaticsub', False)
  3360. or self.get_param('listsubtitles')):
  3361. return self._get_automatic_captions(*args, **kwargs)
  3362. return {}
  3363. def _get_automatic_captions(self, *args, **kwargs):
  3364. raise NotImplementedError('This method must be implemented by subclasses')
  3365. @functools.cached_property
  3366. def _cookies_passed(self):
  3367. """Whether cookies have been passed to YoutubeDL"""
  3368. return self.get_param('cookiefile') is not None or self.get_param('cookiesfrombrowser') is not None
  3369. def mark_watched(self, *args, **kwargs):
  3370. if not self.get_param('mark_watched', False):
  3371. return
  3372. if self.supports_login() and self._get_login_info()[0] is not None or self._cookies_passed:
  3373. self._mark_watched(*args, **kwargs)
  3374. def _mark_watched(self, *args, **kwargs):
  3375. raise NotImplementedError('This method must be implemented by subclasses')
  3376. def geo_verification_headers(self):
  3377. headers = {}
  3378. geo_verification_proxy = self.get_param('geo_verification_proxy')
  3379. if geo_verification_proxy:
  3380. headers['Ytdl-request-proxy'] = geo_verification_proxy
  3381. return headers
  3382. @staticmethod
  3383. def _generic_id(url):
  3384. return urllib.parse.unquote(os.path.splitext(url.rstrip('/').split('/')[-1])[0])
  3385. def _generic_title(self, url='', webpage='', *, default=None):
  3386. return (self._og_search_title(webpage, default=None)
  3387. or self._html_extract_title(webpage, default=None)
  3388. or urllib.parse.unquote(os.path.splitext(url_basename(url))[0])
  3389. or default)
  3390. def _extract_chapters_helper(self, chapter_list, start_function, title_function, duration, strict=True):
  3391. if not duration:
  3392. return
  3393. chapter_list = [{
  3394. 'start_time': start_function(chapter),
  3395. 'title': title_function(chapter),
  3396. } for chapter in chapter_list or []]
  3397. if strict:
  3398. warn = self.report_warning
  3399. else:
  3400. warn = self.write_debug
  3401. chapter_list.sort(key=lambda c: c['start_time'] or 0)
  3402. chapters = [{'start_time': 0}]
  3403. for idx, chapter in enumerate(chapter_list):
  3404. if chapter['start_time'] is None:
  3405. warn(f'Incomplete chapter {idx}')
  3406. elif chapters[-1]['start_time'] <= chapter['start_time'] <= duration:
  3407. chapters.append(chapter)
  3408. elif chapter not in chapters:
  3409. issue = (f'{chapter["start_time"]} > {duration}' if chapter['start_time'] > duration
  3410. else f'{chapter["start_time"]} < {chapters[-1]["start_time"]}')
  3411. warn(f'Invalid start time ({issue}) for chapter "{chapter["title"]}"')
  3412. return chapters[1:]
  3413. def _extract_chapters_from_description(self, description, duration):
  3414. duration_re = r'(?:\d+:)?\d{1,2}:\d{2}'
  3415. sep_re = r'(?m)^\s*(%s)\b\W*\s(%s)\s*$'
  3416. return self._extract_chapters_helper(
  3417. re.findall(sep_re % (duration_re, r'.+?'), description or ''),
  3418. start_function=lambda x: parse_duration(x[0]), title_function=lambda x: x[1],
  3419. duration=duration, strict=False) or self._extract_chapters_helper(
  3420. re.findall(sep_re % (r'.+?', duration_re), description or ''),
  3421. start_function=lambda x: parse_duration(x[1]), title_function=lambda x: x[0],
  3422. duration=duration, strict=False)
  3423. @staticmethod
  3424. def _availability(is_private=None, needs_premium=None, needs_subscription=None, needs_auth=None, is_unlisted=None):
  3425. all_known = all(map(
  3426. lambda x: x is not None,
  3427. (is_private, needs_premium, needs_subscription, needs_auth, is_unlisted)))
  3428. return (
  3429. 'private' if is_private
  3430. else 'premium_only' if needs_premium
  3431. else 'subscriber_only' if needs_subscription
  3432. else 'needs_auth' if needs_auth
  3433. else 'unlisted' if is_unlisted
  3434. else 'public' if all_known
  3435. else None)
  3436. def _configuration_arg(self, key, default=NO_DEFAULT, *, ie_key=None, casesense=False):
  3437. '''
  3438. @returns A list of values for the extractor argument given by "key"
  3439. or "default" if no such key is present
  3440. @param default The default value to return when the key is not present (default: [])
  3441. @param casesense When false, the values are converted to lower case
  3442. '''
  3443. ie_key = ie_key if isinstance(ie_key, str) else (ie_key or self).ie_key()
  3444. val = traverse_obj(self._downloader.params, ('extractor_args', ie_key.lower(), key))
  3445. if val is None:
  3446. return [] if default is NO_DEFAULT else default
  3447. return list(val) if casesense else [x.lower() for x in val]
  3448. def _yes_playlist(self, playlist_id, video_id, smuggled_data=None, *, playlist_label='playlist', video_label='video'):
  3449. if not playlist_id or not video_id:
  3450. return not video_id
  3451. no_playlist = (smuggled_data or {}).get('force_noplaylist')
  3452. if no_playlist is not None:
  3453. return not no_playlist
  3454. video_id = '' if video_id is True else f' {video_id}'
  3455. playlist_id = '' if playlist_id is True else f' {playlist_id}'
  3456. if self.get_param('noplaylist'):
  3457. self.to_screen(f'Downloading just the {video_label}{video_id} because of --no-playlist')
  3458. return False
  3459. self.to_screen(f'Downloading {playlist_label}{playlist_id} - add --no-playlist to download just the {video_label}{video_id}')
  3460. return True
  3461. def _error_or_warning(self, err, _count=None, _retries=0, *, fatal=True):
  3462. RetryManager.report_retry(
  3463. err, _count or int(fatal), _retries,
  3464. info=self.to_screen, warn=self.report_warning, error=None if fatal else self.report_warning,
  3465. sleep_func=self.get_param('retry_sleep_functions', {}).get('extractor'))
  3466. def RetryManager(self, **kwargs):
  3467. return RetryManager(self.get_param('extractor_retries', 3), self._error_or_warning, **kwargs)
  3468. def _extract_generic_embeds(self, url, *args, info_dict={}, note='Extracting generic embeds', **kwargs):
  3469. display_id = traverse_obj(info_dict, 'display_id', 'id')
  3470. self.to_screen(f'{format_field(display_id, None, "%s: ")}{note}')
  3471. return self._downloader.get_info_extractor('Generic')._extract_embeds(
  3472. smuggle_url(url, {'block_ies': [self.ie_key()]}), *args, **kwargs)
  3473. @classmethod
  3474. def extract_from_webpage(cls, ydl, url, webpage):
  3475. ie = (cls if isinstance(cls._extract_from_webpage, types.MethodType)
  3476. else ydl.get_info_extractor(cls.ie_key()))
  3477. for info in ie._extract_from_webpage(url, webpage) or []:
  3478. # url = None since we do not want to set (webpage/original)_url
  3479. ydl.add_default_extra_info(info, ie, None)
  3480. yield info
  3481. @classmethod
  3482. def _extract_from_webpage(cls, url, webpage):
  3483. for embed_url in orderedSet(
  3484. cls._extract_embed_urls(url, webpage) or [], lazy=True):
  3485. yield cls.url_result(embed_url, None if cls._VALID_URL is False else cls)
  3486. @classmethod
  3487. def _extract_embed_urls(cls, url, webpage):
  3488. """@returns all the embed urls on the webpage"""
  3489. if '_EMBED_URL_RE' not in cls.__dict__:
  3490. assert isinstance(cls._EMBED_REGEX, (list, tuple))
  3491. for idx, regex in enumerate(cls._EMBED_REGEX):
  3492. assert regex.count('(?P<url>') == 1, \
  3493. f'{cls.__name__}._EMBED_REGEX[{idx}] must have exactly 1 url group\n\t{regex}'
  3494. cls._EMBED_URL_RE = tuple(map(re.compile, cls._EMBED_REGEX))
  3495. for regex in cls._EMBED_URL_RE:
  3496. for mobj in regex.finditer(webpage):
  3497. embed_url = urllib.parse.urljoin(url, unescapeHTML(mobj.group('url')))
  3498. if cls._VALID_URL is False or cls.suitable(embed_url):
  3499. yield embed_url
  3500. class StopExtraction(Exception):
  3501. pass
  3502. @classmethod
  3503. def _extract_url(cls, webpage): # TODO: Remove
  3504. """Only for compatibility with some older extractors"""
  3505. return next(iter(cls._extract_embed_urls(None, webpage) or []), None)
  3506. @classmethod
  3507. def __init_subclass__(cls, *, plugin_name=None, **kwargs):
  3508. if plugin_name:
  3509. mro = inspect.getmro(cls)
  3510. super_class = cls.__wrapped__ = mro[mro.index(cls) + 1]
  3511. cls.PLUGIN_NAME, cls.ie_key = plugin_name, super_class.ie_key
  3512. cls.IE_NAME = f'{super_class.IE_NAME}+{plugin_name}'
  3513. while getattr(super_class, '__wrapped__', None):
  3514. super_class = super_class.__wrapped__
  3515. setattr(sys.modules[super_class.__module__], super_class.__name__, cls)
  3516. _PLUGIN_OVERRIDES[super_class].append(cls)
  3517. return super().__init_subclass__(**kwargs)
  3518. class SearchInfoExtractor(InfoExtractor):
  3519. """
  3520. Base class for paged search queries extractors.
  3521. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  3522. Instances should define _SEARCH_KEY and optionally _MAX_RESULTS
  3523. """
  3524. _MAX_RESULTS = float('inf')
  3525. _RETURN_TYPE = 'playlist'
  3526. @classproperty
  3527. def _VALID_URL(cls):
  3528. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  3529. def _real_extract(self, query):
  3530. prefix, query = self._match_valid_url(query).group('prefix', 'query')
  3531. if prefix == '':
  3532. return self._get_n_results(query, 1)
  3533. elif prefix == 'all':
  3534. return self._get_n_results(query, self._MAX_RESULTS)
  3535. else:
  3536. n = int(prefix)
  3537. if n <= 0:
  3538. raise ExtractorError(f'invalid download number {n} for query "{query}"')
  3539. elif n > self._MAX_RESULTS:
  3540. self.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  3541. n = self._MAX_RESULTS
  3542. return self._get_n_results(query, n)
  3543. def _get_n_results(self, query, n):
  3544. """Get a specified number of results for a query.
  3545. Either this function or _search_results must be overridden by subclasses """
  3546. return self.playlist_result(
  3547. itertools.islice(self._search_results(query), 0, None if n == float('inf') else n),
  3548. query, query)
  3549. def _search_results(self, query):
  3550. """Returns an iterator of search results"""
  3551. raise NotImplementedError('This method must be implemented by subclasses')
  3552. @classproperty
  3553. def SEARCH_KEY(cls):
  3554. return cls._SEARCH_KEY
  3555. class UnsupportedURLIE(InfoExtractor):
  3556. _VALID_URL = '.*'
  3557. _ENABLED = False
  3558. IE_DESC = False
  3559. def _real_extract(self, url):
  3560. raise UnsupportedError(url)
  3561. _PLUGIN_OVERRIDES = collections.defaultdict(list)