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.

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