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.

171 lines
7.7 KiB

  1. # encoding: utf-8
  2. import re, base64, zlib
  3. from hashlib import sha1
  4. from math import pow, sqrt, floor
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. ExtractorError,
  8. compat_urllib_parse,
  9. compat_urllib_request,
  10. bytes_to_intlist,
  11. intlist_to_bytes,
  12. unified_strdate,
  13. clean_html,
  14. )
  15. from ..aes import (
  16. aes_cbc_decrypt,
  17. inc,
  18. )
  19. class CrunchyrollIE(InfoExtractor):
  20. _VALID_URL = r'(?:https?://)?(?:www\.)?(?P<url>crunchyroll\.com/[^/]*/[^/?&]*?(?P<video_id>[0-9]+))(?:[/?&]|$)'
  21. _TESTS = [{
  22. u'url': u'http://www.crunchyroll.com/wanna-be-the-strongest-in-the-world/episode-1-an-idol-wrestler-is-born-645513',
  23. u'file': u'645513.flv',
  24. #u'md5': u'b1639fd6ddfaa43788c85f6d1dddd412',
  25. u'info_dict': {
  26. u'title': u'Wanna be the Strongest in the World Episode 1 – An Idol-Wrestler is Born!',
  27. u'description': u'md5:2d17137920c64f2f49981a7797d275ef',
  28. u'thumbnail': u'http://img1.ak.crunchyroll.com/i/spire1-tmb/20c6b5e10f1a47b10516877d3c039cae1380951166_full.jpg',
  29. u'uploader': u'Yomiuri Telecasting Corporation (YTV)',
  30. u'upload_date': u'20131013',
  31. },
  32. u'params': {
  33. # rtmp
  34. u'skip_download': True,
  35. },
  36. }]
  37. _FORMAT_IDS = {
  38. u'360': (u'60', u'106'),
  39. u'480': (u'61', u'106'),
  40. u'720': (u'62', u'106'),
  41. u'1080': (u'80', u'108'),
  42. }
  43. def _decrypt_subtitles(self, data, iv, id):
  44. data = bytes_to_intlist(data)
  45. iv = bytes_to_intlist(iv)
  46. id = int(id)
  47. def obfuscate_key_aux(count, modulo, start):
  48. output = list(start)
  49. for _ in range(count):
  50. output.append(output[-1] + output[-2])
  51. # cut off start values
  52. output = output[2:]
  53. output = list(map(lambda x: x % modulo + 33, output))
  54. return output
  55. def obfuscate_key(key):
  56. num1 = int(floor(pow(2, 25) * sqrt(6.9)))
  57. num2 = (num1 ^ key) << 5
  58. num3 = key ^ num1
  59. num4 = num3 ^ (num3 >> 3) ^ num2
  60. prefix = intlist_to_bytes(obfuscate_key_aux(20, 97, (1, 2)))
  61. shaHash = bytes_to_intlist(sha1(prefix + str(num4).encode(u'ascii')).digest())
  62. # Extend 160 Bit hash to 256 Bit
  63. return shaHash + [0] * 12
  64. key = obfuscate_key(id)
  65. class Counter:
  66. __value = iv
  67. def next_value(self):
  68. temp = self.__value
  69. self.__value = inc(self.__value)
  70. return temp
  71. decrypted_data = intlist_to_bytes(aes_cbc_decrypt(data, key, iv))
  72. return zlib.decompress(decrypted_data)
  73. def _convert_subtitles_to_srt(self, subtitles):
  74. i=1
  75. output = u''
  76. for start, end, text in re.findall(r'<event [^>]*?start="([^"]+)" [^>]*?end="([^"]+)" [^>]*?text="([^"]+)"[^>]*?>', subtitles):
  77. start = start.replace(u'.', u',')
  78. end = end.replace(u'.', u',')
  79. text = clean_html(text)
  80. text = text.replace(u'\\N', u'\n')
  81. if not text:
  82. continue
  83. output += u'%d\n%s --> %s\n%s\n\n' % (i, start, end, text)
  84. i+=1
  85. return output
  86. def _real_extract(self,url):
  87. mobj = re.match(self._VALID_URL, url)
  88. webpage_url = u'http://www.' + mobj.group('url')
  89. video_id = mobj.group(u'video_id')
  90. webpage = self._download_webpage(webpage_url, video_id)
  91. note_m = self._html_search_regex(r'<div class="showmedia-trailer-notice">(.+?)</div>', webpage, u'trailer-notice', default=u'')
  92. if note_m:
  93. raise ExtractorError(note_m)
  94. video_title = self._html_search_regex(r'<h1[^>]*>(.+?)</h1>', webpage, u'video_title', flags=re.DOTALL)
  95. video_title = re.sub(r' {2,}', u' ', video_title)
  96. video_description = self._html_search_regex(r'"description":"([^"]+)', webpage, u'video_description', default=u'')
  97. if not video_description:
  98. video_description = None
  99. video_upload_date = self._html_search_regex(r'<div>Availability for free users:(.+?)</div>', webpage, u'video_upload_date', fatal=False, flags=re.DOTALL)
  100. if video_upload_date:
  101. video_upload_date = unified_strdate(video_upload_date)
  102. video_uploader = self._html_search_regex(r'<div>\s*Publisher:(.+?)</div>', webpage, u'video_uploader', fatal=False, flags=re.DOTALL)
  103. playerdata_url = compat_urllib_parse.unquote(self._html_search_regex(r'"config_url":"([^"]+)', webpage, u'playerdata_url'))
  104. playerdata_req = compat_urllib_request.Request(playerdata_url)
  105. playerdata_req.data = compat_urllib_parse.urlencode({u'current_page': webpage_url})
  106. playerdata_req.add_header(u'Content-Type', u'application/x-www-form-urlencoded')
  107. playerdata = self._download_webpage(playerdata_req, video_id, note=u'Downloading media info')
  108. stream_id = self._search_regex(r'<media_id>([^<]+)', playerdata, u'stream_id')
  109. video_thumbnail = self._search_regex(r'<episode_image_url>([^<]+)', playerdata, u'thumbnail', fatal=False)
  110. formats = []
  111. for fmt in re.findall(r'\?p([0-9]{3,4})=1', webpage):
  112. stream_quality, stream_format = self._FORMAT_IDS[fmt]
  113. video_format = fmt+u'p'
  114. streamdata_req = compat_urllib_request.Request(u'http://www.crunchyroll.com/xml/')
  115. # urlencode doesn't work!
  116. streamdata_req.data = u'req=RpcApiVideoEncode%5FGetStreamInfo&video%5Fencode%5Fquality='+stream_quality+u'&media%5Fid='+stream_id+u'&video%5Fformat='+stream_format
  117. streamdata_req.add_header(u'Content-Type', u'application/x-www-form-urlencoded')
  118. streamdata_req.add_header(u'Content-Length', str(len(streamdata_req.data)))
  119. streamdata = self._download_webpage(streamdata_req, video_id, note=u'Downloading media info for '+video_format)
  120. video_url = self._search_regex(r'<host>([^<]+)', streamdata, u'video_url')
  121. video_play_path = self._search_regex(r'<file>([^<]+)', streamdata, u'video_play_path')
  122. formats.append({
  123. u'url': video_url,
  124. u'play_path': video_play_path,
  125. u'ext': 'flv',
  126. u'format': video_format,
  127. u'format_id': video_format,
  128. })
  129. subtitles = {}
  130. for sub_id, sub_name in re.findall(r'\?ssid=([0-9]+)" title="([^"]+)', webpage):
  131. sub_page = self._download_webpage(u'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id='+sub_id,\
  132. video_id, note=u'Downloading subtitles for '+sub_name)
  133. id = self._search_regex(r'id=\'([0-9]+)', sub_page, u'subtitle_id', fatal=False)
  134. iv = self._search_regex(r'<iv>([^<]+)', sub_page, u'subtitle_iv', fatal=False)
  135. data = self._search_regex(r'<data>([^<]+)', sub_page, u'subtitle_data', fatal=False)
  136. if not id or not iv or not data:
  137. continue
  138. id = int(id)
  139. iv = base64.b64decode(iv)
  140. data = base64.b64decode(data)
  141. subtitle = self._decrypt_subtitles(data, iv, id).decode(u'utf-8')
  142. lang_code = self._search_regex(r'lang_code=\'([^\']+)', subtitle, u'subtitle_lang_code', fatal=False)
  143. if not lang_code:
  144. continue
  145. subtitles[lang_code] = self._convert_subtitles_to_srt(subtitle)
  146. return {
  147. u'id': video_id,
  148. u'title': video_title,
  149. u'description': video_description,
  150. u'thumbnail': video_thumbnail,
  151. u'uploader': video_uploader,
  152. u'upload_date': video_upload_date,
  153. u'subtitles': subtitles,
  154. u'formats': formats,
  155. }