adn.py 14 KB

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