2
0

common.py 132 KB

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