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.

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