common.py 114 KB

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