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.

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