You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

206 lines
8.5 KiB

  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_b64decode,
  12. compat_ord,
  13. )
  14. from ..utils import (
  15. bytes_to_intlist,
  16. bytes_to_long,
  17. ExtractorError,
  18. float_or_none,
  19. intlist_to_bytes,
  20. long_to_bytes,
  21. pkcs1pad,
  22. strip_or_none,
  23. urljoin,
  24. )
  25. class ADNIE(InfoExtractor):
  26. IE_DESC = 'Anime Digital Network'
  27. _VALID_URL = r'https?://(?:www\.)?animedigitalnetwork\.fr/video/[^/]+/(?P<id>\d+)'
  28. _TEST = {
  29. 'url': 'http://animedigitalnetwork.fr/video/blue-exorcist-kyoto-saga/7778-episode-1-debut-des-hostilites',
  30. 'md5': 'e497370d847fd79d9d4c74be55575c7a',
  31. 'info_dict': {
  32. 'id': '7778',
  33. 'ext': 'mp4',
  34. 'title': 'Blue Exorcist - Kyôto Saga - Épisode 1',
  35. 'description': 'md5:2f7b5aa76edbc1a7a92cedcda8a528d5',
  36. }
  37. }
  38. _BASE_URL = 'http://animedigitalnetwork.fr'
  39. _RSA_KEY = (0xc35ae1e4356b65a73b551493da94b8cb443491c0aa092a357a5aee57ffc14dda85326f42d716e539a34542a0d3f363adf16c5ec222d713d5997194030ee2e4f0d1fb328c01a81cf6868c090d50de8e169c6b13d1675b9eeed1cbc51e1fffca9b38af07f37abd790924cd3bee59d0257cfda4fe5f3f0534877e21ce5821447d1b, 65537)
  40. _POS_ALIGN_MAP = {
  41. 'start': 1,
  42. 'end': 3,
  43. }
  44. _LINE_ALIGN_MAP = {
  45. 'middle': 8,
  46. 'end': 4,
  47. }
  48. @staticmethod
  49. def _ass_subtitles_timecode(seconds):
  50. return '%01d:%02d:%02d.%02d' % (seconds / 3600, (seconds % 3600) / 60, seconds % 60, (seconds % 1) * 100)
  51. def _get_subtitles(self, sub_path, video_id):
  52. if not sub_path:
  53. return None
  54. enc_subtitles = self._download_webpage(
  55. urljoin(self._BASE_URL, sub_path),
  56. video_id, 'Downloading subtitles location', fatal=False) or '{}'
  57. subtitle_location = (self._parse_json(enc_subtitles, video_id, fatal=False) or {}).get('location')
  58. if subtitle_location:
  59. enc_subtitles = self._download_webpage(
  60. urljoin(self._BASE_URL, subtitle_location),
  61. video_id, 'Downloading subtitles data', fatal=False)
  62. if not enc_subtitles:
  63. return None
  64. # http://animedigitalnetwork.fr/components/com_vodvideo/videojs/adn-vjs.min.js
  65. dec_subtitles = intlist_to_bytes(aes_cbc_decrypt(
  66. bytes_to_intlist(compat_b64decode(enc_subtitles[24:])),
  67. bytes_to_intlist(binascii.unhexlify(self._K + '4421de0a5f0814ba')),
  68. bytes_to_intlist(compat_b64decode(enc_subtitles[:24]))
  69. ))
  70. subtitles_json = self._parse_json(
  71. dec_subtitles[:-compat_ord(dec_subtitles[-1])].decode(),
  72. None, fatal=False)
  73. if not subtitles_json:
  74. return None
  75. subtitles = {}
  76. for sub_lang, sub in subtitles_json.items():
  77. ssa = '''[Script Info]
  78. ScriptType:V4.00
  79. [V4 Styles]
  80. Format: Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,TertiaryColour,BackColour,Bold,Italic,BorderStyle,Outline,Shadow,Alignment,MarginL,MarginR,MarginV,AlphaLevel,Encoding
  81. Style: Default,Arial,18,16777215,16777215,16777215,0,-1,0,1,1,0,2,20,20,20,0,0
  82. [Events]
  83. Format: Marked,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text'''
  84. for current in sub:
  85. start, end, text, line_align, position_align = (
  86. float_or_none(current.get('startTime')),
  87. float_or_none(current.get('endTime')),
  88. current.get('text'), current.get('lineAlign'),
  89. current.get('positionAlign'))
  90. if start is None or end is None or text is None:
  91. continue
  92. alignment = self._POS_ALIGN_MAP.get(position_align, 2) + self._LINE_ALIGN_MAP.get(line_align, 0)
  93. ssa += os.linesep + 'Dialogue: Marked=0,%s,%s,Default,,0,0,0,,%s%s' % (
  94. self._ass_subtitles_timecode(start),
  95. self._ass_subtitles_timecode(end),
  96. '{\\a%d}' % alignment if alignment != 2 else '',
  97. text.replace('\n', '\\N').replace('<i>', '{\\i1}').replace('</i>', '{\\i0}'))
  98. if sub_lang == 'vostf':
  99. sub_lang = 'fr'
  100. subtitles.setdefault(sub_lang, []).extend([{
  101. 'ext': 'json',
  102. 'data': json.dumps(sub),
  103. }, {
  104. 'ext': 'ssa',
  105. 'data': ssa,
  106. }])
  107. return subtitles
  108. def _real_extract(self, url):
  109. video_id = self._match_id(url)
  110. webpage = self._download_webpage(url, video_id)
  111. player_config = self._parse_json(self._search_regex(
  112. r'playerConfig\s*=\s*({.+});', webpage,
  113. 'player config', default='{}'), video_id, fatal=False)
  114. if not player_config:
  115. config_url = urljoin(self._BASE_URL, self._search_regex(
  116. r'(?:id="player"|class="[^"]*adn-player-container[^"]*")[^>]+data-url="([^"]+)"',
  117. webpage, 'config url'))
  118. player_config = self._download_json(
  119. config_url, video_id,
  120. 'Downloading player config JSON metadata')['player']
  121. video_info = {}
  122. video_info_str = self._search_regex(
  123. r'videoInfo\s*=\s*({.+});', webpage,
  124. 'video info', fatal=False)
  125. if video_info_str:
  126. video_info = self._parse_json(
  127. video_info_str, video_id, fatal=False) or {}
  128. options = player_config.get('options') or {}
  129. metas = options.get('metas') or {}
  130. links = player_config.get('links') or {}
  131. sub_path = player_config.get('subtitles')
  132. error = None
  133. if not links:
  134. links_url = player_config.get('linksurl') or options['videoUrl']
  135. token = options['token']
  136. self._K = ''.join([random.choice('0123456789abcdef') for _ in range(16)])
  137. message = bytes_to_intlist(json.dumps({
  138. 'k': self._K,
  139. 'e': 60,
  140. 't': token,
  141. }))
  142. padded_message = intlist_to_bytes(pkcs1pad(message, 128))
  143. n, e = self._RSA_KEY
  144. encrypted_message = long_to_bytes(pow(bytes_to_long(padded_message), e, n))
  145. authorization = base64.b64encode(encrypted_message).decode()
  146. links_data = self._download_json(
  147. urljoin(self._BASE_URL, links_url), video_id,
  148. 'Downloading links JSON metadata', headers={
  149. 'Authorization': 'Bearer ' + authorization,
  150. })
  151. links = links_data.get('links') or {}
  152. metas = metas or links_data.get('meta') or {}
  153. sub_path = sub_path or links_data.get('subtitles') or \
  154. 'index.php?option=com_vodapi&task=subtitles.getJSON&format=json&id=' + video_id
  155. sub_path += '&token=' + token
  156. error = links_data.get('error')
  157. title = metas.get('title') or video_info['title']
  158. formats = []
  159. for format_id, qualities in links.items():
  160. if not isinstance(qualities, dict):
  161. continue
  162. for quality, load_balancer_url in qualities.items():
  163. load_balancer_data = self._download_json(
  164. load_balancer_url, video_id,
  165. 'Downloading %s %s JSON metadata' % (format_id, quality),
  166. fatal=False) or {}
  167. m3u8_url = load_balancer_data.get('location')
  168. if not m3u8_url:
  169. continue
  170. m3u8_formats = self._extract_m3u8_formats(
  171. m3u8_url, video_id, 'mp4', 'm3u8_native',
  172. m3u8_id=format_id, fatal=False)
  173. if format_id == 'vf':
  174. for f in m3u8_formats:
  175. f['language'] = 'fr'
  176. formats.extend(m3u8_formats)
  177. if not error:
  178. error = options.get('error')
  179. if not formats and error:
  180. raise ExtractorError('%s said: %s' % (self.IE_NAME, error), expected=True)
  181. self._sort_formats(formats)
  182. return {
  183. 'id': video_id,
  184. 'title': title,
  185. 'description': strip_or_none(metas.get('summary') or video_info.get('resume')),
  186. 'thumbnail': video_info.get('image'),
  187. 'formats': formats,
  188. 'subtitles': self.extract_subtitles(sub_path, video_id),
  189. 'episode': metas.get('subtitle') or video_info.get('videoTitle'),
  190. 'series': video_info.get('playlistTitle'),
  191. }