]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/adn.py
[ie/adn] Add support for German site (#8708)
[yt-dlp.git] / yt_dlp / extractor / adn.py
CommitLineData
1ea559c4
RA
1import base64
2import binascii
82be732b
RA
3import json
4import os
1ea559c4 5import random
82be732b
RA
6
7from .common import InfoExtractor
1d3586d0 8from ..aes import aes_cbc_decrypt_bytes, unpad_pkcs7
3d2623a8 9from ..compat import compat_b64decode
10from ..networking.exceptions import HTTPError
82be732b 11from ..utils import (
aa7785f8 12 ass_subtitles_timecode,
82be732b 13 bytes_to_intlist,
1ea559c4 14 bytes_to_long,
82be732b
RA
15 ExtractorError,
16 float_or_none,
30a074c2 17 int_or_none,
82be732b 18 intlist_to_bytes,
1ea559c4
RA
19 long_to_bytes,
20 pkcs1pad,
82be732b 21 strip_or_none,
5eb1458b 22 str_or_none,
30a074c2 23 try_get,
24 unified_strdate,
2181983a 25 urlencode_postdata,
82be732b 26)
5eb1458b 27from ..utils.traversal import traverse_obj
82be732b
RA
28
29
5eb1458b 30class ADNBaseIE(InfoExtractor):
db4678e4 31 IE_DESC = 'Animation Digital Network'
5eb1458b
CS
32 _NETRC_MACHINE = 'animationdigitalnetwork'
33 _BASE = 'animationdigitalnetwork.fr'
34 _API_BASE_URL = f'https://gw.api.{_BASE}/'
35 _PLAYER_BASE_URL = f'{_API_BASE_URL}player/'
36 _HEADERS = {}
37 _LOGIN_ERR_MESSAGE = 'Unable to log in'
38 _RSA_KEY = (0x9B42B08905199A5CCE2026274399CA560ECB209EE9878A708B1C0812E1BB8CB5D1FB7441861147C1A1F2F3A0476DD63A9CAC20D3E983613346850AA6CB38F16DC7D720FD7D86FC6E5B3D5BBC72E14CD0BF9E869F2CEA2CCAD648F1DCE38F1FF916CEFB2D339B64AA0264372344BC775E265E8A852F88144AB0BD9AA06C1A4ABB, 65537)
39 _POS_ALIGN_MAP = {
40 'start': 1,
41 'end': 3,
42 }
43 _LINE_ALIGN_MAP = {
44 'middle': 8,
45 'end': 4,
46 }
47
48
49class ADNIE(ADNBaseIE):
50 _VALID_URL = r'https?://(?:www\.)?(?:animation|anime)digitalnetwork\.(?P<lang>fr|de)/video/[^/?#]+/(?P<id>\d+)'
db4678e4 51 _TESTS = [{
52 'url': 'https://animationdigitalnetwork.fr/video/fruits-basket/9841-episode-1-a-ce-soir',
53 'md5': '1c9ef066ceb302c86f80c2b371615261',
82be732b 54 'info_dict': {
db4678e4 55 'id': '9841',
82be732b 56 'ext': 'mp4',
db4678e4 57 'title': 'Fruits Basket - Episode 1',
58 'description': 'md5:14be2f72c3c96809b0ca424b0097d336',
59 'series': 'Fruits Basket',
60 'duration': 1437,
61 'release_date': '20190405',
30a074c2 62 'comment_count': int,
63 'average_rating': float,
db4678e4 64 'season_number': 1,
65 'episode': 'À ce soir !',
30a074c2 66 'episode_number': 1,
5eb1458b
CS
67 'thumbnail': str,
68 'season': 'Season 1',
db4678e4 69 },
5eb1458b 70 'skip': 'Only available in French and German speaking Europe',
db4678e4 71 }, {
72 'url': 'http://animedigitalnetwork.fr/video/blue-exorcist-kyoto-saga/7778-episode-1-debut-des-hostilites',
73 'only_matching': True,
5eb1458b
CS
74 }, {
75 'url': 'https://animationdigitalnetwork.de/video/the-eminence-in-shadow/23550-folge-1',
76 'md5': '5c5651bf5791fa6fcd7906012b9d94e8',
77 'info_dict': {
78 'id': '23550',
79 'ext': 'mp4',
80 'episode_number': 1,
81 'duration': 1417,
82 'release_date': '20231004',
83 'series': 'The Eminence in Shadow',
84 'season_number': 2,
85 'episode': str,
86 'title': str,
87 'thumbnail': str,
88 'season': 'Season 2',
89 'comment_count': int,
90 'average_rating': float,
91 'description': str,
92 },
93 # 'skip': 'Only available in French and German speaking Europe',
db4678e4 94 }]
30a074c2 95
30a074c2 96 def _get_subtitles(self, sub_url, video_id):
97 if not sub_url:
82be732b
RA
98 return None
99
100 enc_subtitles = self._download_webpage(
30a074c2 101 sub_url, video_id, 'Downloading subtitles location', fatal=False) or '{}'
e6c9ae31
RA
102 subtitle_location = (self._parse_json(enc_subtitles, video_id, fatal=False) or {}).get('location')
103 if subtitle_location:
104 enc_subtitles = self._download_webpage(
30a074c2 105 subtitle_location, video_id, 'Downloading subtitles data',
db4678e4 106 fatal=False, headers={'Origin': 'https://' + self._BASE})
82be732b
RA
107 if not enc_subtitles:
108 return None
109
db4678e4 110 # http://animationdigitalnetwork.fr/components/com_vodvideo/videojs/adn-vjs.min.js
1d3586d0 111 dec_subtitles = unpad_pkcs7(aes_cbc_decrypt_bytes(
112 compat_b64decode(enc_subtitles[24:]),
3358f893 113 binascii.unhexlify(self._K + '7fac1178830cfe0c'),
1d3586d0 114 compat_b64decode(enc_subtitles[:24])))
115 subtitles_json = self._parse_json(dec_subtitles.decode(), None, fatal=False)
82be732b
RA
116 if not subtitles_json:
117 return None
118
119 subtitles = {}
120 for sub_lang, sub in subtitles_json.items():
b966740c
RA
121 ssa = '''[Script Info]
122ScriptType:V4.00
123[V4 Styles]
2bbde1d0
RA
124Format: Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,TertiaryColour,BackColour,Bold,Italic,BorderStyle,Outline,Shadow,Alignment,MarginL,MarginR,MarginV,AlphaLevel,Encoding
125Style: Default,Arial,18,16777215,16777215,16777215,0,-1,0,1,1,0,2,20,20,20,0,0
b966740c 126[Events]
2bbde1d0 127Format: Marked,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text'''
b966740c
RA
128 for current in sub:
129 start, end, text, line_align, position_align = (
82be732b
RA
130 float_or_none(current.get('startTime')),
131 float_or_none(current.get('endTime')),
b966740c
RA
132 current.get('text'), current.get('lineAlign'),
133 current.get('positionAlign'))
82be732b
RA
134 if start is None or end is None or text is None:
135 continue
b966740c 136 alignment = self._POS_ALIGN_MAP.get(position_align, 2) + self._LINE_ALIGN_MAP.get(line_align, 0)
2bbde1d0 137 ssa += os.linesep + 'Dialogue: Marked=0,%s,%s,Default,,0,0,0,,%s%s' % (
aa7785f8 138 ass_subtitles_timecode(start),
139 ass_subtitles_timecode(end),
b966740c
RA
140 '{\\a%d}' % alignment if alignment != 2 else '',
141 text.replace('\n', '\\N').replace('<i>', '{\\i1}').replace('</i>', '{\\i0}'))
82be732b
RA
142
143 if sub_lang == 'vostf':
144 sub_lang = 'fr'
5eb1458b
CS
145 elif sub_lang == 'vostde':
146 sub_lang = 'de'
82be732b
RA
147 subtitles.setdefault(sub_lang, []).extend([{
148 'ext': 'json',
149 'data': json.dumps(sub),
150 }, {
b966740c
RA
151 'ext': 'ssa',
152 'data': ssa,
82be732b
RA
153 }])
154 return subtitles
155
52efa4b3 156 def _perform_login(self, username, password):
2181983a 157 try:
158 access_token = (self._download_json(
159 self._API_BASE_URL + 'authentication/login', None,
160 'Logging in', self._LOGIN_ERR_MESSAGE, fatal=False,
161 data=urlencode_postdata({
162 'password': password,
163 'rememberMe': False,
164 'source': 'Web',
165 'username': username,
166 })) or {}).get('accessToken')
167 if access_token:
168 self._HEADERS = {'authorization': 'Bearer ' + access_token}
169 except ExtractorError as e:
170 message = None
3d2623a8 171 if isinstance(e.cause, HTTPError) and e.cause.status == 401:
2181983a 172 resp = self._parse_json(
3d2623a8 173 e.cause.response.read().decode(), None, fatal=False) or {}
2181983a 174 message = resp.get('message') or resp.get('code')
175 self.report_warning(message or self._LOGIN_ERR_MESSAGE)
176
82be732b 177 def _real_extract(self, url):
5eb1458b 178 lang, video_id = self._match_valid_url(url).group('lang', 'id')
30a074c2 179 video_base_url = self._PLAYER_BASE_URL + 'video/%s/' % video_id
180 player = self._download_json(
181 video_base_url + 'configuration', video_id,
2181983a 182 'Downloading player config JSON metadata',
183 headers=self._HEADERS)['player']
30a074c2 184 options = player['options']
185
186 user = options['user']
187 if not user.get('hasAccess'):
2181983a 188 self.raise_login_required()
30a074c2 189
190 token = self._download_json(
191 user.get('refreshTokenUrl') or (self._PLAYER_BASE_URL + 'refresh/token'),
192 video_id, 'Downloading access token', headers={
5eb1458b 193 'X-Player-Refresh-Token': user['refreshToken'],
30a074c2 194 }, data=b'')['token']
195
196 links_url = try_get(options, lambda x: x['video']['url']) or (video_base_url + 'link')
efa944f4 197 self._K = ''.join(random.choices('0123456789abcdef', k=16))
30a074c2 198 message = bytes_to_intlist(json.dumps({
199 'k': self._K,
200 't': token,
201 }))
202
203 # Sometimes authentication fails for no good reason, retry with
204 # a different random padding
205 links_data = None
206 for _ in range(3):
1ea559c4
RA
207 padded_message = intlist_to_bytes(pkcs1pad(message, 128))
208 n, e = self._RSA_KEY
209 encrypted_message = long_to_bytes(pow(bytes_to_long(padded_message), e, n))
210 authorization = base64.b64encode(encrypted_message).decode()
30a074c2 211
212 try:
213 links_data = self._download_json(
214 links_url, video_id, 'Downloading links JSON metadata', headers={
5eb1458b
CS
215 'X-Player-Token': authorization,
216 'X-Target-Distribution': lang,
217 **self._HEADERS
30a074c2 218 }, query={
219 'freeWithAds': 'true',
220 'adaptive': 'false',
221 'withMetadata': 'true',
222 'source': 'Web'
223 })
224 break
225 except ExtractorError as e:
3d2623a8 226 if not isinstance(e.cause, HTTPError):
30a074c2 227 raise e
228
3d2623a8 229 if e.cause.status == 401:
30a074c2 230 # This usually goes away with a different random pkcs1pad, so retry
231 continue
232
3d2623a8 233 error = self._parse_json(e.cause.response.read(), video_id)
30a074c2 234 message = error.get('message')
235 if e.cause.code == 403 and error.get('code') == 'player-bad-geolocation-country':
236 self.raise_geo_restricted(msg=message)
2181983a 237 raise ExtractorError(message)
30a074c2 238 else:
239 raise ExtractorError('Giving up retrying')
240
241 links = links_data.get('links') or {}
242 metas = links_data.get('metadata') or {}
243 sub_url = (links.get('subtitles') or {}).get('all')
244 video_info = links_data.get('video') or {}
245 title = metas['title']
82be732b
RA
246
247 formats = []
30a074c2 248 for format_id, qualities in (links.get('streaming') or {}).items():
20e2c9de
RA
249 if not isinstance(qualities, dict):
250 continue
b966740c 251 for quality, load_balancer_url in qualities.items():
82be732b 252 load_balancer_data = self._download_json(
b966740c
RA
253 load_balancer_url, video_id,
254 'Downloading %s %s JSON metadata' % (format_id, quality),
255 fatal=False) or {}
82be732b
RA
256 m3u8_url = load_balancer_data.get('location')
257 if not m3u8_url:
258 continue
259 m3u8_formats = self._extract_m3u8_formats(
260 m3u8_url, video_id, 'mp4', 'm3u8_native',
261 m3u8_id=format_id, fatal=False)
262 if format_id == 'vf':
263 for f in m3u8_formats:
264 f['language'] = 'fr'
5eb1458b
CS
265 elif format_id == 'vde':
266 for f in m3u8_formats:
267 f['language'] = 'de'
82be732b 268 formats.extend(m3u8_formats)
82be732b 269
30a074c2 270 video = (self._download_json(
271 self._API_BASE_URL + 'video/%s' % video_id, video_id,
272 'Downloading additional video metadata', fatal=False) or {}).get('video') or {}
273 show = video.get('show') or {}
274
82be732b
RA
275 return {
276 'id': video_id,
277 'title': title,
30a074c2 278 'description': strip_or_none(metas.get('summary') or video.get('summary')),
279 'thumbnail': video_info.get('image') or player.get('image'),
82be732b 280 'formats': formats,
30a074c2 281 'subtitles': self.extract_subtitles(sub_url, video_id),
282 'episode': metas.get('subtitle') or video.get('name'),
283 'episode_number': int_or_none(video.get('shortNumber')),
284 'series': show.get('title'),
285 'season_number': int_or_none(video.get('season')),
286 'duration': int_or_none(video_info.get('duration') or video.get('duration')),
287 'release_date': unified_strdate(video.get('releaseDate')),
288 'average_rating': float_or_none(video.get('rating') or metas.get('rating')),
289 'comment_count': int_or_none(video.get('commentsCount')),
82be732b 290 }
5eb1458b
CS
291
292
293class ADNSeasonIE(ADNBaseIE):
294 _VALID_URL = r'https?://(?:www\.)?(?:animation|anime)digitalnetwork\.(?P<lang>fr|de)/video/(?P<id>[^/?#]+)/?(?:$|[#?])'
295 _TESTS = [{
296 'url': 'https://animationdigitalnetwork.fr/video/tokyo-mew-mew-new',
297 'playlist_count': 12,
298 'info_dict': {
299 'id': '911',
300 'title': 'Tokyo Mew Mew New',
301 },
302 # 'skip': 'Only available in French end German speaking Europe',
303 }]
304
305 def _real_extract(self, url):
306 lang, video_show_slug = self._match_valid_url(url).group('lang', 'id')
307 show = self._download_json(
308 f'{self._API_BASE_URL}show/{video_show_slug}/', video_show_slug,
309 'Downloading show JSON metadata', headers=self._HEADERS)['show']
310 show_id = str(show['id'])
311 episodes = self._download_json(
312 f'{self._API_BASE_URL}video/show/{show_id}', video_show_slug,
313 'Downloading episode list', headers={
314 'X-Target-Distribution': lang,
315 **self._HEADERS
316 }, query={
317 'order': 'asc',
318 'limit': '-1',
319 })
320
321 def entries():
322 for episode_id in traverse_obj(episodes, ('videos', ..., 'id', {str_or_none})):
323 yield self.url_result(
324 f'https://animationdigitalnetwork.{lang}/video/{video_show_slug}/{episode_id}',
325 ADNIE, episode_id)
326
327 return self.playlist_result(entries(), show_id, show.get('title'))