common.py 144 KB

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