adn.py 10 KB

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