common.py 133 KB

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