common.py 181 KB

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