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