logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

digitalconcerthall.py (12334B)


  1. import time
  2. from .common import InfoExtractor
  3. from ..networking.exceptions import HTTPError
  4. from ..utils import (
  5. ExtractorError,
  6. jwt_decode_hs256,
  7. parse_codecs,
  8. try_get,
  9. url_or_none,
  10. urlencode_postdata,
  11. )
  12. from ..utils.traversal import traverse_obj
  13. class DigitalConcertHallIE(InfoExtractor):
  14. IE_DESC = 'DigitalConcertHall extractor'
  15. _VALID_URL = r'https?://(?:www\.)?digitalconcerthall\.com/(?P<language>[a-z]+)/(?P<type>film|concert|work)/(?P<id>[0-9]+)-?(?P<part>[0-9]+)?'
  16. _NETRC_MACHINE = 'digitalconcerthall'
  17. _TESTS = [{
  18. 'note': 'Playlist with only one video',
  19. 'url': 'https://www.digitalconcerthall.com/en/concert/53201',
  20. 'info_dict': {
  21. 'id': '53201-1',
  22. 'ext': 'mp4',
  23. 'composer': 'Kurt Weill',
  24. 'title': '[Magic Night]',
  25. 'thumbnail': r're:^https?://images.digitalconcerthall.com/cms/thumbnails.*\.jpg$',
  26. 'upload_date': '20210624',
  27. 'timestamp': 1624548600,
  28. 'duration': 2798,
  29. 'album_artists': ['Members of the Berliner Philharmoniker', 'Simon Rössler'],
  30. 'composers': ['Kurt Weill'],
  31. },
  32. 'params': {'skip_download': 'm3u8'},
  33. }, {
  34. 'note': 'Concert with several works and an interview',
  35. 'url': 'https://www.digitalconcerthall.com/en/concert/53785',
  36. 'info_dict': {
  37. 'id': '53785',
  38. 'album_artists': ['Berliner Philharmoniker', 'Kirill Petrenko'],
  39. 'title': 'Kirill Petrenko conducts Mendelssohn and Shostakovich',
  40. 'thumbnail': r're:^https?://images.digitalconcerthall.com/cms/thumbnails.*\.jpg$',
  41. },
  42. 'params': {'skip_download': 'm3u8'},
  43. 'playlist_count': 3,
  44. }, {
  45. 'url': 'https://www.digitalconcerthall.com/en/film/388',
  46. 'info_dict': {
  47. 'id': '388',
  48. 'ext': 'mp4',
  49. 'title': 'The Berliner Philharmoniker and Frank Peter Zimmermann',
  50. 'description': 'md5:cfe25a7044fa4be13743e5089b5b5eb2',
  51. 'thumbnail': r're:^https?://images.digitalconcerthall.com/cms/thumbnails.*\.jpg$',
  52. 'upload_date': '20220714',
  53. 'timestamp': 1657785600,
  54. 'album_artists': ['Frank Peter Zimmermann', 'Benedikt von Bernstorff', 'Jakob von Bernstorff'],
  55. },
  56. 'params': {'skip_download': 'm3u8'},
  57. }, {
  58. 'note': 'Concert with several works and an interview',
  59. 'url': 'https://www.digitalconcerthall.com/en/work/53785-1',
  60. 'info_dict': {
  61. 'id': '53785',
  62. 'album_artists': ['Berliner Philharmoniker', 'Kirill Petrenko'],
  63. 'title': 'Kirill Petrenko conducts Mendelssohn and Shostakovich',
  64. 'thumbnail': r're:^https?://images.digitalconcerthall.com/cms/thumbnails.*\.jpg$',
  65. },
  66. 'params': {'skip_download': 'm3u8'},
  67. 'playlist_count': 1,
  68. }]
  69. _LOGIN_HINT = ('Use --username token --password ACCESS_TOKEN where ACCESS_TOKEN '
  70. 'is the "access_token_production" from your browser local storage')
  71. _REFRESH_HINT = 'or else use a "refresh_token" with --username refresh --password REFRESH_TOKEN'
  72. _OAUTH_URL = 'https://api.digitalconcerthall.com/v2/oauth2/token'
  73. _CLIENT_ID = 'dch.webapp'
  74. _CLIENT_SECRET = '2ySLN+2Fwb'
  75. _USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15'
  76. _OAUTH_HEADERS = {
  77. 'Accept': 'application/json',
  78. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  79. 'Origin': 'https://www.digitalconcerthall.com',
  80. 'Referer': 'https://www.digitalconcerthall.com/',
  81. 'User-Agent': _USER_AGENT,
  82. }
  83. _access_token = None
  84. _access_token_expiry = 0
  85. _refresh_token = None
  86. @property
  87. def _access_token_is_expired(self):
  88. return self._access_token_expiry - 30 <= int(time.time())
  89. def _set_access_token(self, value):
  90. self._access_token = value
  91. self._access_token_expiry = traverse_obj(value, ({jwt_decode_hs256}, 'exp', {int})) or 0
  92. def _cache_tokens(self, /):
  93. self.cache.store(self._NETRC_MACHINE, 'tokens', {
  94. 'access_token': self._access_token,
  95. 'refresh_token': self._refresh_token,
  96. })
  97. def _fetch_new_tokens(self, invalidate=False):
  98. if invalidate:
  99. self.report_warning('Access token has been invalidated')
  100. self._set_access_token(None)
  101. if not self._access_token_is_expired:
  102. return
  103. if not self._refresh_token:
  104. self._set_access_token(None)
  105. self._cache_tokens()
  106. raise ExtractorError(
  107. 'Access token has expired or been invalidated. '
  108. 'Get a new "access_token_production" value from your browser '
  109. f'and try again, {self._REFRESH_HINT}', expected=True)
  110. # If we only have a refresh token, we need a temporary "initial token" for the refresh flow
  111. bearer_token = self._access_token or self._download_json(
  112. self._OAUTH_URL, None, 'Obtaining initial token', 'Unable to obtain initial token',
  113. data=urlencode_postdata({
  114. 'affiliate': 'none',
  115. 'grant_type': 'device',
  116. 'device_vendor': 'unknown',
  117. # device_model 'Safari' gets split streams of 4K/HEVC video and lossless/FLAC audio,
  118. # but this is no longer effective since actual login is not possible anymore
  119. 'device_model': 'unknown',
  120. 'app_id': self._CLIENT_ID,
  121. 'app_distributor': 'berlinphil',
  122. 'app_version': '1.95.0',
  123. 'client_secret': self._CLIENT_SECRET,
  124. }), headers=self._OAUTH_HEADERS)['access_token']
  125. try:
  126. response = self._download_json(
  127. self._OAUTH_URL, None, 'Refreshing token', 'Unable to refresh token',
  128. data=urlencode_postdata({
  129. 'grant_type': 'refresh_token',
  130. 'refresh_token': self._refresh_token,
  131. 'client_id': self._CLIENT_ID,
  132. 'client_secret': self._CLIENT_SECRET,
  133. }), headers={
  134. **self._OAUTH_HEADERS,
  135. 'Authorization': f'Bearer {bearer_token}',
  136. })
  137. except ExtractorError as e:
  138. if isinstance(e.cause, HTTPError) and e.cause.status == 401:
  139. self._set_access_token(None)
  140. self._refresh_token = None
  141. self._cache_tokens()
  142. raise ExtractorError('Your tokens have been invalidated', expected=True)
  143. raise
  144. self._set_access_token(response['access_token'])
  145. if refresh_token := traverse_obj(response, ('refresh_token', {str})):
  146. self.write_debug('New refresh token granted')
  147. self._refresh_token = refresh_token
  148. self._cache_tokens()
  149. def _perform_login(self, username, password):
  150. self.report_login()
  151. if username == 'refresh':
  152. self._refresh_token = password
  153. self._fetch_new_tokens()
  154. if username == 'token':
  155. if not traverse_obj(password, {jwt_decode_hs256}):
  156. raise ExtractorError(
  157. f'The access token passed to yt-dlp is not valid. {self._LOGIN_HINT}', expected=True)
  158. self._set_access_token(password)
  159. self._cache_tokens()
  160. if username in ('refresh', 'token'):
  161. if self.get_param('cachedir') is not False:
  162. token_type = 'access' if username == 'token' else 'refresh'
  163. self.to_screen(f'Your {token_type} token has been cached to disk. To use the cached '
  164. 'token next time, pass --username cache along with any password')
  165. return
  166. if username != 'cache':
  167. raise ExtractorError(
  168. 'Login with username and password is no longer supported '
  169. f'for this site. {self._LOGIN_HINT}, {self._REFRESH_HINT}', expected=True)
  170. # Try cached access_token
  171. cached_tokens = self.cache.load(self._NETRC_MACHINE, 'tokens', default={})
  172. self._set_access_token(cached_tokens.get('access_token'))
  173. self._refresh_token = cached_tokens.get('refresh_token')
  174. if not self._access_token_is_expired:
  175. return
  176. # Try cached refresh_token
  177. self._fetch_new_tokens(invalidate=True)
  178. def _real_initialize(self):
  179. if not self._access_token:
  180. self.raise_login_required(
  181. 'All content on this site is only available for registered users. '
  182. f'{self._LOGIN_HINT}, {self._REFRESH_HINT}', method=None)
  183. def _entries(self, items, language, type_, **kwargs):
  184. for item in items:
  185. video_id = item['id']
  186. for should_retry in (True, False):
  187. self._fetch_new_tokens(invalidate=not should_retry)
  188. try:
  189. stream_info = self._download_json(
  190. self._proto_relative_url(item['_links']['streams']['href']), video_id, headers={
  191. 'Accept': 'application/json',
  192. 'Authorization': f'Bearer {self._access_token}',
  193. 'Accept-Language': language,
  194. 'User-Agent': self._USER_AGENT,
  195. })
  196. break
  197. except ExtractorError as error:
  198. if should_retry and isinstance(error.cause, HTTPError) and error.cause.status == 401:
  199. continue
  200. raise
  201. formats = []
  202. for m3u8_url in traverse_obj(stream_info, ('channel', ..., 'stream', ..., 'url', {url_or_none})):
  203. formats.extend(self._extract_m3u8_formats(m3u8_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
  204. for fmt in formats:
  205. if fmt.get('format_note') and fmt.get('vcodec') == 'none':
  206. fmt.update(parse_codecs(fmt['format_note']))
  207. yield {
  208. 'id': video_id,
  209. 'title': item.get('title'),
  210. 'composer': item.get('name_composer'),
  211. 'formats': formats,
  212. 'duration': item.get('duration_total'),
  213. 'timestamp': traverse_obj(item, ('date', 'published')),
  214. 'description': item.get('short_description') or stream_info.get('short_description'),
  215. **kwargs,
  216. 'chapters': [{
  217. 'start_time': chapter.get('time'),
  218. 'end_time': try_get(chapter, lambda x: x['time'] + x['duration']),
  219. 'title': chapter.get('text'),
  220. } for chapter in item['cuepoints']] if item.get('cuepoints') and type_ == 'concert' else None,
  221. }
  222. def _real_extract(self, url):
  223. language, type_, video_id, part = self._match_valid_url(url).group('language', 'type', 'id', 'part')
  224. if not language:
  225. language = 'en'
  226. api_type = 'concert' if type_ == 'work' else type_
  227. vid_info = self._download_json(
  228. f'https://api.digitalconcerthall.com/v2/{api_type}/{video_id}', video_id, headers={
  229. 'Accept': 'application/json',
  230. 'Accept-Language': language,
  231. 'User-Agent': self._USER_AGENT,
  232. })
  233. videos = [vid_info] if type_ == 'film' else traverse_obj(vid_info, ('_embedded', ..., ...))
  234. if type_ == 'work':
  235. videos = [videos[int(part) - 1]]
  236. album_artists = traverse_obj(vid_info, ('_links', 'artist', ..., 'name', {str}))
  237. thumbnail = traverse_obj(vid_info, (
  238. 'image', ..., {self._proto_relative_url}, {url_or_none},
  239. {lambda x: x.format(width=0, height=0)}, any)) # NB: 0x0 is the original size
  240. return {
  241. '_type': 'playlist',
  242. 'id': video_id,
  243. 'title': vid_info.get('title'),
  244. 'entries': self._entries(
  245. videos, language, type_, thumbnail=thumbnail, album_artists=album_artists),
  246. 'thumbnail': thumbnail,
  247. 'album_artists': album_artists,
  248. }