crunchyroll.py 27 KB

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