common.py 138 KB

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