common.py 134 KB

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