crunchyroll.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import json
  5. import zlib
  6. from hashlib import sha1
  7. from math import pow, sqrt, floor
  8. from .common import InfoExtractor
  9. from .vrv import VRVIE
  10. from ..compat import (
  11. compat_b64decode,
  12. compat_etree_fromstring,
  13. compat_urllib_parse_urlencode,
  14. compat_urllib_request,
  15. compat_urlparse,
  16. )
  17. from ..utils import (
  18. ExtractorError,
  19. bytes_to_intlist,
  20. extract_attributes,
  21. float_or_none,
  22. intlist_to_bytes,
  23. int_or_none,
  24. lowercase_escape,
  25. remove_end,
  26. sanitized_Request,
  27. unified_strdate,
  28. urlencode_postdata,
  29. xpath_text,
  30. )
  31. from ..aes import (
  32. aes_cbc_decrypt,
  33. )
  34. class CrunchyrollBaseIE(InfoExtractor):
  35. _LOGIN_URL = 'https://www.crunchyroll.com/login'
  36. _LOGIN_FORM = 'login_form'
  37. _NETRC_MACHINE = 'crunchyroll'
  38. def _call_rpc_api(self, method, video_id, note=None, data=None):
  39. data = data or {}
  40. data['req'] = 'RpcApi' + method
  41. data = compat_urllib_parse_urlencode(data).encode('utf-8')
  42. return self._download_xml(
  43. 'http://www.crunchyroll.com/xml/',
  44. video_id, note, fatal=False, data=data, headers={
  45. 'Content-Type': 'application/x-www-form-urlencoded',
  46. })
  47. def _login(self):
  48. username, password = self._get_login_info()
  49. if username is None:
  50. return
  51. self._download_webpage(
  52. 'https://www.crunchyroll.com/?a=formhandler',
  53. None, 'Logging in', 'Wrong login info',
  54. data=urlencode_postdata({
  55. 'formname': 'RpcApiUser_Login',
  56. 'next_url': 'https://www.crunchyroll.com/acct/membership',
  57. 'name': username,
  58. 'password': password,
  59. }))
  60. '''
  61. login_page = self._download_webpage(
  62. self._LOGIN_URL, None, 'Downloading login page')
  63. def is_logged(webpage):
  64. return '<title>Redirecting' in webpage
  65. # Already logged in
  66. if is_logged(login_page):
  67. return
  68. login_form_str = self._search_regex(
  69. r'(?P<form><form[^>]+?id=(["\'])%s\2[^>]*>)' % self._LOGIN_FORM,
  70. login_page, 'login form', group='form')
  71. post_url = extract_attributes(login_form_str).get('action')
  72. if not post_url:
  73. post_url = self._LOGIN_URL
  74. elif not post_url.startswith('http'):
  75. post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
  76. login_form = self._form_hidden_inputs(self._LOGIN_FORM, login_page)
  77. login_form.update({
  78. 'login_form[name]': username,
  79. 'login_form[password]': password,
  80. })
  81. response = self._download_webpage(
  82. post_url, None, 'Logging in', 'Wrong login info',
  83. data=urlencode_postdata(login_form),
  84. headers={'Content-Type': 'application/x-www-form-urlencoded'})
  85. # Successful login
  86. if is_logged(response):
  87. return
  88. error = self._html_search_regex(
  89. '(?s)<ul[^>]+class=["\']messages["\'][^>]*>(.+?)</ul>',
  90. response, 'error message', default=None)
  91. if error:
  92. raise ExtractorError('Unable to login: %s' % error, expected=True)
  93. raise ExtractorError('Unable to log in')
  94. '''
  95. def _real_initialize(self):
  96. self._login()
  97. def _download_webpage(self, url_or_request, *args, **kwargs):
  98. request = (url_or_request if isinstance(url_or_request, compat_urllib_request.Request)
  99. else sanitized_Request(url_or_request))
  100. # Accept-Language must be set explicitly to accept any language to avoid issues
  101. # similar to https://github.com/rg3/youtube-dl/issues/6797.
  102. # Along with IP address Crunchyroll uses Accept-Language to guess whether georestriction
  103. # should be imposed or not (from what I can see it just takes the first language
  104. # ignoring the priority and requires it to correspond the IP). By the way this causes
  105. # Crunchyroll to not work in georestriction cases in some browsers that don't place
  106. # the locale lang first in header. However allowing any language seems to workaround the issue.
  107. request.add_header('Accept-Language', '*')
  108. return super(CrunchyrollBaseIE, self)._download_webpage(request, *args, **kwargs)
  109. @staticmethod
  110. def _add_skip_wall(url):
  111. parsed_url = compat_urlparse.urlparse(url)
  112. qs = compat_urlparse.parse_qs(parsed_url.query)
  113. # Always force skip_wall to bypass maturity wall, namely 18+ confirmation message:
  114. # > This content may be inappropriate for some people.
  115. # > Are you sure you want to continue?
  116. # since it's not disabled by default in crunchyroll account's settings.
  117. # See https://github.com/rg3/youtube-dl/issues/7202.
  118. qs['skip_wall'] = ['1']
  119. return compat_urlparse.urlunparse(
  120. parsed_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
  121. class CrunchyrollIE(CrunchyrollBaseIE, VRVIE):
  122. IE_NAME = 'crunchyroll'
  123. _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.(?:com|fr)/(?:media(?:-|/\?id=)|[^/]*/[^/?&]*?)(?P<video_id>[0-9]+))(?:[/?&]|$)'
  124. _TESTS = [{
  125. 'url': 'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
  126. 'info_dict': {
  127. 'id': '645513',
  128. 'ext': 'mp4',
  129. 'title': 'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
  130. 'description': 'md5:2d17137920c64f2f49981a7797d275ef',
  131. 'thumbnail': r're:^https?://.*\.jpg$',
  132. 'uploader': 'Yomiuri Telecasting Corporation (YTV)',
  133. 'upload_date': '20131013',
  134. 'url': 're:(?!.*&amp)',
  135. },
  136. 'params': {
  137. # rtmp
  138. 'skip_download': True,
  139. },
  140. }, {
  141. 'url': 'http://www.crunchyroll.com/media-589804/culture-japan-1',
  142. 'info_dict': {
  143. 'id': '589804',
  144. 'ext': 'flv',
  145. 'title': 'Culture Japan Episode 1 – Rebuilding Japan after the 3.11',
  146. 'description': 'md5:2fbc01f90b87e8e9137296f37b461c12',
  147. 'thumbnail': r're:^https?://.*\.jpg$',
  148. 'uploader': 'Danny Choo Network',
  149. 'upload_date': '20120213',
  150. },
  151. 'params': {
  152. # rtmp
  153. 'skip_download': True,
  154. },
  155. 'skip': 'Video gone',
  156. }, {
  157. 'url': 'http://www.crunchyroll.com/rezero-starting-life-in-another-world-/episode-5-the-morning-of-our-promise-is-still-distant-702409',
  158. 'info_dict': {
  159. 'id': '702409',
  160. 'ext': 'mp4',
  161. 'title': 'Re:ZERO -Starting Life in Another World- Episode 5 – The Morning of Our Promise Is Still Distant',
  162. 'description': 'md5:97664de1ab24bbf77a9c01918cb7dca9',
  163. 'thumbnail': r're:^https?://.*\.jpg$',
  164. 'uploader': 'TV TOKYO',
  165. 'upload_date': '20160508',
  166. },
  167. 'params': {
  168. # m3u8 download
  169. 'skip_download': True,
  170. },
  171. }, {
  172. 'url': 'http://www.crunchyroll.com/konosuba-gods-blessing-on-this-wonderful-world/episode-1-give-me-deliverance-from-this-judicial-injustice-727589',
  173. 'info_dict': {
  174. 'id': '727589',
  175. 'ext': 'mp4',
  176. 'title': "KONOSUBA -God's blessing on this wonderful world! 2 Episode 1 – Give Me Deliverance From This Judicial Injustice!",
  177. 'description': 'md5:cbcf05e528124b0f3a0a419fc805ea7d',
  178. 'thumbnail': r're:^https?://.*\.jpg$',
  179. 'uploader': 'Kadokawa Pictures Inc.',
  180. 'upload_date': '20170118',
  181. 'series': "KONOSUBA -God's blessing on this wonderful world!",
  182. 'season': "KONOSUBA -God's blessing on this wonderful world! 2",
  183. 'season_number': 2,
  184. 'episode': 'Give Me Deliverance From This Judicial Injustice!',
  185. 'episode_number': 1,
  186. },
  187. 'params': {
  188. # m3u8 download
  189. 'skip_download': True,
  190. },
  191. }, {
  192. 'url': 'http://www.crunchyroll.fr/girl-friend-beta/episode-11-goodbye-la-mode-661697',
  193. 'only_matching': True,
  194. }, {
  195. # geo-restricted (US), 18+ maturity wall, non-premium available
  196. 'url': 'http://www.crunchyroll.com/cosplay-complex-ova/episode-1-the-birth-of-the-cosplay-club-565617',
  197. 'only_matching': True,
  198. }, {
  199. # A description with double quotes
  200. 'url': 'http://www.crunchyroll.com/11eyes/episode-1-piros-jszaka-red-night-535080',
  201. 'info_dict': {
  202. 'id': '535080',
  203. 'ext': 'mp4',
  204. 'title': '11eyes Episode 1 – Red Night ~ Piros éjszaka',
  205. 'description': 'Kakeru and Yuka are thrown into an alternate nightmarish world they call "Red Night".',
  206. 'uploader': 'Marvelous AQL Inc.',
  207. 'upload_date': '20091021',
  208. },
  209. 'params': {
  210. # Just test metadata extraction
  211. 'skip_download': True,
  212. },
  213. }, {
  214. # make sure we can extract an uploader name that's not a link
  215. 'url': 'http://www.crunchyroll.com/hakuoki-reimeiroku/episode-1-dawn-of-the-divine-warriors-606899',
  216. 'info_dict': {
  217. 'id': '606899',
  218. 'ext': 'mp4',
  219. 'title': 'Hakuoki Reimeiroku Episode 1 – Dawn of the Divine Warriors',
  220. 'description': 'Ryunosuke was left to die, but Serizawa-san asked him a simple question "Do you want to live?"',
  221. 'uploader': 'Geneon Entertainment',
  222. 'upload_date': '20120717',
  223. },
  224. 'params': {
  225. # just test metadata extraction
  226. 'skip_download': True,
  227. },
  228. }, {
  229. # A video with a vastly different season name compared to the series name
  230. 'url': 'http://www.crunchyroll.com/nyarko-san-another-crawling-chaos/episode-1-test-590532',
  231. 'info_dict': {
  232. 'id': '590532',
  233. 'ext': 'mp4',
  234. 'title': 'Haiyoru! Nyaruani (ONA) Episode 1 – Test',
  235. 'description': 'Mahiro and Nyaruko talk about official certification.',
  236. 'uploader': 'TV TOKYO',
  237. 'upload_date': '20120305',
  238. 'series': 'Nyarko-san: Another Crawling Chaos',
  239. 'season': 'Haiyoru! Nyaruani (ONA)',
  240. },
  241. 'params': {
  242. # Just test metadata extraction
  243. 'skip_download': True,
  244. },
  245. }, {
  246. 'url': 'http://www.crunchyroll.com/media-723735',
  247. 'only_matching': True,
  248. }]
  249. _FORMAT_IDS = {
  250. '360': ('60', '106'),
  251. '480': ('61', '106'),
  252. '720': ('62', '106'),
  253. '1080': ('80', '108'),
  254. }
  255. def _decrypt_subtitles(self, data, iv, id):
  256. data = bytes_to_intlist(compat_b64decode(data))
  257. iv = bytes_to_intlist(compat_b64decode(iv))
  258. id = int(id)
  259. def obfuscate_key_aux(count, modulo, start):
  260. output = list(start)
  261. for _ in range(count):
  262. output.append(output[-1] + output[-2])
  263. # cut off start values
  264. output = output[2:]
  265. output = list(map(lambda x: x % modulo + 33, output))
  266. return output
  267. def obfuscate_key(key):
  268. num1 = int(floor(pow(2, 25) * sqrt(6.9)))
  269. num2 = (num1 ^ key) << 5
  270. num3 = key ^ num1
  271. num4 = num3 ^ (num3 >> 3) ^ num2
  272. prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
  273. shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode('ascii')).digest())
  274. # Extend 160 Bit hash to 256 Bit
  275. return shaHash + [0] * 12
  276. key = obfuscate_key(id)
  277. decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
  278. return zlib.decompress(decrypted_data)
  279. def _convert_subtitles_to_srt(self, sub_root):
  280. output = ''
  281. for i, event in enumerate(sub_root.findall('./events/event'), 1):
  282. start = event.attrib['start'].replace('.', ',')
  283. end = event.attrib['end'].replace('.', ',')
  284. text = event.attrib['text'].replace('\\N', '\n')
  285. output += '%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
  286. return output
  287. def _convert_subtitles_to_ass(self, sub_root):
  288. output = ''
  289. def ass_bool(strvalue):
  290. assvalue = '0'
  291. if strvalue == '1':
  292. assvalue = '-1'
  293. return assvalue
  294. output = '[Script Info]\n'
  295. output += 'Title: %s\n' % sub_root.attrib['title']
  296. output += 'ScriptType: v4.00+\n'
  297. output += 'WrapStyle: %s\n' % sub_root.attrib['wrap_style']
  298. output += 'PlayResX: %s\n' % sub_root.attrib['play_res_x']
  299. output += 'PlayResY: %s\n' % sub_root.attrib['play_res_y']
  300. output += """
  301. [V4+ Styles]
  302. Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
  303. """
  304. for style in sub_root.findall('./styles/style'):
  305. output += 'Style: ' + style.attrib['name']
  306. output += ',' + style.attrib['font_name']
  307. output += ',' + style.attrib['font_size']
  308. output += ',' + style.attrib['primary_colour']
  309. output += ',' + style.attrib['secondary_colour']
  310. output += ',' + style.attrib['outline_colour']
  311. output += ',' + style.attrib['back_colour']
  312. output += ',' + ass_bool(style.attrib['bold'])
  313. output += ',' + ass_bool(style.attrib['italic'])
  314. output += ',' + ass_bool(style.attrib['underline'])
  315. output += ',' + ass_bool(style.attrib['strikeout'])
  316. output += ',' + style.attrib['scale_x']
  317. output += ',' + style.attrib['scale_y']
  318. output += ',' + style.attrib['spacing']
  319. output += ',' + style.attrib['angle']
  320. output += ',' + style.attrib['border_style']
  321. output += ',' + style.attrib['outline']
  322. output += ',' + style.attrib['shadow']
  323. output += ',' + style.attrib['alignment']
  324. output += ',' + style.attrib['margin_l']
  325. output += ',' + style.attrib['margin_r']
  326. output += ',' + style.attrib['margin_v']
  327. output += ',' + style.attrib['encoding']
  328. output += '\n'
  329. output += """
  330. [Events]
  331. Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
  332. """
  333. for event in sub_root.findall('./events/event'):
  334. output += 'Dialogue: 0'
  335. output += ',' + event.attrib['start']
  336. output += ',' + event.attrib['end']
  337. output += ',' + event.attrib['style']
  338. output += ',' + event.attrib['name']
  339. output += ',' + event.attrib['margin_l']
  340. output += ',' + event.attrib['margin_r']
  341. output += ',' + event.attrib['margin_v']
  342. output += ',' + event.attrib['effect']
  343. output += ',' + event.attrib['text']
  344. output += '\n'
  345. return output
  346. def _extract_subtitles(self, subtitle):
  347. sub_root = compat_etree_fromstring(subtitle)
  348. return [{
  349. 'ext': 'srt',
  350. 'data': self._convert_subtitles_to_srt(sub_root),
  351. }, {
  352. 'ext': 'ass',
  353. 'data': self._convert_subtitles_to_ass(sub_root),
  354. }]
  355. def _get_subtitles(self, video_id, webpage):
  356. subtitles = {}
  357. for sub_id, sub_name in re.findall(r'\bssid=([0-9]+)"[^>]+?\btitle="([^"]+)', webpage):
  358. sub_doc = self._call_rpc_api(
  359. 'Subtitle_GetXml', video_id,
  360. 'Downloading subtitles for ' + sub_name, data={
  361. 'subtitle_script_id': sub_id,
  362. })
  363. if sub_doc is None:
  364. continue
  365. sid = sub_doc.get('id')
  366. iv = xpath_text(sub_doc, 'iv', 'subtitle iv')
  367. data = xpath_text(sub_doc, 'data', 'subtitle data')
  368. if not sid or not iv or not data:
  369. continue
  370. subtitle = self._decrypt_subtitles(data, iv, sid).decode('utf-8')
  371. lang_code = self._search_regex(r'lang_code=["\']([^"\']+)', subtitle, 'subtitle_lang_code', fatal=False)
  372. if not lang_code:
  373. continue
  374. subtitles[lang_code] = self._extract_subtitles(subtitle)
  375. return subtitles
  376. def _real_extract(self, url):
  377. mobj = re.match(self._VALID_URL, url)
  378. video_id = mobj.group('video_id')
  379. if mobj.group('prefix') == 'm':
  380. mobile_webpage = self._download_webpage(url, video_id, 'Downloading mobile webpage')
  381. webpage_url = self._search_regex(r'<link rel="canonical" href="([^"]+)" />', mobile_webpage, 'webpage_url')
  382. else:
  383. webpage_url = 'http://www.' + mobj.group('url')
  384. webpage = self._download_webpage(
  385. self._add_skip_wall(webpage_url), video_id,
  386. headers=self.geo_verification_headers())
  387. note_m = self._html_search_regex(
  388. r'<div class="showmedia-trailer-notice">(.+?)</div>',
  389. webpage, 'trailer-notice', default='')
  390. if note_m:
  391. raise ExtractorError(note_m)
  392. mobj = re.search(r'Page\.messaging_box_controller\.addItems\(\[(?P<msg>{.+?})\]\)', webpage)
  393. if mobj:
  394. msg = json.loads(mobj.group('msg'))
  395. if msg.get('type') == 'error':
  396. raise ExtractorError('crunchyroll returned error: %s' % msg['message_body'], expected=True)
  397. if 'To view this, please log in to verify you are 18 or older.' in webpage:
  398. self.raise_login_required()
  399. media = self._parse_json(self._search_regex(
  400. r'vilos\.config\.media\s*=\s*({.+?});',
  401. webpage, 'vilos media', default='{}'), video_id)
  402. media_metadata = media.get('metadata') or {}
  403. language = self._search_regex(
  404. r'(?:vilos\.config\.player\.language|LOCALE)\s*=\s*(["\'])(?P<lang>(?:(?!\1).)+)\1',
  405. webpage, 'language', default=None, group='lang')
  406. video_title = self._html_search_regex(
  407. r'(?s)<h1[^>]*>((?:(?!<h1).)*?<span[^>]+itemprop=["\']title["\'][^>]*>(?:(?!<h1).)+?)</h1>',
  408. webpage, 'video_title')
  409. video_title = re.sub(r' {2,}', ' ', video_title)
  410. video_description = (self._parse_json(self._html_search_regex(
  411. r'<script[^>]*>\s*.+?\[media_id=%s\].+?({.+?"description"\s*:.+?})\);' % video_id,
  412. webpage, 'description', default='{}'), video_id) or media_metadata).get('description')
  413. if video_description:
  414. video_description = lowercase_escape(video_description.replace(r'\r\n', '\n'))
  415. video_upload_date = self._html_search_regex(
  416. [r'<div>Availability for free users:(.+?)</div>', r'<div>[^<>]+<span>\s*(.+?\d{4})\s*</span></div>'],
  417. webpage, 'video_upload_date', fatal=False, flags=re.DOTALL)
  418. if video_upload_date:
  419. video_upload_date = unified_strdate(video_upload_date)
  420. video_uploader = self._html_search_regex(
  421. # try looking for both an uploader that's a link and one that's not
  422. [r'<a[^>]+href="/publisher/[^"]+"[^>]*>([^<]+)</a>', r'<div>\s*Publisher:\s*<span>\s*(.+?)\s*</span>\s*</div>'],
  423. webpage, 'video_uploader', fatal=False)
  424. formats = []
  425. for stream in media.get('streams', []):
  426. audio_lang = stream.get('audio_lang')
  427. hardsub_lang = stream.get('hardsub_lang')
  428. vrv_formats = self._extract_vrv_formats(
  429. stream.get('url'), video_id, stream.get('format'),
  430. audio_lang, hardsub_lang)
  431. for f in vrv_formats:
  432. if not hardsub_lang:
  433. f['preference'] = 1
  434. language_preference = 0
  435. if audio_lang == language:
  436. language_preference += 1
  437. if hardsub_lang == language:
  438. language_preference += 1
  439. if language_preference:
  440. f['language_preference'] = language_preference
  441. formats.extend(vrv_formats)
  442. if not formats:
  443. available_fmts = []
  444. for a, fmt in re.findall(r'(<a[^>]+token=["\']showmedia\.([0-9]{3,4})p["\'][^>]+>)', webpage):
  445. attrs = extract_attributes(a)
  446. href = attrs.get('href')
  447. if href and '/freetrial' in href:
  448. continue
  449. available_fmts.append(fmt)
  450. if not available_fmts:
  451. for p in (r'token=["\']showmedia\.([0-9]{3,4})p"', r'showmedia\.([0-9]{3,4})p'):
  452. available_fmts = re.findall(p, webpage)
  453. if available_fmts:
  454. break
  455. if not available_fmts:
  456. available_fmts = self._FORMAT_IDS.keys()
  457. video_encode_ids = []
  458. for fmt in available_fmts:
  459. stream_quality, stream_format = self._FORMAT_IDS[fmt]
  460. video_format = fmt + 'p'
  461. stream_infos = []
  462. streamdata = self._call_rpc_api(
  463. 'VideoPlayer_GetStandardConfig', video_id,
  464. 'Downloading media info for %s' % video_format, data={
  465. 'media_id': video_id,
  466. 'video_format': stream_format,
  467. 'video_quality': stream_quality,
  468. 'current_page': url,
  469. })
  470. if streamdata is not None:
  471. stream_info = streamdata.find('./{default}preload/stream_info')
  472. if stream_info is not None:
  473. stream_infos.append(stream_info)
  474. stream_info = self._call_rpc_api(
  475. 'VideoEncode_GetStreamInfo', video_id,
  476. 'Downloading stream info for %s' % video_format, data={
  477. 'media_id': video_id,
  478. 'video_format': stream_format,
  479. 'video_encode_quality': stream_quality,
  480. })
  481. if stream_info is not None:
  482. stream_infos.append(stream_info)
  483. for stream_info in stream_infos:
  484. video_encode_id = xpath_text(stream_info, './video_encode_id')
  485. if video_encode_id in video_encode_ids:
  486. continue
  487. video_encode_ids.append(video_encode_id)
  488. video_file = xpath_text(stream_info, './file')
  489. if not video_file:
  490. continue
  491. if video_file.startswith('http'):
  492. formats.extend(self._extract_m3u8_formats(
  493. video_file, video_id, 'mp4', entry_protocol='m3u8_native',
  494. m3u8_id='hls', fatal=False))
  495. continue
  496. video_url = xpath_text(stream_info, './host')
  497. if not video_url:
  498. continue
  499. metadata = stream_info.find('./metadata')
  500. format_info = {
  501. 'format': video_format,
  502. 'height': int_or_none(xpath_text(metadata, './height')),
  503. 'width': int_or_none(xpath_text(metadata, './width')),
  504. }
  505. if '.fplive.net/' in video_url:
  506. video_url = re.sub(r'^rtmpe?://', 'http://', video_url.strip())
  507. parsed_video_url = compat_urlparse.urlparse(video_url)
  508. direct_video_url = compat_urlparse.urlunparse(parsed_video_url._replace(
  509. netloc='v.lvlt.crcdn.net',
  510. path='%s/%s' % (remove_end(parsed_video_url.path, '/'), video_file.split(':')[-1])))
  511. if self._is_valid_url(direct_video_url, video_id, video_format):
  512. format_info.update({
  513. 'format_id': 'http-' + video_format,
  514. 'url': direct_video_url,
  515. })
  516. formats.append(format_info)
  517. continue
  518. format_info.update({
  519. 'format_id': 'rtmp-' + video_format,
  520. 'url': video_url,
  521. 'play_path': video_file,
  522. 'ext': 'flv',
  523. })
  524. formats.append(format_info)
  525. self._sort_formats(formats, ('preference', 'language_preference', 'height', 'width', 'tbr', 'fps'))
  526. metadata = self._call_rpc_api(
  527. 'VideoPlayer_GetMediaMetadata', video_id,
  528. note='Downloading media info', data={
  529. 'media_id': video_id,
  530. })
  531. subtitles = {}
  532. for subtitle in media.get('subtitles', []):
  533. subtitle_url = subtitle.get('url')
  534. if not subtitle_url:
  535. continue
  536. subtitles.setdefault(subtitle.get('language', 'enUS'), []).append({
  537. 'url': subtitle_url,
  538. 'ext': subtitle.get('format', 'ass'),
  539. })
  540. if not subtitles:
  541. subtitles = self.extract_subtitles(video_id, webpage)
  542. # webpage provide more accurate data than series_title from XML
  543. series = self._html_search_regex(
  544. r'(?s)<h\d[^>]+\bid=["\']showmedia_about_episode_num[^>]+>(.+?)</h\d',
  545. webpage, 'series', fatal=False)
  546. season = xpath_text(metadata, 'series_title')
  547. episode = xpath_text(metadata, 'episode_title') or media_metadata.get('title')
  548. episode_number = int_or_none(xpath_text(metadata, 'episode_number') or media_metadata.get('episode_number'))
  549. season_number = int_or_none(self._search_regex(
  550. r'(?s)<h\d[^>]+id=["\']showmedia_about_episode_num[^>]+>.+?</h\d>\s*<h4>\s*Season (\d+)',
  551. webpage, 'season number', default=None))
  552. return {
  553. 'id': video_id,
  554. 'title': video_title,
  555. 'description': video_description,
  556. 'duration': float_or_none(media_metadata.get('duration'), 1000),
  557. 'thumbnail': xpath_text(metadata, 'episode_image_url') or media_metadata.get('thumbnail', {}).get('url'),
  558. 'uploader': video_uploader,
  559. 'upload_date': video_upload_date,
  560. 'series': series,
  561. 'season': season,
  562. 'season_number': season_number,
  563. 'episode': episode,
  564. 'episode_number': episode_number,
  565. 'subtitles': subtitles,
  566. 'formats': formats,
  567. }
  568. class CrunchyrollShowPlaylistIE(CrunchyrollBaseIE):
  569. IE_NAME = 'crunchyroll:playlist'
  570. _VALID_URL = r'https?://(?:(?P<prefix>www|m)\.)?(?P<url>crunchyroll\.com/(?!(?:news|anime-news|library|forum|launchcalendar|lineup|store|comics|freetrial|login|media-\d+))(?P<id>[\w\-]+))/?(?:\?|$)'
  571. _TESTS = [{
  572. 'url': 'http://www.crunchyroll.com/a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
  573. 'info_dict': {
  574. 'id': 'a-bridge-to-the-starry-skies-hoshizora-e-kakaru-hashi',
  575. 'title': 'A Bridge to the Starry Skies - Hoshizora e Kakaru Hashi'
  576. },
  577. 'playlist_count': 13,
  578. }, {
  579. # geo-restricted (US), 18+ maturity wall, non-premium available
  580. 'url': 'http://www.crunchyroll.com/cosplay-complex-ova',
  581. 'info_dict': {
  582. 'id': 'cosplay-complex-ova',
  583. 'title': 'Cosplay Complex OVA'
  584. },
  585. 'playlist_count': 3,
  586. 'skip': 'Georestricted',
  587. }, {
  588. # geo-restricted (US), 18+ maturity wall, non-premium will be available since 2015.11.14
  589. 'url': 'http://www.crunchyroll.com/ladies-versus-butlers?skip_wall=1',
  590. 'only_matching': True,
  591. }]
  592. def _real_extract(self, url):
  593. show_id = self._match_id(url)
  594. webpage = self._download_webpage(
  595. self._add_skip_wall(url), show_id,
  596. headers=self.geo_verification_headers())
  597. title = self._html_search_regex(
  598. r'(?s)<h1[^>]*>\s*<span itemprop="name">(.*?)</span>',
  599. webpage, 'title')
  600. episode_paths = re.findall(
  601. r'(?s)<li id="showview_videos_media_(\d+)"[^>]+>.*?<a href="([^"]+)"',
  602. webpage)
  603. entries = [
  604. self.url_result('http://www.crunchyroll.com' + ep, 'Crunchyroll', ep_id)
  605. for ep_id, ep in episode_paths
  606. ]
  607. entries.reverse()
  608. return {
  609. '_type': 'playlist',
  610. 'id': show_id,
  611. 'title': title,
  612. 'entries': entries,
  613. }