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.

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