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