common.py 110 KB

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