common.py 138 KB

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