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.

467 lines
20 KiB

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