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.

324 lines
14 KiB

  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import json
  5. import base64
  6. import zlib
  7. import xml.etree.ElementTree
  8. from hashlib import sha1
  9. from math import pow, sqrt, floor
  10. from .subtitles import SubtitlesInfoExtractor
  11. from ..utils import (
  12. ExtractorError,
  13. compat_urllib_parse,
  14. compat_urllib_request,
  15. bytes_to_intlist,
  16. intlist_to_bytes,
  17. unified_strdate,
  18. urlencode_postdata,
  19. )
  20. from ..aes import (
  21. aes_cbc_decrypt,
  22. inc,
  23. )
  24. from .common import InfoExtractor
  25. class CrunchyrollIE(SubtitlesInfoExtractor):
  26. _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?:[^/]*/[^/?&]*?|media/\?id=)(?P<video_id>[0-9]+))(?:[/?&]|$)'
  27. _TEST = {
  28. 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
  29. #'md5': 'b1639fd6ddfaa43788c85f6d1dddd412',
  30. 'info_dict': {
  31. 'id': '645513',
  32. 'ext': 'flv',
  33. 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
  34. 'description': 'md5:2d17137920c64f2f49981a7797d275ef',
  35. 'thumbnail': 'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
  36. 'uploader': 'Yomiuri Telecasting Corporation (YTV)',
  37. 'upload_date': '20131013',
  38. 'url': 're:(?!.*&amp)',
  39. },
  40. 'params': {
  41. # rtmp
  42. 'skip_download': True,
  43. },
  44. }
  45. _FORMAT_IDS = {
  46. '360': ('60', '106'),
  47. '480': ('61', '106'),
  48. '720': ('62', '106'),
  49. '1080': ('80', '108'),
  50. }
  51. def _login(self):
  52. (username, password) = self._get_login_info()
  53. if username is None:
  54. return
  55. self.report_login()
  56. login_url = 'https://www.crunchyroll.com/?a=formhandler'
  57. data = urlencode_postdata({
  58. 'formname': 'RpcApiUser_Login',
  59. 'name': username,
  60. 'password': password,
  61. })
  62. login_request = compat_urllib_request.Request(login_url, data)
  63. login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  64. self._download_webpage(login_request, None, False, 'Wrong login info')
  65. def _real_initialize(self):
  66. self._login()
  67. def _decrypt_subtitles(self, data, iv, id):
  68. data = bytes_to_intlist(data)
  69. iv = bytes_to_intlist(iv)
  70. id = int(id)
  71. def obfuscate_key_aux(count, modulo, start):
  72. output = list(start)
  73. for _ in range(count):
  74. output.append(output[-1] + output[-2])
  75. # cut off start values
  76. output = output[2:]
  77. output = list(map(lambda x: x % modulo + 33, output))
  78. return output
  79. def obfuscate_key(key):
  80. num1 = int(floor(pow(2, 25) * sqrt(6.9)))
  81. num2 = (num1 ^ key) << 5
  82. num3 = key ^ num1
  83. num4 = num3 ^ (num3 >> 3) ^ num2
  84. prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
  85. shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
  86. # Extend 160 Bit hash to 256 Bit
  87. return shaHash + [0] * 12
  88. key = obfuscate_key(id)
  89. class Counter:
  90. __value = iv
  91. def next_value(self):
  92. temp = self.__value
  93. self.__value = inc(self.__value)
  94. return temp
  95. decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
  96. return zlib.decompress(decrypted_data)
  97. def _convert_subtitles_to_srt(self, sub_root):
  98. output = ''
  99. for i, event in enumerate(sub_root.findall('./events/event'), 1):
  100. start = event.attrib['start'].replace('.', ',')
  101. end = event.attrib['end'].replace('.', ',')
  102. text = event.attrib['text'].replace('\\N', '\n')
  103. output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
  104. return output
  105. def _convert_subtitles_to_ass(self, sub_root):
  106. output = ''
  107. def ass_bool(strvalue):
  108. assvalue = '0'
  109. if strvalue == '1':
  110. assvalue = '-1'
  111. return assvalue
  112. output = '[Script Info]\n'
  113. output += 'Title: %s\n' % sub_root.attrib["title"]
  114. output += 'ScriptType: v4.00+\n'
  115. output += 'WrapStyle: %s\n' % sub_root.attrib["wrap_style"]
  116. output += 'PlayResX: %s\n' % sub_root.attrib["play_res_x"]
  117. output += 'PlayResY: %s\n' % sub_root.attrib["play_res_y"]
  118. output += """ScaledBorderAndShadow: yes
  119. [V4+ Styles]
  120. Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
  121. """
  122. for style in sub_root.findall('./styles/style'):
  123. output += 'Style: ' + style.attrib["name"]
  124. output += ',' + style.attrib["font_name"]
  125. output += ',' + style.attrib["font_size"]
  126. output += ',' + style.attrib["primary_colour"]
  127. output += ',' + style.attrib["secondary_colour"]
  128. output += ',' + style.attrib["outline_colour"]
  129. output += ',' + style.attrib["back_colour"]
  130. output += ',' + ass_bool(style.attrib["bold"])
  131. output += ',' + ass_bool(style.attrib["italic"])
  132. output += ',' + ass_bool(style.attrib["underline"])
  133. output += ',' + ass_bool(style.attrib["strikeout"])
  134. output += ',' + style.attrib["scale_x"]
  135. output += ',' + style.attrib["scale_y"]
  136. output += ',' + style.attrib["spacing"]
  137. output += ',' + style.attrib["angle"]
  138. output += ',' + style.attrib["border_style"]
  139. output += ',' + style.attrib["outline"]
  140. output += ',' + style.attrib["shadow"]
  141. output += ',' + style.attrib["alignment"]
  142. output += ',' + style.attrib["margin_l"]
  143. output += ',' + style.attrib["margin_r"]
  144. output += ',' + style.attrib["margin_v"]
  145. output += ',' + style.attrib["encoding"]
  146. output += '\n'
  147. output += """
  148. [Events]
  149. Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
  150. """
  151. for event in sub_root.findall('./events/event'):
  152. output += 'Dialogue: 0'
  153. output += ',' + event.attrib["start"]
  154. output += ',' + event.attrib["end"]
  155. output += ',' + event.attrib["style"]
  156. output += ',' + event.attrib["name"]
  157. output += ',' + event.attrib["margin_l"]
  158. output += ',' + event.attrib["margin_r"]
  159. output += ',' + event.attrib["margin_v"]
  160. output += ',' + event.attrib["effect"]
  161. output += ',' + event.attrib["text"]
  162. output += '\n'
  163. return output
  164. def _real_extract(self,url):
  165. mobj = re.match(self._VALID_URL, url)
  166. video_id = mobj.group('video_id')
  167. if mobj.group('prefix') == 'm':
  168. mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
  169. webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
  170. else:
  171. webpage_url = 'http://www.' + mobj.group('url')
  172. webpage = self._download_webpage(webpage_url, video_id, 'Downloading webpage')
  173. note_m = self._html_search_regex(r'<div class="showmedia-trailer-notice">(.+?)</div>', webpage, 'trailer-notice', default='')
  174. if note_m:
  175. raise ExtractorError(note_m)
  176. mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
  177. if mobj:
  178. msg = json.loads(mobj.group('msg'))
  179. if msg.get('type') == 'error':
  180. raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
  181. video_title = self._html_search_regex(r'<h1[^>]*>(.+?)</h1>', webpage, 'video_title', flags=re.DOTALL)
  182. video_title = re.sub(r' {2,}', ' ', video_title)
  183. video_description = self._html_search_regex(r'"description":"([^"]+)', webpage, 'video_description', default='')
  184. if not video_description:
  185. video_description = None
  186. video_upload_date = self._html_search_regex(r'<div>Availability for free users:(.+?)</div>', webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
  187. if video_upload_date:
  188. video_upload_date = unified_strdate(video_upload_date)
  189. video_uploader = self._html_search_regex(r'<div>\s*Publisher:(.+?)</div>', webpage, 'video_uploader', fatal=False, flags=re.DOTALL)
  190. playerdata_url = compat_urllib_parse.unquote(self._html_search_regex(r'"config_url":"([^"]+)', webpage, 'playerdata_url'))
  191. playerdata_req = compat_urllib_request.Request(playerdata_url)
  192. playerdata_req.data = compat_urllib_parse.urlencode({'current_page': webpage_url})
  193. playerdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  194. playerdata = self._download_webpage(playerdata_req, video_id, note='Downloading media info')
  195. stream_id = self._search_regex(r'<media_id>([^<]+)', playerdata, 'stream_id')
  196. video_thumbnail = self._search_regex(r'<episode_image_url>([^<]+)', playerdata, 'thumbnail', fatal=False)
  197. formats = []
  198. for fmt in re.findall(r'\?p([0-9]{3,4})=1', webpage):
  199. stream_quality, stream_format = self._FORMAT_IDS[fmt]
  200. video_format = fmt+'p'
  201. streamdata_req = compat_urllib_request.Request('http://www.crunchyroll.com/xml/')
  202. # urlencode doesn't work!
  203. streamdata_req.data = 'req=RpcApiVideoEncode%5FGetStreamInfo&video%5Fencode%5Fquality='+stream_quality+'&media%5Fid='+stream_id+'&video%5Fformat='+stream_format
  204. streamdata_req.add_header('Content-Type', 'application/x-www-form-urlencoded')
  205. streamdata_req.add_header('Content-Length', str(len(streamdata_req.data)))
  206. streamdata = self._download_xml(
  207. streamdata_req, video_id,
  208. note='Downloading media info for %s' % video_format)
  209. video_url = streamdata.find('.//host').text
  210. video_play_path = streamdata.find('.//file').text
  211. formats.append({
  212. 'url': video_url,
  213. 'play_path': video_play_path,
  214. 'ext': 'flv',
  215. 'format': video_format,
  216. 'format_id': video_format,
  217. })
  218. subtitles = {}
  219. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  220. for sub_id, sub_name in re.findall(r'\?ssid=([0-9]+)" title="([^"]+)', webpage):
  221. sub_page = self._download_webpage('http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id='+sub_id,\
  222. video_id, note='Downloading subtitles for '+sub_name)
  223. id = self._search_regex(r'id=\'([0-9]+)', sub_page, 'subtitle_id', fatal=False)
  224. iv = self._search_regex(r'<iv>([^<]+)', sub_page, 'subtitle_iv', fatal=False)
  225. data = self._search_regex(r'<data>([^<]+)', sub_page, 'subtitle_data', fatal=False)
  226. if not id or not iv or not data:
  227. continue
  228. id = int(id)
  229. iv = base64.b64decode(iv)
  230. data = base64.b64decode(data)
  231. subtitle = self._decrypt_subtitles(data, iv, id).decode('utf-8')
  232. lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
  233. if not lang_code:
  234. continue
  235. sub_root = xml.etree.ElementTree.fromstring(subtitle)
  236. if not sub_root:
  237. subtitles[lang_code] = ''
  238. if sub_format == 'ass':
  239. subtitles[lang_code] = self._convert_subtitles_to_ass(sub_root)
  240. else:
  241. subtitles[lang_code] = self._convert_subtitles_to_srt(sub_root)
  242. if self._downloader.params.get('listsubtitles', False):
  243. self._list_available_subtitles(video_id, subtitles)
  244. return
  245. return {
  246. 'id': video_id,
  247. 'title': video_title,
  248. 'description': video_description,
  249. 'thumbnail': video_thumbnail,
  250. 'uploader': video_uploader,
  251. 'upload_date': video_upload_date,
  252. 'subtitles': subtitles,
  253. 'formats': formats,
  254. }
  255. class CrunchyrollShowPlaylistIE(InfoExtractor):
  256. IE_NAME = "crunchyroll:playlist"
  257. _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?!(?:news|anime-news|library|forum|launchcalendar|lineup|store|comics|freetrial|login))(?P<id>[\w\-]+))/?$'
  258. _TESTS = [{
  259. 'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
  260. 'info_dict': {
  261. 'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
  262. 'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
  263. },
  264. 'playlist_count': 13,
  265. }]
  266. def _real_extract(self, url):
  267. show_id = self._match_id(url)
  268. webpage = self._download_webpage(url, show_id)
  269. title = self._html_search_regex(
  270. r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
  271. webpage, 'title')
  272. episode_paths = re.findall(
  273. r'(?s)<li id="showview_videos_media_[0-9]+"[^>]+>.*?<a href="([^"]+)"',
  274. webpage)
  275. entries = [
  276. self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll')
  277. for ep in episode_paths
  278. ]
  279. entries.reverse()
  280. return {
  281. '_type': 'playlist',
  282. 'id': show_id,
  283. 'title': title,
  284. 'entries': entries,
  285. }