crunchyroll.py 25 KB

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