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