adn.py 11 KB

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