youku.py 8.5 KB

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