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.

201 lines
8.1 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 data', fatal=False)
  57. if not enc_subtitles:
  58. return None
  59. # http://animedigitalnetwork.fr/components/com_vodvideo/videojs/adn-vjs.min.js
  60. dec_subtitles = intlist_to_bytes(aes_cbc_decrypt(
  61. bytes_to_intlist(compat_b64decode(enc_subtitles[24:])),
  62. bytes_to_intlist(binascii.unhexlify(self._K + '083db5aebd9353b4')),
  63. bytes_to_intlist(compat_b64decode(enc_subtitles[:24]))
  64. ))
  65. subtitles_json = self._parse_json(
  66. dec_subtitles[:-compat_ord(dec_subtitles[-1])].decode(),
  67. None, fatal=False)
  68. if not subtitles_json:
  69. return None
  70. subtitles = {}
  71. for sub_lang, sub in subtitles_json.items():
  72. ssa = '''[Script Info]
  73. ScriptType:V4.00
  74. [V4 Styles]
  75. Format: Name,Fontname,Fontsize,PrimaryColour,SecondaryColour,TertiaryColour,BackColour,Bold,Italic,BorderStyle,Outline,Shadow,Alignment,MarginL,MarginR,MarginV,AlphaLevel,Encoding
  76. Style: Default,Arial,18,16777215,16777215,16777215,0,-1,0,1,1,0,2,20,20,20,0,0
  77. [Events]
  78. Format: Marked,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text'''
  79. for current in sub:
  80. start, end, text, line_align, position_align = (
  81. float_or_none(current.get('startTime')),
  82. float_or_none(current.get('endTime')),
  83. current.get('text'), current.get('lineAlign'),
  84. current.get('positionAlign'))
  85. if start is None or end is None or text is None:
  86. continue
  87. alignment = self._POS_ALIGN_MAP.get(position_align, 2) + self._LINE_ALIGN_MAP.get(line_align, 0)
  88. ssa += os.linesep + 'Dialogue: Marked=0,%s,%s,Default,,0,0,0,,%s%s' % (
  89. self._ass_subtitles_timecode(start),
  90. self._ass_subtitles_timecode(end),
  91. '{\\a%d}' % alignment if alignment != 2 else '',
  92. text.replace('\n', '\\N').replace('<i>', '{\\i1}').replace('</i>', '{\\i0}'))
  93. if sub_lang == 'vostf':
  94. sub_lang = 'fr'
  95. subtitles.setdefault(sub_lang, []).extend([{
  96. 'ext': 'json',
  97. 'data': json.dumps(sub),
  98. }, {
  99. 'ext': 'ssa',
  100. 'data': ssa,
  101. }])
  102. return subtitles
  103. def _real_extract(self, url):
  104. video_id = self._match_id(url)
  105. webpage = self._download_webpage(url, video_id)
  106. player_config = self._parse_json(self._search_regex(
  107. r'playerConfig\s*=\s*({.+});', webpage,
  108. 'player config', default='{}'), video_id, fatal=False)
  109. if not player_config:
  110. config_url = urljoin(self._BASE_URL, self._search_regex(
  111. r'(?:id="player"|class="[^"]*adn-player-container[^"]*")[^>]+data-url="([^"]+)"',
  112. webpage, 'config url'))
  113. player_config = self._download_json(
  114. config_url, video_id,
  115. 'Downloading player config JSON metadata')['player']
  116. video_info = {}
  117. video_info_str = self._search_regex(
  118. r'videoInfo\s*=\s*({.+});', webpage,
  119. 'video info', fatal=False)
  120. if video_info_str:
  121. video_info = self._parse_json(
  122. video_info_str, video_id, fatal=False) or {}
  123. options = player_config.get('options') or {}
  124. metas = options.get('metas') or {}
  125. links = player_config.get('links') or {}
  126. sub_path = player_config.get('subtitles')
  127. error = None
  128. if not links:
  129. links_url = player_config.get('linksurl') or options['videoUrl']
  130. token = options['token']
  131. self._K = ''.join([random.choice('0123456789abcdef') for _ in range(16)])
  132. message = bytes_to_intlist(json.dumps({
  133. 'k': self._K,
  134. 'e': 60,
  135. 't': token,
  136. }))
  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. links_data = self._download_json(
  142. urljoin(self._BASE_URL, links_url), video_id,
  143. 'Downloading links JSON metadata', headers={
  144. 'Authorization': 'Bearer ' + authorization,
  145. })
  146. links = links_data.get('links') or {}
  147. metas = metas or links_data.get('meta') or {}
  148. sub_path = sub_path or links_data.get('subtitles') or \
  149. 'index.php?option=com_vodapi&task=subtitles.getJSON&format=json&id=' + video_id
  150. sub_path += '&token=' + token
  151. error = links_data.get('error')
  152. title = metas.get('title') or video_info['title']
  153. formats = []
  154. for format_id, qualities in links.items():
  155. if not isinstance(qualities, dict):
  156. continue
  157. for quality, load_balancer_url in qualities.items():
  158. load_balancer_data = self._download_json(
  159. load_balancer_url, video_id,
  160. 'Downloading %s %s JSON metadata' % (format_id, quality),
  161. fatal=False) or {}
  162. m3u8_url = load_balancer_data.get('location')
  163. if not m3u8_url:
  164. continue
  165. m3u8_formats = self._extract_m3u8_formats(
  166. m3u8_url, video_id, 'mp4', 'm3u8_native',
  167. m3u8_id=format_id, fatal=False)
  168. if format_id == 'vf':
  169. for f in m3u8_formats:
  170. f['language'] = 'fr'
  171. formats.extend(m3u8_formats)
  172. if not error:
  173. error = options.get('error')
  174. if not formats and error:
  175. raise ExtractorError('%s said: %s' % (self.IE_NAME, error), expected=True)
  176. self._sort_formats(formats)
  177. return {
  178. 'id': video_id,
  179. 'title': title,
  180. 'description': strip_or_none(metas.get('summary') or video_info.get('resume')),
  181. 'thumbnail': video_info.get('image'),
  182. 'formats': formats,
  183. 'subtitles': self.extract_subtitles(sub_path, video_id),
  184. 'episode': metas.get('subtitle') or video_info.get('videoTitle'),
  185. 'series': video_info.get('playlistTitle'),
  186. }