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.

337 lines
14 KiB

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