]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/abematv.py
[ie/JoqrAg] Add extractor (#8384)
[yt-dlp.git] / yt_dlp / extractor / abematv.py
1 import base64
2 import binascii
3 import functools
4 import hashlib
5 import hmac
6 import io
7 import json
8 import re
9 import struct
10 import time
11 import urllib.parse
12 import urllib.request
13 import urllib.response
14 import uuid
15 from ..utils.networking import clean_proxies
16 from .common import InfoExtractor
17 from ..aes import aes_ecb_decrypt
18 from ..utils import (
19 ExtractorError,
20 bytes_to_intlist,
21 decode_base_n,
22 int_or_none,
23 intlist_to_bytes,
24 OnDemandPagedList,
25 time_seconds,
26 traverse_obj,
27 update_url_query,
28 )
29
30
31 def add_opener(ydl, handler): # FIXME: Create proper API in .networking
32 """Add a handler for opening URLs, like _download_webpage"""
33 # https://github.com/python/cpython/blob/main/Lib/urllib/request.py#L426
34 # https://github.com/python/cpython/blob/main/Lib/urllib/request.py#L605
35 rh = ydl._request_director.handlers['Urllib']
36 if 'abematv-license' in rh._SUPPORTED_URL_SCHEMES:
37 return
38 headers = ydl.params['http_headers'].copy()
39 proxies = ydl.proxies.copy()
40 clean_proxies(proxies, headers)
41 opener = rh._get_instance(cookiejar=ydl.cookiejar, proxies=proxies)
42 assert isinstance(opener, urllib.request.OpenerDirector)
43 opener.add_handler(handler)
44 rh._SUPPORTED_URL_SCHEMES = (*rh._SUPPORTED_URL_SCHEMES, 'abematv-license')
45
46
47 class AbemaLicenseHandler(urllib.request.BaseHandler):
48 handler_order = 499
49 STRTABLE = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
50 HKEY = b'3AF0298C219469522A313570E8583005A642E73EDD58E3EA2FB7339D3DF1597E'
51
52 def __init__(self, ie: 'AbemaTVIE'):
53 # the protocol that this should really handle is 'abematv-license://'
54 # abematv_license_open is just a placeholder for development purposes
55 # ref. https://github.com/python/cpython/blob/f4c03484da59049eb62a9bf7777b963e2267d187/Lib/urllib/request.py#L510
56 setattr(self, 'abematv-license_open', getattr(self, 'abematv_license_open'))
57 self.ie = ie
58
59 def _get_videokey_from_ticket(self, ticket):
60 to_show = self.ie.get_param('verbose', False)
61 media_token = self.ie._get_media_token(to_show=to_show)
62
63 license_response = self.ie._download_json(
64 'https://license.abema.io/abematv-hls', None, note='Requesting playback license' if to_show else False,
65 query={'t': media_token},
66 data=json.dumps({
67 'kv': 'a',
68 'lt': ticket
69 }).encode('utf-8'),
70 headers={
71 'Content-Type': 'application/json',
72 })
73
74 res = decode_base_n(license_response['k'], table=self.STRTABLE)
75 encvideokey = bytes_to_intlist(struct.pack('>QQ', res >> 64, res & 0xffffffffffffffff))
76
77 h = hmac.new(
78 binascii.unhexlify(self.HKEY),
79 (license_response['cid'] + self.ie._DEVICE_ID).encode('utf-8'),
80 digestmod=hashlib.sha256)
81 enckey = bytes_to_intlist(h.digest())
82
83 return intlist_to_bytes(aes_ecb_decrypt(encvideokey, enckey))
84
85 def abematv_license_open(self, url):
86 url = url.get_full_url() if isinstance(url, urllib.request.Request) else url
87 ticket = urllib.parse.urlparse(url).netloc
88 response_data = self._get_videokey_from_ticket(ticket)
89 return urllib.response.addinfourl(io.BytesIO(response_data), headers={
90 'Content-Length': str(len(response_data)),
91 }, url=url, code=200)
92
93
94 class AbemaTVBaseIE(InfoExtractor):
95 _USERTOKEN = None
96 _DEVICE_ID = None
97 _MEDIATOKEN = None
98
99 _SECRETKEY = b'v+Gjs=25Aw5erR!J8ZuvRrCx*rGswhB&qdHd_SYerEWdU&a?3DzN9BRbp5KwY4hEmcj5#fykMjJ=AuWz5GSMY-d@H7DMEh3M@9n2G552Us$$k9cD=3TxwWe86!x#Zyhe'
100
101 @classmethod
102 def _generate_aks(cls, deviceid):
103 deviceid = deviceid.encode('utf-8')
104 # add 1 hour and then drop minute and secs
105 ts_1hour = int((time_seconds() // 3600 + 1) * 3600)
106 time_struct = time.gmtime(ts_1hour)
107 ts_1hour_str = str(ts_1hour).encode('utf-8')
108
109 tmp = None
110
111 def mix_once(nonce):
112 nonlocal tmp
113 h = hmac.new(cls._SECRETKEY, digestmod=hashlib.sha256)
114 h.update(nonce)
115 tmp = h.digest()
116
117 def mix_tmp(count):
118 nonlocal tmp
119 for i in range(count):
120 mix_once(tmp)
121
122 def mix_twist(nonce):
123 nonlocal tmp
124 mix_once(base64.urlsafe_b64encode(tmp).rstrip(b'=') + nonce)
125
126 mix_once(cls._SECRETKEY)
127 mix_tmp(time_struct.tm_mon)
128 mix_twist(deviceid)
129 mix_tmp(time_struct.tm_mday % 5)
130 mix_twist(ts_1hour_str)
131 mix_tmp(time_struct.tm_hour % 5)
132
133 return base64.urlsafe_b64encode(tmp).rstrip(b'=').decode('utf-8')
134
135 def _get_device_token(self):
136 if self._USERTOKEN:
137 return self._USERTOKEN
138
139 username, _ = self._get_login_info()
140 AbemaTVBaseIE._USERTOKEN = username and self.cache.load(self._NETRC_MACHINE, username)
141 if AbemaTVBaseIE._USERTOKEN:
142 # try authentication with locally stored token
143 try:
144 self._get_media_token(True)
145 return
146 except ExtractorError as e:
147 self.report_warning(f'Failed to login with cached user token; obtaining a fresh one ({e})')
148
149 AbemaTVBaseIE._DEVICE_ID = str(uuid.uuid4())
150 aks = self._generate_aks(self._DEVICE_ID)
151 user_data = self._download_json(
152 'https://api.abema.io/v1/users', None, note='Authorizing',
153 data=json.dumps({
154 'deviceId': self._DEVICE_ID,
155 'applicationKeySecret': aks,
156 }).encode('utf-8'),
157 headers={
158 'Content-Type': 'application/json',
159 })
160 AbemaTVBaseIE._USERTOKEN = user_data['token']
161
162 add_opener(self._downloader, AbemaLicenseHandler(self))
163 return self._USERTOKEN
164
165 def _get_media_token(self, invalidate=False, to_show=True):
166 if not invalidate and self._MEDIATOKEN:
167 return self._MEDIATOKEN
168
169 AbemaTVBaseIE._MEDIATOKEN = self._download_json(
170 'https://api.abema.io/v1/media/token', None, note='Fetching media token' if to_show else False,
171 query={
172 'osName': 'android',
173 'osVersion': '6.0.1',
174 'osLang': 'ja_JP',
175 'osTimezone': 'Asia/Tokyo',
176 'appId': 'tv.abema',
177 'appVersion': '3.27.1'
178 }, headers={
179 'Authorization': f'bearer {self._get_device_token()}',
180 })['token']
181
182 return self._MEDIATOKEN
183
184 def _call_api(self, endpoint, video_id, query=None, note='Downloading JSON metadata'):
185 return self._download_json(
186 f'https://api.abema.io/{endpoint}', video_id, query=query or {},
187 note=note,
188 headers={
189 'Authorization': f'bearer {self._get_device_token()}',
190 })
191
192 def _extract_breadcrumb_list(self, webpage, video_id):
193 for jld in re.finditer(
194 r'(?is)</span></li></ul><script[^>]+type=(["\']?)application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>',
195 webpage):
196 jsonld = self._parse_json(jld.group('json_ld'), video_id, fatal=False)
197 if traverse_obj(jsonld, '@type') != 'BreadcrumbList':
198 continue
199 items = traverse_obj(jsonld, ('itemListElement', ..., 'name'))
200 if items:
201 return items
202 return []
203
204
205 class AbemaTVIE(AbemaTVBaseIE):
206 _VALID_URL = r'https?://abema\.tv/(?P<type>now-on-air|video/episode|channels/.+?/slots)/(?P<id>[^?/]+)'
207 _NETRC_MACHINE = 'abematv'
208 _TESTS = [{
209 'url': 'https://abema.tv/video/episode/194-25_s2_p1',
210 'info_dict': {
211 'id': '194-25_s2_p1',
212 'title': '1話 「チーズケーキ」 「モーニング再び」',
213 'series': '異世界食堂2',
214 'season': 'シーズン2',
215 'season_number': 2,
216 'episode': '1話 「チーズケーキ」 「モーニング再び」',
217 'episode_number': 1,
218 },
219 'skip': 'expired',
220 }, {
221 'url': 'https://abema.tv/channels/anime-live2/slots/E8tvAnMJ7a9a5d',
222 'info_dict': {
223 'id': 'E8tvAnMJ7a9a5d',
224 'title': 'ゆるキャン△ SEASON2 全話一挙【無料ビデオ72時間】',
225 'series': 'ゆるキャン△ SEASON2',
226 'episode': 'ゆるキャン△ SEASON2 全話一挙【無料ビデオ72時間】',
227 'series_number': 2,
228 'episode_number': 1,
229 'description': 'md5:9c5a3172ae763278f9303922f0ea5b17',
230 },
231 'skip': 'expired',
232 }, {
233 'url': 'https://abema.tv/video/episode/87-877_s1282_p31047',
234 'info_dict': {
235 'id': 'E8tvAnMJ7a9a5d',
236 'title': '5話『光射す』',
237 'description': 'md5:56d4fc1b4f7769ded5f923c55bb4695d',
238 'thumbnail': r're:https://hayabusa\.io/.+',
239 'series': '相棒',
240 'episode': '5話『光射す』',
241 },
242 'skip': 'expired',
243 }, {
244 'url': 'https://abema.tv/now-on-air/abema-anime',
245 'info_dict': {
246 'id': 'abema-anime',
247 # this varies
248 # 'title': '女子高生の無駄づかい 全話一挙【無料ビデオ72時間】',
249 'description': 'md5:55f2e61f46a17e9230802d7bcc913d5f',
250 'is_live': True,
251 },
252 'skip': 'Not supported until yt-dlp implements native live downloader OR AbemaTV can start a local HTTP server',
253 }]
254 _TIMETABLE = None
255
256 def _perform_login(self, username, password):
257 self._get_device_token()
258 if self.cache.load(self._NETRC_MACHINE, username) and self._get_media_token():
259 self.write_debug('Skipping logging in')
260 return
261
262 if '@' in username: # don't strictly check if it's email address or not
263 ep, method = 'user/email', 'email'
264 else:
265 ep, method = 'oneTimePassword', 'userId'
266
267 login_response = self._download_json(
268 f'https://api.abema.io/v1/auth/{ep}', None, note='Logging in',
269 data=json.dumps({
270 method: username,
271 'password': password
272 }).encode('utf-8'), headers={
273 'Authorization': f'bearer {self._get_device_token()}',
274 'Origin': 'https://abema.tv',
275 'Referer': 'https://abema.tv/',
276 'Content-Type': 'application/json',
277 })
278
279 AbemaTVBaseIE._USERTOKEN = login_response['token']
280 self._get_media_token(True)
281 self.cache.store(self._NETRC_MACHINE, username, AbemaTVBaseIE._USERTOKEN)
282
283 def _real_extract(self, url):
284 # starting download using infojson from this extractor is undefined behavior,
285 # and never be fixed in the future; you must trigger downloads by directly specifying URL.
286 # (unless there's a way to hook before downloading by extractor)
287 video_id, video_type = self._match_valid_url(url).group('id', 'type')
288 headers = {
289 'Authorization': 'Bearer ' + self._get_device_token(),
290 }
291 video_type = video_type.split('/')[-1]
292
293 webpage = self._download_webpage(url, video_id)
294 canonical_url = self._search_regex(
295 r'<link\s+rel="canonical"\s*href="(.+?)"', webpage, 'canonical URL',
296 default=url)
297 info = self._search_json_ld(webpage, video_id, default={})
298
299 title = self._search_regex(
300 r'<span\s*class=".+?EpisodeTitleBlock__title">(.+?)</span>', webpage, 'title', default=None)
301 if not title:
302 jsonld = None
303 for jld in re.finditer(
304 r'(?is)<span\s*class="com-m-Thumbnail__image">(?:</span>)?<script[^>]+type=(["\']?)application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>',
305 webpage):
306 jsonld = self._parse_json(jld.group('json_ld'), video_id, fatal=False)
307 if jsonld:
308 break
309 if jsonld:
310 title = jsonld.get('caption')
311 if not title and video_type == 'now-on-air':
312 if not self._TIMETABLE:
313 # cache the timetable because it goes to 5MiB in size (!!)
314 self._TIMETABLE = self._download_json(
315 'https://api.abema.io/v1/timetable/dataSet?debug=false', video_id,
316 headers=headers)
317 now = time_seconds(hours=9)
318 for slot in self._TIMETABLE.get('slots', []):
319 if slot.get('channelId') != video_id:
320 continue
321 if slot['startAt'] <= now and now < slot['endAt']:
322 title = slot['title']
323 break
324
325 # read breadcrumb on top of page
326 breadcrumb = self._extract_breadcrumb_list(webpage, video_id)
327 if breadcrumb:
328 # breadcrumb list translates to: (e.g. 1st test for this IE)
329 # Home > Anime (genre) > Isekai Shokudo 2 (series name) > Episode 1 "Cheese cakes" "Morning again" (episode title)
330 # hence this works
331 info['series'] = breadcrumb[-2]
332 info['episode'] = breadcrumb[-1]
333 if not title:
334 title = info['episode']
335
336 description = self._html_search_regex(
337 (r'<p\s+class="com-video-EpisodeDetailsBlock__content"><span\s+class=".+?">(.+?)</span></p><div',
338 r'<span\s+class=".+?SlotSummary.+?">(.+?)</span></div><div',),
339 webpage, 'description', default=None, group=1)
340 if not description:
341 og_desc = self._html_search_meta(
342 ('description', 'og:description', 'twitter:description'), webpage)
343 if og_desc:
344 description = re.sub(r'''(?sx)
345 ^(.+?)(?:
346 アニメの動画を無料で見るならABEMA!| # anime
347 等、.+ # applies for most of categories
348 )?
349 ''', r'\1', og_desc)
350
351 # canonical URL may contain season and episode number
352 mobj = re.search(r's(\d+)_p(\d+)$', canonical_url)
353 if mobj:
354 seri = int_or_none(mobj.group(1), default=float('inf'))
355 epis = int_or_none(mobj.group(2), default=float('inf'))
356 info['season_number'] = seri if seri < 100 else None
357 # some anime like Detective Conan (though not available in AbemaTV)
358 # has more than 1000 episodes (1026 as of 2021/11/15)
359 info['episode_number'] = epis if epis < 2000 else None
360
361 is_live, m3u8_url = False, None
362 if video_type == 'now-on-air':
363 is_live = True
364 channel_url = 'https://api.abema.io/v1/channels'
365 if video_id == 'news-global':
366 channel_url = update_url_query(channel_url, {'division': '1'})
367 onair_channels = self._download_json(channel_url, video_id)
368 for ch in onair_channels['channels']:
369 if video_id == ch['id']:
370 m3u8_url = ch['playback']['hls']
371 break
372 else:
373 raise ExtractorError(f'Cannot find on-air {video_id} channel.', expected=True)
374 elif video_type == 'episode':
375 api_response = self._download_json(
376 f'https://api.abema.io/v1/video/programs/{video_id}', video_id,
377 note='Checking playability',
378 headers=headers)
379 ondemand_types = traverse_obj(api_response, ('terms', ..., 'onDemandType'))
380 if 3 not in ondemand_types:
381 # cannot acquire decryption key for these streams
382 self.report_warning('This is a premium-only stream')
383 info.update(traverse_obj(api_response, {
384 'series': ('series', 'title'),
385 'season': ('season', 'name'),
386 'season_number': ('season', 'sequence'),
387 'episode_number': ('episode', 'number'),
388 }))
389 if not title:
390 title = traverse_obj(api_response, ('episode', 'title'))
391 if not description:
392 description = traverse_obj(api_response, ('episode', 'content'))
393
394 m3u8_url = f'https://vod-abematv.akamaized.net/program/{video_id}/playlist.m3u8'
395 elif video_type == 'slots':
396 api_response = self._download_json(
397 f'https://api.abema.io/v1/media/slots/{video_id}', video_id,
398 note='Checking playability',
399 headers=headers)
400 if not traverse_obj(api_response, ('slot', 'flags', 'timeshiftFree'), default=False):
401 self.report_warning('This is a premium-only stream')
402
403 m3u8_url = f'https://vod-abematv.akamaized.net/slot/{video_id}/playlist.m3u8'
404 else:
405 raise ExtractorError('Unreachable')
406
407 if is_live:
408 self.report_warning("This is a livestream; yt-dlp doesn't support downloading natively, but FFmpeg cannot handle m3u8 manifests from AbemaTV")
409 self.report_warning('Please consider using Streamlink to download these streams (https://github.com/streamlink/streamlink)')
410 formats = self._extract_m3u8_formats(
411 m3u8_url, video_id, ext='mp4', live=is_live)
412
413 info.update({
414 'id': video_id,
415 'title': title,
416 'description': description,
417 'formats': formats,
418 'is_live': is_live,
419 })
420 return info
421
422
423 class AbemaTVTitleIE(AbemaTVBaseIE):
424 _VALID_URL = r'https?://abema\.tv/video/title/(?P<id>[^?/]+)'
425 _PAGE_SIZE = 25
426
427 _TESTS = [{
428 'url': 'https://abema.tv/video/title/90-1597',
429 'info_dict': {
430 'id': '90-1597',
431 'title': 'シャッフルアイランド',
432 },
433 'playlist_mincount': 2,
434 }, {
435 'url': 'https://abema.tv/video/title/193-132',
436 'info_dict': {
437 'id': '193-132',
438 'title': '真心が届く~僕とスターのオフィス・ラブ!?~',
439 },
440 'playlist_mincount': 16,
441 }, {
442 'url': 'https://abema.tv/video/title/25-102',
443 'info_dict': {
444 'id': '25-102',
445 'title': 'ソードアート・オンライン アリシゼーション',
446 },
447 'playlist_mincount': 24,
448 }]
449
450 def _fetch_page(self, playlist_id, series_version, page):
451 programs = self._call_api(
452 f'v1/video/series/{playlist_id}/programs', playlist_id,
453 note=f'Downloading page {page + 1}',
454 query={
455 'seriesVersion': series_version,
456 'offset': str(page * self._PAGE_SIZE),
457 'order': 'seq',
458 'limit': str(self._PAGE_SIZE),
459 })
460 yield from (
461 self.url_result(f'https://abema.tv/video/episode/{x}')
462 for x in traverse_obj(programs, ('programs', ..., 'id')))
463
464 def _entries(self, playlist_id, series_version):
465 return OnDemandPagedList(
466 functools.partial(self._fetch_page, playlist_id, series_version),
467 self._PAGE_SIZE)
468
469 def _real_extract(self, url):
470 playlist_id = self._match_id(url)
471 series_info = self._call_api(f'v1/video/series/{playlist_id}', playlist_id)
472
473 return self.playlist_result(
474 self._entries(playlist_id, series_info['version']), playlist_id=playlist_id,
475 playlist_title=series_info.get('title'),
476 playlist_description=series_info.get('content'))