common.py 145 KB

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