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.

178 lines
8.0 KiB

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