common.py 129 KB

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