adn.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. unified_strdate,
  26. urljoin,
  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. }
  40. }
  41. _BASE_URL = 'http://animedigitalnetwork.fr'
  42. _API_BASE_URL = 'https://gw.api.animedigitalnetwork.fr'
  43. _RSA_KEY = (0x9B42B08905199A5CCE2026274399CA560ECB209EE9878A708B1C0812E1BB8CB5D1FB7441861147C1A1F2F3A0476DD63A9CAC20D3E983613346850AA6CB38F16DC7D720FD7D86FC6E5B3D5BBC72E14CD0BF9E869F2CEA2CCAD648F1DCE38F1FF916CEFB2D339B64AA0264372344BC775E265E8A852F88144AB0BD9AA06C1A4ABB, 65537)
  44. _POS_ALIGN_MAP = {
  45. 'start': 1,
  46. 'end': 3,
  47. }
  48. _LINE_ALIGN_MAP = {
  49. 'middle': 8,
  50. 'end': 4,
  51. }
  52. @staticmethod
  53. def _ass_subtitles_timecode(seconds):
  54. return '%01d:%02d:%02d.%02d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 100)
  55. def _get_subtitles(self, sub_path, video_id):
  56. if not sub_path:
  57. return None
  58. enc_subtitles = self._download_webpage(
  59. urljoin(self._BASE_URL, sub_path),
  60. video_id, 'Downloading subtitles location', fatal=False) or '{}'
  61. subtitle_location = (self._parse_json(enc_subtitles, video_id, fatal=False) or {}).get('location')
  62. if subtitle_location:
  63. enc_subtitles = self._download_webpage(
  64. urljoin(self._BASE_URL, subtitle_location),
  65. video_id, 'Downloading subtitles data', fatal=False,
  66. headers={'Origin': 'https://animedigitalnetwork.fr'})
  67. if not enc_subtitles:
  68. return None
  69. # http://animedigitalnetwork.fr/components/com_vodvideo/videojs/adn-vjs.min.js
  70. dec_subtitles = intlist_to_bytes(aes_cbc_decrypt(
  71. bytes_to_intlist(compat_b64decode(enc_subtitles[24:])),
  72. bytes_to_intlist(binascii.unhexlify(self._K + '4b8ef13ec1872730')),
  73. bytes_to_intlist(compat_b64decode(enc_subtitles[:24]))
  74. ))
  75. subtitles_json = self._parse_json(
  76. dec_subtitles[:-compat_ord(dec_subtitles[-1])].decode(),
  77. None, fatal=False)
  78. if not subtitles_json:
  79. return None
  80. subtitles = {}
  81. for sub_lang, sub in subtitles_json.items():
  82. ssa = '''[Script Info]
  83. ScriptType:V4.00
  84. [V4 Styles]
  85. Format: Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,TertiaryColour,BackColour,Bold,Italic,BorderStyle,Outline,Shadow,Alignment,MarginL,MarginR,MarginV,AlphaLevel,Encoding
  86. Style: Default,Arial,18,16777215,16777215,16777215,0,-1,0,1,1,0,2,20,20,20,0,0
  87. [Events]
  88. Format: Marked,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text'''
  89. for current in sub:
  90. start, end, text, line_align, position_align = (
  91. float_or_none(current.get('startTime')),
  92. float_or_none(current.get('endTime')),
  93. current.get('text'), current.get('lineAlign'),
  94. current.get('positionAlign'))
  95. if start is None or end is None or text is None:
  96. continue
  97. alignment = self._POS_ALIGN_MAP.get(position_align, 2) + self._LINE_ALIGN_MAP.get(line_align, 0)
  98. ssa += os.linesep + 'Dialogue: Marked=0,%s,%s,Default,,0,0,0,,%s%s' % (
  99. self._ass_subtitles_timecode(start),
  100. self._ass_subtitles_timecode(end),
  101. '{\\a%d}' % alignment if alignment != 2 else '',
  102. text.replace('\n', '\\N').replace('<i>', '{\\i1}').replace('</i>', '{\\i0}'))
  103. if sub_lang == 'vostf':
  104. sub_lang = 'fr'
  105. subtitles.setdefault(sub_lang, []).extend([{
  106. 'ext': 'json',
  107. 'data': json.dumps(sub),
  108. }, {
  109. 'ext': 'ssa',
  110. 'data': ssa,
  111. }])
  112. return subtitles
  113. def _real_extract(self, url):
  114. video_id = self._match_id(url)
  115. config_url = self._API_BASE_URL + '/player/video/%s/configuration' % video_id
  116. player_config = self._download_json(
  117. config_url, video_id,
  118. 'Downloading player config JSON metadata')['player']['options']
  119. user = player_config['user']
  120. if not user.get('hasAccess'):
  121. raise ExtractorError('This video is only available for paying users')
  122. # self.raise_login_required() # FIXME: Login is not implemented
  123. token = self._download_json(
  124. user.get('refreshTokenUrl') or (self._API_BASE_URL + '/player/refresh/token'),
  125. video_id, 'Downloading access token', headers={'x-player-refresh-token': user['refreshToken']},
  126. data=b'')['token']
  127. links_url = player_config.get('videoUrl') or (self._API_BASE_URL + '/player/video/%s/link' % video_id)
  128. self._K = ''.join([random.choice('0123456789abcdef') for _ in range(16)])
  129. message = bytes_to_intlist(json.dumps({
  130. 'k': self._K,
  131. 't': token,
  132. }))
  133. # Sometimes authentication fails for no good reason, retry with
  134. # a different random padding
  135. links_data = None
  136. for _ in range(3):
  137. padded_message = intlist_to_bytes(pkcs1pad(message, 128))
  138. n, e = self._RSA_KEY
  139. encrypted_message = long_to_bytes(pow(bytes_to_long(padded_message), e, n))
  140. authorization = base64.b64encode(encrypted_message).decode()
  141. try:
  142. links_data = self._download_json(
  143. urljoin(self._BASE_URL, links_url), video_id,
  144. 'Downloading links JSON metadata', headers={
  145. 'X-Player-Token': authorization
  146. },
  147. query={
  148. 'freeWithAds': 'true',
  149. 'adaptive': 'false',
  150. 'withMetadata': 'true',
  151. 'source': 'Web'
  152. }
  153. )
  154. break
  155. except ExtractorError as e:
  156. if not isinstance(e.cause, compat_HTTPError):
  157. raise e
  158. if e.cause.code == 401:
  159. # This usually goes away with a different random pkcs1pad, so retry
  160. continue
  161. error = self._parse_json(e.cause.read(), video_id)
  162. message = error.get('message')
  163. if e.cause.code == 403 and error.get('code') == 'player-bad-geolocation-country':
  164. self.raise_geo_restricted(msg=message)
  165. else:
  166. raise ExtractorError(message)
  167. else:
  168. raise ExtractorError('Giving up retrying')
  169. links = links_data.get('links') or {}
  170. metas = links_data.get('metadata') or {}
  171. sub_path = (links.get('subtitles') or {}).get('all')
  172. video_info = links_data.get('video') or {}
  173. formats = []
  174. for format_id, qualities in (links.get('streaming') or {}).items():
  175. if not isinstance(qualities, dict):
  176. continue
  177. for quality, load_balancer_url in qualities.items():
  178. load_balancer_data = self._download_json(
  179. load_balancer_url, video_id,
  180. 'Downloading %s %s JSON metadata' % (format_id, quality),
  181. fatal=False) or {}
  182. m3u8_url = load_balancer_data.get('location')
  183. if not m3u8_url:
  184. continue
  185. m3u8_formats = self._extract_m3u8_formats(
  186. m3u8_url, video_id, 'mp4', 'm3u8_native',
  187. m3u8_id=format_id, fatal=False)
  188. if format_id == 'vf':
  189. for f in m3u8_formats:
  190. f['language'] = 'fr'
  191. formats.extend(m3u8_formats)
  192. self._sort_formats(formats)
  193. video = (self._download_json(self._API_BASE_URL + '/video/%s' % video_id, video_id,
  194. 'Downloading additional video metadata', fatal=False) or {}).get('video')
  195. show = video.get('show') or {}
  196. return {
  197. 'id': video_id,
  198. 'title': metas.get('title') or video_id,
  199. 'description': strip_or_none(metas.get('summary') or video.get('summary')),
  200. 'thumbnail': video_info.get('image'),
  201. 'formats': formats,
  202. 'subtitles': sub_path and self.extract_subtitles(sub_path, video_id),
  203. 'episode': metas.get('subtitle') or video.get('name'),
  204. 'episode_number': int_or_none(video.get('shortNumber')),
  205. 'series': video_info.get('playlistTitle') or show.get('title'),
  206. 'season_number': int_or_none(video.get('season')),
  207. 'duration': int_or_none(video_info.get('duration') or video.get('duration')),
  208. 'release_date': unified_strdate(video.get('release_date')),
  209. 'average_rating': video.get('rating') or metas.get('rating'),
  210. 'comment_count': int_or_none(video.get('commentsCount')),
  211. }