common.py 116 KB

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