]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/adn.py
[extractor] Deprecate `_sort_formats`
[yt-dlp.git] / yt_dlp / extractor / adn.py
1 import base64
2 import binascii
3 import json
4 import os
5 import random
6
7 from .common import InfoExtractor
8 from ..aes import aes_cbc_decrypt_bytes, unpad_pkcs7
9 from ..compat import (
10 compat_HTTPError,
11 compat_b64decode,
12 )
13 from ..utils import (
14 ass_subtitles_timecode,
15 bytes_to_intlist,
16 bytes_to_long,
17 ExtractorError,
18 float_or_none,
19 int_or_none,
20 intlist_to_bytes,
21 long_to_bytes,
22 pkcs1pad,
23 strip_or_none,
24 try_get,
25 unified_strdate,
26 urlencode_postdata,
27 )
28
29
30 class ADNIE(InfoExtractor):
31 IE_DESC = 'Animation Digital Network'
32 _VALID_URL = r'https?://(?:www\.)?(?:animation|anime)digitalnetwork\.fr/video/[^/]+/(?P<id>\d+)'
33 _TESTS = [{
34 'url': 'https://animationdigitalnetwork.fr/video/fruits-basket/9841-episode-1-a-ce-soir',
35 'md5': '1c9ef066ceb302c86f80c2b371615261',
36 'info_dict': {
37 'id': '9841',
38 'ext': 'mp4',
39 'title': 'Fruits Basket - Episode 1',
40 'description': 'md5:14be2f72c3c96809b0ca424b0097d336',
41 'series': 'Fruits Basket',
42 'duration': 1437,
43 'release_date': '20190405',
44 'comment_count': int,
45 'average_rating': float,
46 'season_number': 1,
47 'episode': 'À ce soir !',
48 'episode_number': 1,
49 },
50 'skip': 'Only available in region (FR, ...)',
51 }, {
52 'url': 'http://animedigitalnetwork.fr/video/blue-exorcist-kyoto-saga/7778-episode-1-debut-des-hostilites',
53 'only_matching': True,
54 }]
55
56 _NETRC_MACHINE = 'animationdigitalnetwork'
57 _BASE = 'animationdigitalnetwork.fr'
58 _API_BASE_URL = 'https://gw.api.' + _BASE + '/'
59 _PLAYER_BASE_URL = _API_BASE_URL + 'player/'
60 _HEADERS = {}
61 _LOGIN_ERR_MESSAGE = 'Unable to log in'
62 _RSA_KEY = (0x9B42B08905199A5CCE2026274399CA560ECB209EE9878A708B1C0812E1BB8CB5D1FB7441861147C1A1F2F3A0476DD63A9CAC20D3E983613346850AA6CB38F16DC7D720FD7D86FC6E5B3D5BBC72E14CD0BF9E869F2CEA2CCAD648F1DCE38F1FF916CEFB2D339B64AA0264372344BC775E265E8A852F88144AB0BD9AA06C1A4ABB, 65537)
63 _POS_ALIGN_MAP = {
64 'start': 1,
65 'end': 3,
66 }
67 _LINE_ALIGN_MAP = {
68 'middle': 8,
69 'end': 4,
70 }
71
72 def _get_subtitles(self, sub_url, video_id):
73 if not sub_url:
74 return None
75
76 enc_subtitles = self._download_webpage(
77 sub_url, video_id, 'Downloading subtitles location', fatal=False) or '{}'
78 subtitle_location = (self._parse_json(enc_subtitles, video_id, fatal=False) or {}).get('location')
79 if subtitle_location:
80 enc_subtitles = self._download_webpage(
81 subtitle_location, video_id, 'Downloading subtitles data',
82 fatal=False, headers={'Origin': 'https://' + self._BASE})
83 if not enc_subtitles:
84 return None
85
86 # http://animationdigitalnetwork.fr/components/com_vodvideo/videojs/adn-vjs.min.js
87 dec_subtitles = unpad_pkcs7(aes_cbc_decrypt_bytes(
88 compat_b64decode(enc_subtitles[24:]),
89 binascii.unhexlify(self._K + '7fac1178830cfe0c'),
90 compat_b64decode(enc_subtitles[:24])))
91 subtitles_json = self._parse_json(dec_subtitles.decode(), None, fatal=False)
92 if not subtitles_json:
93 return None
94
95 subtitles = {}
96 for sub_lang, sub in subtitles_json.items():
97 ssa = '''[Script Info]
98 ScriptType:V4.00
99 [V4 Styles]
100 Format: Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,TertiaryColour,BackColour,Bold,Italic,BorderStyle,Outline,Shadow,Alignment,MarginL,MarginR,MarginV,AlphaLevel,Encoding
101 Style: Default,Arial,18,16777215,16777215,16777215,0,-1,0,1,1,0,2,20,20,20,0,0
102 [Events]
103 Format: Marked,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text'''
104 for current in sub:
105 start, end, text, line_align, position_align = (
106 float_or_none(current.get('startTime')),
107 float_or_none(current.get('endTime')),
108 current.get('text'), current.get('lineAlign'),
109 current.get('positionAlign'))
110 if start is None or end is None or text is None:
111 continue
112 alignment = self._POS_ALIGN_MAP.get(position_align, 2) + self._LINE_ALIGN_MAP.get(line_align, 0)
113 ssa += os.linesep + 'Dialogue: Marked=0,%s,%s,Default,,0,0,0,,%s%s' % (
114 ass_subtitles_timecode(start),
115 ass_subtitles_timecode(end),
116 '{\\a%d}' % alignment if alignment != 2 else '',
117 text.replace('\n', '\\N').replace('<i>', '{\\i1}').replace('</i>', '{\\i0}'))
118
119 if sub_lang == 'vostf':
120 sub_lang = 'fr'
121 subtitles.setdefault(sub_lang, []).extend([{
122 'ext': 'json',
123 'data': json.dumps(sub),
124 }, {
125 'ext': 'ssa',
126 'data': ssa,
127 }])
128 return subtitles
129
130 def _perform_login(self, username, password):
131 try:
132 access_token = (self._download_json(
133 self._API_BASE_URL + 'authentication/login', None,
134 'Logging in', self._LOGIN_ERR_MESSAGE, fatal=False,
135 data=urlencode_postdata({
136 'password': password,
137 'rememberMe': False,
138 'source': 'Web',
139 'username': username,
140 })) or {}).get('accessToken')
141 if access_token:
142 self._HEADERS = {'authorization': 'Bearer ' + access_token}
143 except ExtractorError as e:
144 message = None
145 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401:
146 resp = self._parse_json(
147 e.cause.read().decode(), None, fatal=False) or {}
148 message = resp.get('message') or resp.get('code')
149 self.report_warning(message or self._LOGIN_ERR_MESSAGE)
150
151 def _real_extract(self, url):
152 video_id = self._match_id(url)
153 video_base_url = self._PLAYER_BASE_URL + 'video/%s/' % video_id
154 player = self._download_json(
155 video_base_url + 'configuration', video_id,
156 'Downloading player config JSON metadata',
157 headers=self._HEADERS)['player']
158 options = player['options']
159
160 user = options['user']
161 if not user.get('hasAccess'):
162 self.raise_login_required()
163
164 token = self._download_json(
165 user.get('refreshTokenUrl') or (self._PLAYER_BASE_URL + 'refresh/token'),
166 video_id, 'Downloading access token', headers={
167 'x-player-refresh-token': user['refreshToken']
168 }, data=b'')['token']
169
170 links_url = try_get(options, lambda x: x['video']['url']) or (video_base_url + 'link')
171 self._K = ''.join([random.choice('0123456789abcdef') for _ in range(16)])
172 message = bytes_to_intlist(json.dumps({
173 'k': self._K,
174 't': token,
175 }))
176
177 # Sometimes authentication fails for no good reason, retry with
178 # a different random padding
179 links_data = None
180 for _ in range(3):
181 padded_message = intlist_to_bytes(pkcs1pad(message, 128))
182 n, e = self._RSA_KEY
183 encrypted_message = long_to_bytes(pow(bytes_to_long(padded_message), e, n))
184 authorization = base64.b64encode(encrypted_message).decode()
185
186 try:
187 links_data = self._download_json(
188 links_url, video_id, 'Downloading links JSON metadata', headers={
189 'X-Player-Token': authorization
190 }, query={
191 'freeWithAds': 'true',
192 'adaptive': 'false',
193 'withMetadata': 'true',
194 'source': 'Web'
195 })
196 break
197 except ExtractorError as e:
198 if not isinstance(e.cause, compat_HTTPError):
199 raise e
200
201 if e.cause.code == 401:
202 # This usually goes away with a different random pkcs1pad, so retry
203 continue
204
205 error = self._parse_json(e.cause.read(), video_id)
206 message = error.get('message')
207 if e.cause.code == 403 and error.get('code') == 'player-bad-geolocation-country':
208 self.raise_geo_restricted(msg=message)
209 raise ExtractorError(message)
210 else:
211 raise ExtractorError('Giving up retrying')
212
213 links = links_data.get('links') or {}
214 metas = links_data.get('metadata') or {}
215 sub_url = (links.get('subtitles') or {}).get('all')
216 video_info = links_data.get('video') or {}
217 title = metas['title']
218
219 formats = []
220 for format_id, qualities in (links.get('streaming') or {}).items():
221 if not isinstance(qualities, dict):
222 continue
223 for quality, load_balancer_url in qualities.items():
224 load_balancer_data = self._download_json(
225 load_balancer_url, video_id,
226 'Downloading %s %s JSON metadata' % (format_id, quality),
227 fatal=False) or {}
228 m3u8_url = load_balancer_data.get('location')
229 if not m3u8_url:
230 continue
231 m3u8_formats = self._extract_m3u8_formats(
232 m3u8_url, video_id, 'mp4', 'm3u8_native',
233 m3u8_id=format_id, fatal=False)
234 if format_id == 'vf':
235 for f in m3u8_formats:
236 f['language'] = 'fr'
237 formats.extend(m3u8_formats)
238
239 video = (self._download_json(
240 self._API_BASE_URL + 'video/%s' % video_id, video_id,
241 'Downloading additional video metadata', fatal=False) or {}).get('video') or {}
242 show = video.get('show') or {}
243
244 return {
245 'id': video_id,
246 'title': title,
247 'description': strip_or_none(metas.get('summary') or video.get('summary')),
248 'thumbnail': video_info.get('image') or player.get('image'),
249 'formats': formats,
250 'subtitles': self.extract_subtitles(sub_url, video_id),
251 'episode': metas.get('subtitle') or video.get('name'),
252 'episode_number': int_or_none(video.get('shortNumber')),
253 'series': show.get('title'),
254 'season_number': int_or_none(video.get('season')),
255 'duration': int_or_none(video_info.get('duration') or video.get('duration')),
256 'release_date': unified_strdate(video.get('releaseDate')),
257 'average_rating': float_or_none(video.get('rating') or metas.get('rating')),
258 'comment_count': int_or_none(video.get('commentsCount')),
259 }