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.

331 lines
14 KiB

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