youku.py 9.0 KB

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