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.

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