adn.py 11 KB

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