adn.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import base64
  4. import binascii
  5. import json
  6. import os
  7. import random
  8. from .common import InfoExtractor
  9. from ..aes import aes_cbc_decrypt
  10. from ..compat import (
  11. compat_HTTPError,
  12. compat_b64decode,
  13. compat_ord,
  14. )
  15. from ..utils import (
  16. bytes_to_intlist,
  17. bytes_to_long,
  18. ExtractorError,
  19. float_or_none,
  20. int_or_none,
  21. intlist_to_bytes,
  22. long_to_bytes,
  23. pkcs1pad,
  24. strip_or_none,
  25. try_get,
  26. unified_strdate,
  27. )
  28. class ADNIE(InfoExtractor):
  29. IE_DESC = 'Anime Digital Network'
  30. _VALID_URL = r'https?://(?:www\.)?animedigitalnetwork\.fr/video/[^/]+/(?P<id>\d+)'
  31. _TEST = {
  32. 'url': 'http://animedigitalnetwork.fr/video/blue-exorcist-kyoto-saga/7778-episode-1-debut-des-hostilites',
  33. 'md5': '0319c99885ff5547565cacb4f3f9348d',
  34. 'info_dict': {
  35. 'id': '7778',
  36. 'ext': 'mp4',
  37. 'title': 'Blue Exorcist - Kyôto Saga - Episode 1',
  38. 'description': 'md5:2f7b5aa76edbc1a7a92cedcda8a528d5',
  39. 'series': 'Blue Exorcist - Kyôto Saga',
  40. 'duration': 1467,
  41. 'release_date': '20170106',
  42. 'comment_count': int,
  43. 'average_rating': float,
  44. 'season_number': 2,
  45. 'episode': 'Début des hostilités',
  46. 'episode_number': 1,
  47. }
  48. }
  49. _BASE_URL = 'http://animedigitalnetwork.fr'
  50. _API_BASE_URL = 'https://gw.api.animedigitalnetwork.fr/'
  51. _PLAYER_BASE_URL = _API_BASE_URL + 'player/'
  52. _RSA_KEY = (0x9B42B08905199A5CCE2026274399CA560ECB209EE9878A708B1C0812E1BB8CB5D1FB7441861147C1A1F2F3A0476DD63A9CAC20D3E983613346850AA6CB38F16DC7D720FD7D86FC6E5B3D5BBC72E14CD0BF9E869F2CEA2CCAD648F1DCE38F1FF916CEFB2D339B64AA0264372344BC775E265E8A852F88144AB0BD9AA06C1A4ABB, 65537)
  53. _POS_ALIGN_MAP = {
  54. 'start': 1,
  55. 'end': 3,
  56. }
  57. _LINE_ALIGN_MAP = {
  58. 'middle': 8,
  59. 'end': 4,
  60. }
  61. @staticmethod
  62. def _ass_subtitles_timecode(seconds):
  63. return '%01d:%02d:%02d.%02d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 100)
  64. def _get_subtitles(self, sub_url, video_id):
  65. if not sub_url:
  66. return None
  67. enc_subtitles = self._download_webpage(
  68. sub_url, video_id, 'Downloading subtitles location', fatal=False) or '{}'
  69. subtitle_location = (self._parse_json(enc_subtitles, video_id, fatal=False) or {}).get('location')
  70. if subtitle_location:
  71. enc_subtitles = self._download_webpage(
  72. subtitle_location, video_id, 'Downloading subtitles data',
  73. fatal=False, headers={'Origin': 'https://animedigitalnetwork.fr'})
  74. if not enc_subtitles:
  75. return None
  76. # http://animedigitalnetwork.fr/components/com_vodvideo/videojs/adn-vjs.min.js
  77. dec_subtitles = intlist_to_bytes(aes_cbc_decrypt(
  78. bytes_to_intlist(compat_b64decode(enc_subtitles[24:])),
  79. bytes_to_intlist(binascii.unhexlify(self._K + 'ab9f52f5baae7c72')),
  80. bytes_to_intlist(compat_b64decode(enc_subtitles[:24]))
  81. ))
  82. subtitles_json = self._parse_json(
  83. dec_subtitles[:-compat_ord(dec_subtitles[-1])].decode(),
  84. 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. self._ass_subtitles_timecode(start),
  107. self._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 _real_extract(self, url):
  121. video_id = self._match_id(url)
  122. video_base_url = self._PLAYER_BASE_URL + 'video/%s/' % video_id
  123. player = self._download_json(
  124. video_base_url + 'configuration', video_id,
  125. 'Downloading player config JSON metadata')['player']
  126. options = player['options']
  127. user = options['user']
  128. if not user.get('hasAccess'):
  129. raise ExtractorError(
  130. 'This video is only available for paying users', expected=True)
  131. # self.raise_login_required() # FIXME: Login is not implemented
  132. token = self._download_json(
  133. user.get('refreshTokenUrl') or (self._PLAYER_BASE_URL + 'refresh/token'),
  134. video_id, 'Downloading access token', headers={
  135. 'x-player-refresh-token': user['refreshToken']
  136. }, data=b'')['token']
  137. links_url = try_get(options, lambda x: x['video']['url']) or (video_base_url + 'link')
  138. self._K = ''.join([random.choice('0123456789abcdef') for _ in range(16)])
  139. message = bytes_to_intlist(json.dumps({
  140. 'k': self._K,
  141. 't': token,
  142. }))
  143. # Sometimes authentication fails for no good reason, retry with
  144. # a different random padding
  145. links_data = None
  146. for _ in range(3):
  147. padded_message = intlist_to_bytes(pkcs1pad(message, 128))
  148. n, e = self._RSA_KEY
  149. encrypted_message = long_to_bytes(pow(bytes_to_long(padded_message), e, n))
  150. authorization = base64.b64encode(encrypted_message).decode()
  151. try:
  152. links_data = self._download_json(
  153. links_url, video_id, 'Downloading links JSON metadata', headers={
  154. 'X-Player-Token': authorization
  155. }, query={
  156. 'freeWithAds': 'true',
  157. 'adaptive': 'false',
  158. 'withMetadata': 'true',
  159. 'source': 'Web'
  160. })
  161. break
  162. except ExtractorError as e:
  163. if not isinstance(e.cause, compat_HTTPError):
  164. raise e
  165. if e.cause.code == 401:
  166. # This usually goes away with a different random pkcs1pad, so retry
  167. continue
  168. error = self._parse_json(e.cause.read(), video_id)
  169. message = error.get('message')
  170. if e.cause.code == 403 and error.get('code') == 'player-bad-geolocation-country':
  171. self.raise_geo_restricted(msg=message)
  172. else:
  173. raise ExtractorError(message)
  174. else:
  175. raise ExtractorError('Giving up retrying')
  176. links = links_data.get('links') or {}
  177. metas = links_data.get('metadata') or {}
  178. sub_url = (links.get('subtitles') or {}).get('all')
  179. video_info = links_data.get('video') or {}
  180. title = metas['title']
  181. formats = []
  182. for format_id, qualities in (links.get('streaming') or {}).items():
  183. if not isinstance(qualities, dict):
  184. continue
  185. for quality, load_balancer_url in qualities.items():
  186. load_balancer_data = self._download_json(
  187. load_balancer_url, video_id,
  188. 'Downloading %s %s JSON metadata' % (format_id, quality),
  189. fatal=False) or {}
  190. m3u8_url = load_balancer_data.get('location')
  191. if not m3u8_url:
  192. continue
  193. m3u8_formats = self._extract_m3u8_formats(
  194. m3u8_url, video_id, 'mp4', 'm3u8_native',
  195. m3u8_id=format_id, fatal=False)
  196. if format_id == 'vf':
  197. for f in m3u8_formats:
  198. f['language'] = 'fr'
  199. formats.extend(m3u8_formats)
  200. self._sort_formats(formats)
  201. video = (self._download_json(
  202. self._API_BASE_URL + 'video/%s' % video_id, video_id,
  203. 'Downloading additional video metadata', fatal=False) or {}).get('video') or {}
  204. show = video.get('show') or {}
  205. return {
  206. 'id': video_id,
  207. 'title': title,
  208. 'description': strip_or_none(metas.get('summary') or video.get('summary')),
  209. 'thumbnail': video_info.get('image') or player.get('image'),
  210. 'formats': formats,
  211. 'subtitles': self.extract_subtitles(sub_url, video_id),
  212. 'episode': metas.get('subtitle') or video.get('name'),
  213. 'episode_number': int_or_none(video.get('shortNumber')),
  214. 'series': show.get('title'),
  215. 'season_number': int_or_none(video.get('season')),
  216. 'duration': int_or_none(video_info.get('duration') or video.get('duration')),
  217. 'release_date': unified_strdate(video.get('releaseDate')),
  218. 'average_rating': float_or_none(video.get('rating') or metas.get('rating')),
  219. 'comment_count': int_or_none(video.get('commentsCount')),
  220. }