common.py 147 KB

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