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.

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