common.py 178 KB

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