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.

285 lines
9.0 KiB

Switch codebase to use sanitized_Request instead of compat_urllib_request.Request [downloader/dash] Use sanitized_Request [downloader/http] Use sanitized_Request [atresplayer] Use sanitized_Request [bambuser] Use sanitized_Request [bliptv] Use sanitized_Request [brightcove] Use sanitized_Request [cbs] Use sanitized_Request [ceskatelevize] Use sanitized_Request [collegerama] Use sanitized_Request [extractor/common] Use sanitized_Request [crunchyroll] Use sanitized_Request [dailymotion] Use sanitized_Request [dcn] Use sanitized_Request [dramafever] Use sanitized_Request [dumpert] Use sanitized_Request [eitb] Use sanitized_Request [escapist] Use sanitized_Request [everyonesmixtape] Use sanitized_Request [extremetube] Use sanitized_Request [facebook] Use sanitized_Request [fc2] Use sanitized_Request [flickr] Use sanitized_Request [4tube] Use sanitized_Request [gdcvault] Use sanitized_Request [extractor/generic] Use sanitized_Request [hearthisat] Use sanitized_Request [hotnewhiphop] Use sanitized_Request [hypem] Use sanitized_Request [iprima] Use sanitized_Request [ivi] Use sanitized_Request [keezmovies] Use sanitized_Request [letv] Use sanitized_Request [lynda] Use sanitized_Request [metacafe] Use sanitized_Request [minhateca] Use sanitized_Request [miomio] Use sanitized_Request [meovideo] Use sanitized_Request [mofosex] Use sanitized_Request [moniker] Use sanitized_Request [mooshare] Use sanitized_Request [movieclips] Use sanitized_Request [mtv] Use sanitized_Request [myvideo] Use sanitized_Request [neteasemusic] Use sanitized_Request [nfb] Use sanitized_Request [niconico] Use sanitized_Request [noco] Use sanitized_Request [nosvideo] Use sanitized_Request [novamov] Use sanitized_Request [nowness] Use sanitized_Request [nuvid] Use sanitized_Request [played] Use sanitized_Request [pluralsight] Use sanitized_Request [pornhub] Use sanitized_Request [pornotube] Use sanitized_Request [primesharetv] Use sanitized_Request [promptfile] Use sanitized_Request [qqmusic] Use sanitized_Request [rtve] Use sanitized_Request [safari] Use sanitized_Request [sandia] Use sanitized_Request [shared] Use sanitized_Request [sharesix] Use sanitized_Request [sina] Use sanitized_Request [smotri] Use sanitized_Request [sohu] Use sanitized_Request [spankwire] Use sanitized_Request [sportdeutschland] Use sanitized_Request [streamcloud] Use sanitized_Request [streamcz] Use sanitized_Request [tapely] Use sanitized_Request [tube8] Use sanitized_Request [tubitv] Use sanitized_Request [twitch] Use sanitized_Request [twitter] Use sanitized_Request [udemy] Use sanitized_Request [vbox7] Use sanitized_Request [veoh] Use sanitized_Request [vessel] Use sanitized_Request [vevo] Use sanitized_Request [viddler] Use sanitized_Request [videomega] Use sanitized_Request [viewvster] Use sanitized_Request [viki] Use sanitized_Request [vk] Use sanitized_Request [vodlocker] Use sanitized_Request [voicerepublic] Use sanitized_Request [wistia] Use sanitized_Request [xfileshare] Use sanitized_Request [xtube] Use sanitized_Request [xvideos] Use sanitized_Request [yandexmusic] Use sanitized_Request [youku] Use sanitized_Request [youporn] Use sanitized_Request [youtube] Use sanitized_Request [patreon] Use sanitized_Request [extractor/common] Remove unused import [nfb] PEP 8
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import base64
  4. import random
  5. import string
  6. import time
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_urllib_parse_urlencode,
  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. # MD5 is unstable
  27. 'url': 'http://v.youku.com/v_show/id_XMTc1ODE5Njcy.html',
  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. 'skip': 'Available in China only',
  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. }, {
  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. # /play/get.json contains streams with "channel_type":"tail"
  64. 'url': 'http://v.youku.com/v_show/id_XOTUxMzg4NDMy.html',
  65. 'info_dict': {
  66. 'id': 'XOTUxMzg4NDMy',
  67. 'title': '我的世界☆明月庄主☆车震猎杀☆杀人艺术Minecraft',
  68. },
  69. 'playlist_count': 6,
  70. }]
  71. def construct_video_urls(self, data):
  72. # get sid, token
  73. def yk_t(s1, s2):
  74. ls = list(range(256))
  75. t = 0
  76. for i in range(256):
  77. t = (t + ls[i] + compat_ord(s1[i % len(s1)])) % 256
  78. ls[i], ls[t] = ls[t], ls[i]
  79. s = bytearray()
  80. x, y = 0, 0
  81. for i in range(len(s2)):
  82. y = (y + 1) % 256
  83. x = (x + ls[y]) % 256
  84. ls[x], ls[y] = ls[y], ls[x]
  85. s.append(compat_ord(s2[i]) ^ ls[(ls[x] + ls[y]) % 256])
  86. return bytes(s)
  87. sid, token = yk_t(
  88. b'becaf9be', base64.b64decode(data['security']['encrypt_string'].encode('ascii'))
  89. ).decode('ascii').split('_')
  90. # get oip
  91. oip = data['security']['ip']
  92. fileid_dict = {}
  93. for stream in data['stream']:
  94. if stream.get('channel_type') == 'tail':
  95. continue
  96. format = stream.get('stream_type')
  97. fileid = stream['stream_fileid']
  98. fileid_dict[format] = fileid
  99. def get_fileid(format, n):
  100. number = hex(int(str(n), 10))[2:].upper()
  101. if len(number) == 1:
  102. number = '0' + number
  103. streamfileids = fileid_dict[format]
  104. fileid = streamfileids[0:8] + number + streamfileids[10:]
  105. return fileid
  106. # get ep
  107. def generate_ep(format, n):
  108. fileid = get_fileid(format, n)
  109. ep_t = yk_t(
  110. b'bf7e5f01',
  111. ('%s_%s_%s' % (sid, fileid, token)).encode('ascii')
  112. )
  113. ep = base64.b64encode(ep_t).decode('ascii')
  114. return ep
  115. # generate video_urls
  116. video_urls_dict = {}
  117. for stream in data['stream']:
  118. if stream.get('channel_type') == 'tail':
  119. continue
  120. format = stream.get('stream_type')
  121. video_urls = []
  122. for dt in stream['segs']:
  123. n = str(stream['segs'].index(dt))
  124. param = {
  125. 'K': dt['key'],
  126. 'hd': self.get_hd(format),
  127. 'myp': 0,
  128. 'ypp': 0,
  129. 'ctype': 12,
  130. 'ev': 1,
  131. 'token': token,
  132. 'oip': oip,
  133. 'ep': generate_ep(format, n)
  134. }
  135. video_url = \
  136. 'http://k.youku.com/player/getFlvPath/' + \
  137. 'sid/' + sid + \
  138. '_00' + \
  139. '/st/' + self.parse_ext_l(format) + \
  140. '/fileid/' + get_fileid(format, n) + '?' + \
  141. compat_urllib_parse_urlencode(param)
  142. video_urls.append(video_url)
  143. video_urls_dict[format] = video_urls
  144. return video_urls_dict
  145. @staticmethod
  146. def get_ysuid():
  147. return '%d%s' % (int(time.time()), ''.join([
  148. random.choice(string.ascii_letters) for i in range(3)]))
  149. def get_hd(self, fm):
  150. hd_id_dict = {
  151. '3gp': '0',
  152. '3gphd': '1',
  153. 'flv': '0',
  154. 'flvhd': '0',
  155. 'mp4': '1',
  156. 'mp4hd': '1',
  157. 'mp4hd2': '1',
  158. 'mp4hd3': '1',
  159. 'hd2': '2',
  160. 'hd3': '3',
  161. }
  162. return hd_id_dict[fm]
  163. def parse_ext_l(self, fm):
  164. ext_dict = {
  165. '3gp': 'flv',
  166. '3gphd': 'mp4',
  167. 'flv': 'flv',
  168. 'flvhd': 'flv',
  169. 'mp4': 'mp4',
  170. 'mp4hd': 'mp4',
  171. 'mp4hd2': 'flv',
  172. 'mp4hd3': 'flv',
  173. 'hd2': 'flv',
  174. 'hd3': 'flv',
  175. }
  176. return ext_dict[fm]
  177. def get_format_name(self, fm):
  178. _dict = {
  179. '3gp': 'h6',
  180. '3gphd': 'h5',
  181. 'flv': 'h4',
  182. 'flvhd': 'h4',
  183. 'mp4': 'h3',
  184. 'mp4hd': 'h3',
  185. 'mp4hd2': 'h4',
  186. 'mp4hd3': 'h4',
  187. 'hd2': 'h2',
  188. 'hd3': 'h1',
  189. }
  190. return _dict[fm]
  191. def _real_extract(self, url):
  192. video_id = self._match_id(url)
  193. self._set_cookie('youku.com', '__ysuid', self.get_ysuid())
  194. def retrieve_data(req_url, note):
  195. headers = {
  196. 'Referer': req_url,
  197. }
  198. self._set_cookie('youku.com', 'xreferrer', 'http://www.youku.com')
  199. req = sanitized_Request(req_url, headers=headers)
  200. cn_verification_proxy = self._downloader.params.get('cn_verification_proxy')
  201. if cn_verification_proxy:
  202. req.add_header('Ytdl-request-proxy', cn_verification_proxy)
  203. raw_data = self._download_json(req, video_id, note=note)
  204. return raw_data['data']
  205. video_password = self._downloader.params.get('videopassword')
  206. # request basic data
  207. basic_data_url = 'http://play.youku.com/play/get.json?vid=%s&ct=12' % video_id
  208. if video_password:
  209. basic_data_url += '&pwd=%s' % video_password
  210. data = retrieve_data(basic_data_url, 'Downloading JSON metadata')
  211. error = data.get('error')
  212. if error:
  213. error_note = error.get('note')
  214. if error_note is not None and '因版权原因无法观看此视频' in error_note:
  215. raise ExtractorError(
  216. 'Youku said: Sorry, this video is available in China only', expected=True)
  217. elif error_note and '该视频被设为私密' in error_note:
  218. raise ExtractorError(
  219. 'Youku said: Sorry, this video is private', expected=True)
  220. else:
  221. msg = 'Youku server reported error %i' % error.get('code')
  222. if error_note is not None:
  223. msg += ': ' + error_note
  224. raise ExtractorError(msg)
  225. # get video title
  226. title = data['video']['title']
  227. # generate video_urls_dict
  228. video_urls_dict = self.construct_video_urls(data)
  229. # construct info
  230. entries = [{
  231. 'id': '%s_part%d' % (video_id, i + 1),
  232. 'title': title,
  233. 'formats': [],
  234. # some formats are not available for all parts, we have to detect
  235. # which one has all
  236. } for i in range(max(len(v.get('segs')) for v in data['stream']))]
  237. for stream in data['stream']:
  238. if stream.get('channel_type') == 'tail':
  239. continue
  240. fm = stream.get('stream_type')
  241. video_urls = video_urls_dict[fm]
  242. for video_url, seg, entry in zip(video_urls, stream['segs'], entries):
  243. entry['formats'].append({
  244. 'url': video_url,
  245. 'format_id': self.get_format_name(fm),
  246. 'ext': self.parse_ext_l(fm),
  247. 'filesize': int(seg['size']),
  248. })
  249. return {
  250. '_type': 'multi_video',
  251. 'id': video_id,
  252. 'title': title,
  253. 'entries': entries,
  254. }