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.

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