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.

235 lines
7.5 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import base64
  4. from .common import InfoExtractor
  5. from ..utils import ExtractorError
  6. from ..compat import (
  7. compat_urllib_parse,
  8. compat_ord,
  9. compat_urllib_request,
  10. )
  11. class YoukuIE(InfoExtractor):
  12. IE_NAME = 'youku'
  13. _VALID_URL = r'''(?x)
  14. (?:
  15. http://(?:v|player)\.youku\.com/(?:v_show/id_|player\.php/sid/)|
  16. youku:)
  17. (?P<id>[A-Za-z0-9]+)(?:\.html|/v\.swf|)
  18. '''
  19. _TESTS = [{
  20. 'url': 'http://v.youku.com/v_show/id_XMTc1ODE5Njcy.html',
  21. 'md5': '5f3af4192eabacc4501508d54a8cabd7',
  22. 'info_dict': {
  23. 'id': 'XMTc1ODE5Njcy_part1',
  24. 'title': '★Smile﹗♡ Git Fresh -Booty Music舞蹈.',
  25. 'ext': 'flv'
  26. }
  27. }, {
  28. 'url': 'http://player.youku.com/player.php/sid/XNDgyMDQ2NTQw/v.swf',
  29. 'only_matching': True,
  30. }, {
  31. 'url': 'http://v.youku.com/v_show/id_XODgxNjg1Mzk2_ev_1.html',
  32. 'info_dict': {
  33. 'id': 'XODgxNjg1Mzk2',
  34. 'title': '武媚娘传奇 85',
  35. },
  36. 'playlist_count': 11,
  37. }, {
  38. 'url': 'http://v.youku.com/v_show/id_XMTI1OTczNDM5Mg==.html',
  39. 'info_dict': {
  40. 'id': 'XMTI1OTczNDM5Mg',
  41. 'title': '花千骨 04',
  42. },
  43. 'playlist_count': 13,
  44. 'skip': 'Available in China only',
  45. }]
  46. def construct_video_urls(self, data1, data2):
  47. # get sid, token
  48. def yk_t(s1, s2):
  49. ls = list(range(256))
  50. t = 0
  51. for i in range(256):
  52. t = (t + ls[i] + compat_ord(s1[i % len(s1)])) % 256
  53. ls[i], ls[t] = ls[t], ls[i]
  54. s = bytearray()
  55. x, y = 0, 0
  56. for i in range(len(s2)):
  57. y = (y + 1) % 256
  58. x = (x + ls[y]) % 256
  59. ls[x], ls[y] = ls[y], ls[x]
  60. s.append(compat_ord(s2[i]) ^ ls[(ls[x] + ls[y]) % 256])
  61. return bytes(s)
  62. sid, token = yk_t(
  63. b'becaf9be', base64.b64decode(data2['ep'].encode('ascii'))
  64. ).decode('ascii').split('_')
  65. # get oip
  66. oip = data2['ip']
  67. # get fileid
  68. string_ls = list(
  69. 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890')
  70. shuffled_string_ls = []
  71. seed = data1['seed']
  72. N = len(string_ls)
  73. for ii in range(N):
  74. seed = (seed * 0xd3 + 0x754f) % 0x10000
  75. idx = seed * len(string_ls) // 0x10000
  76. shuffled_string_ls.append(string_ls[idx])
  77. del string_ls[idx]
  78. fileid_dict = {}
  79. for format in data1['streamtypes']:
  80. streamfileid = [
  81. int(i) for i in data1['streamfileids'][format].strip('*').split('*')]
  82. fileid = ''.join(
  83. [shuffled_string_ls[i] for i in streamfileid])
  84. fileid_dict[format] = fileid[:8] + '%s' + fileid[10:]
  85. def get_fileid(format, n):
  86. fileid = fileid_dict[format] % hex(int(n))[2:].upper().zfill(2)
  87. return fileid
  88. # get ep
  89. def generate_ep(format, n):
  90. fileid = get_fileid(format, n)
  91. ep_t = yk_t(
  92. b'bf7e5f01',
  93. ('%s_%s_%s' % (sid, fileid, token)).encode('ascii')
  94. )
  95. ep = base64.b64encode(ep_t).decode('ascii')
  96. return ep
  97. # generate video_urls
  98. video_urls_dict = {}
  99. for format in data1['streamtypes']:
  100. video_urls = []
  101. for dt in data1['segs'][format]:
  102. n = str(int(dt['no']))
  103. param = {
  104. 'K': dt['k'],
  105. 'hd': self.get_hd(format),
  106. 'myp': 0,
  107. 'ts': dt['seconds'],
  108. 'ypp': 0,
  109. 'ctype': 12,
  110. 'ev': 1,
  111. 'token': token,
  112. 'oip': oip,
  113. 'ep': generate_ep(format, n)
  114. }
  115. video_url = \
  116. 'http://k.youku.com/player/getFlvPath/' + \
  117. 'sid/' + sid + \
  118. '_' + str(int(n) + 1).zfill(2) + \
  119. '/st/' + self.parse_ext_l(format) + \
  120. '/fileid/' + get_fileid(format, n) + '?' + \
  121. compat_urllib_parse.urlencode(param)
  122. video_urls.append(video_url)
  123. video_urls_dict[format] = video_urls
  124. return video_urls_dict
  125. def get_hd(self, fm):
  126. hd_id_dict = {
  127. 'flv': '0',
  128. 'mp4': '1',
  129. 'hd2': '2',
  130. 'hd3': '3',
  131. '3gp': '0',
  132. '3gphd': '1'
  133. }
  134. return hd_id_dict[fm]
  135. def parse_ext_l(self, fm):
  136. ext_dict = {
  137. 'flv': 'flv',
  138. 'mp4': 'mp4',
  139. 'hd2': 'flv',
  140. 'hd3': 'flv',
  141. '3gp': 'flv',
  142. '3gphd': 'mp4'
  143. }
  144. return ext_dict[fm]
  145. def get_format_name(self, fm):
  146. _dict = {
  147. '3gp': 'h6',
  148. '3gphd': 'h5',
  149. 'flv': 'h4',
  150. 'mp4': 'h3',
  151. 'hd2': 'h2',
  152. 'hd3': 'h1'
  153. }
  154. return _dict[fm]
  155. def _real_extract(self, url):
  156. video_id = self._match_id(url)
  157. def retrieve_data(req_url, note):
  158. req = compat_urllib_request.Request(req_url)
  159. cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
  160. if cn_verification_proxy:
  161. req.add_header('Ytdl-request-proxy', cn_verification_proxy)
  162. raw_data = self._download_json(req, video_id, note=note)
  163. return raw_data['data'][0]
  164. # request basic data
  165. data1 = retrieve_data(
  166. 'http://v.youku.com/player/getPlayList/VideoIDS/%s' % video_id,
  167. 'Downloading JSON metadata 1')
  168. data2 = retrieve_data(
  169. 'http://v.youku.com/player/getPlayList/VideoIDS/%s/Pf/4/ctype/12/ev/1' % video_id,
  170. 'Downloading JSON metadata 2')
  171. error_code = data1.get('error_code')
  172. if error_code:
  173. error = data1.get('error')
  174. if error is not None and '因版权原因无法观看此视频' in error:
  175. raise ExtractorError(
  176. 'Youku said: Sorry, this video is available in China only', expected=True)
  177. else:
  178. msg = 'Youku server reported error %i' % error_code
  179. if error is not None:
  180. msg += ': ' + error
  181. raise ExtractorError(msg)
  182. title = data1['title']
  183. # generate video_urls_dict
  184. video_urls_dict = self.construct_video_urls(data1, data2)
  185. # construct info
  186. entries = [{
  187. 'id': '%s_part%d' % (video_id, i + 1),
  188. 'title': title,
  189. 'formats': [],
  190. # some formats are not available for all parts, we have to detect
  191. # which one has all
  192. } for i in range(max(len(v) for v in data1['segs'].values()))]
  193. for fm in data1['streamtypes']:
  194. video_urls = video_urls_dict[fm]
  195. for video_url, seg, entry in zip(video_urls, data1['segs'][fm], entries):
  196. entry['formats'].append({
  197. 'url': video_url,
  198. 'format_id': self.get_format_name(fm),
  199. 'ext': self.parse_ext_l(fm),
  200. 'filesize': int(seg['size']),
  201. })
  202. return {
  203. '_type': 'multi_video',
  204. 'id': video_id,
  205. 'title': title,
  206. 'entries': entries,
  207. }