common.py 110 KB

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