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.

334 lines
11 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 itertools
  5. import random
  6. import re
  7. import string
  8. import time
  9. from .common import InfoExtractor
  10. from ..compat import (
  11. compat_urllib_parse_urlencode,
  12. compat_ord,
  13. )
  14. from ..utils import (
  15. ExtractorError,
  16. get_element_by_attribute,
  17. )
  18. class YoukuIE(InfoExtractor):
  19. IE_NAME = 'youku'
  20. IE_DESC = '优酷'
  21. _VALID_URL = r'''(?x)
  22. (?:
  23. http://(?:v|player)\.youku\.com/(?:v_show/id_|player\.php/sid/)|
  24. youku:)
  25. (?P<id>[A-Za-z0-9]+)(?:\.html|/v\.swf|)
  26. '''
  27. _TESTS = [{
  28. # MD5 is unstable
  29. 'url': 'http://v.youku.com/v_show/id_XMTc1ODE5Njcy.html',
  30. 'info_dict': {
  31. 'id': 'XMTc1ODE5Njcy_part1',
  32. 'title': '★Smile﹗♡ Git Fresh -Booty Music舞蹈.',
  33. 'ext': 'flv'
  34. }
  35. }, {
  36. 'url': 'http://player.youku.com/player.php/sid/XNDgyMDQ2NTQw/v.swf',
  37. 'only_matching': True,
  38. }, {
  39. 'url': 'http://v.youku.com/v_show/id_XODgxNjg1Mzk2_ev_1.html',
  40. 'info_dict': {
  41. 'id': 'XODgxNjg1Mzk2',
  42. 'title': '武媚娘传奇 85',
  43. },
  44. 'playlist_count': 11,
  45. 'skip': 'Available in China only',
  46. }, {
  47. 'url': 'http://v.youku.com/v_show/id_XMTI1OTczNDM5Mg==.html',
  48. 'info_dict': {
  49. 'id': 'XMTI1OTczNDM5Mg',
  50. 'title': '花千骨 04',
  51. },
  52. 'playlist_count': 13,
  53. }, {
  54. 'url': 'http://v.youku.com/v_show/id_XNjA1NzA2Njgw.html',
  55. 'note': 'Video protected with password',
  56. 'info_dict': {
  57. 'id': 'XNjA1NzA2Njgw',
  58. 'title': '邢義田复旦讲座之想象中的胡人—从“左衽孔子”说起',
  59. },
  60. 'playlist_count': 19,
  61. 'params': {
  62. 'videopassword': '100600',
  63. },
  64. }, {
  65. # /play/get.json contains streams with "channel_type":"tail"
  66. 'url': 'http://v.youku.com/v_show/id_XOTUxMzg4NDMy.html',
  67. 'info_dict': {
  68. 'id': 'XOTUxMzg4NDMy',
  69. 'title': '我的世界☆明月庄主☆车震猎杀☆杀人艺术Minecraft',
  70. },
  71. 'playlist_count': 6,
  72. }]
  73. def construct_video_urls(self, data):
  74. # get sid, token
  75. def yk_t(s1, s2):
  76. ls = list(range(256))
  77. t = 0
  78. for i in range(256):
  79. t = (t + ls[i] + compat_ord(s1[i % len(s1)])) % 256
  80. ls[i], ls[t] = ls[t], ls[i]
  81. s = bytearray()
  82. x, y = 0, 0
  83. for i in range(len(s2)):
  84. y = (y + 1) % 256
  85. x = (x + ls[y]) % 256
  86. ls[x], ls[y] = ls[y], ls[x]
  87. s.append(compat_ord(s2[i]) ^ ls[(ls[x] + ls[y]) % 256])
  88. return bytes(s)
  89. sid, token = yk_t(
  90. b'becaf9be', base64.b64decode(data['security']['encrypt_string'].encode('ascii'))
  91. ).decode('ascii').split('_')
  92. # get oip
  93. oip = data['security']['ip']
  94. fileid_dict = {}
  95. for stream in data['stream']:
  96. if stream.get('channel_type') == 'tail':
  97. continue
  98. format = stream.get('stream_type')
  99. fileid = stream['stream_fileid']
  100. fileid_dict[format] = fileid
  101. def get_fileid(format, n):
  102. number = hex(int(str(n), 10))[2:].upper()
  103. if len(number) == 1:
  104. number = '0' + number
  105. streamfileids = fileid_dict[format]
  106. fileid = streamfileids[0:8] + number + streamfileids[10:]
  107. return fileid
  108. # get ep
  109. def generate_ep(format, n):
  110. fileid = get_fileid(format, n)
  111. ep_t = yk_t(
  112. b'bf7e5f01',
  113. ('%s_%s_%s' % (sid, fileid, token)).encode('ascii')
  114. )
  115. ep = base64.b64encode(ep_t).decode('ascii')
  116. return ep
  117. # generate video_urls
  118. video_urls_dict = {}
  119. for stream in data['stream']:
  120. if stream.get('channel_type') == 'tail':
  121. continue
  122. format = stream.get('stream_type')
  123. video_urls = []
  124. for dt in stream['segs']:
  125. n = str(stream['segs'].index(dt))
  126. param = {
  127. 'K': dt['key'],
  128. 'hd': self.get_hd(format),
  129. 'myp': 0,
  130. 'ypp': 0,
  131. 'ctype': 12,
  132. 'ev': 1,
  133. 'token': token,
  134. 'oip': oip,
  135. 'ep': generate_ep(format, n)
  136. }
  137. video_url = \
  138. 'http://k.youku.com/player/getFlvPath/' + \
  139. 'sid/' + sid + \
  140. '_00' + \
  141. '/st/' + self.parse_ext_l(format) + \
  142. '/fileid/' + get_fileid(format, n) + '?' + \
  143. compat_urllib_parse_urlencode(param)
  144. video_urls.append(video_url)
  145. video_urls_dict[format] = video_urls
  146. return video_urls_dict
  147. @staticmethod
  148. def get_ysuid():
  149. return '%d%s' % (int(time.time()), ''.join([
  150. random.choice(string.ascii_letters) for i in range(3)]))
  151. def get_hd(self, fm):
  152. hd_id_dict = {
  153. '3gp': '0',
  154. '3gphd': '1',
  155. 'flv': '0',
  156. 'flvhd': '0',
  157. 'mp4': '1',
  158. 'mp4hd': '1',
  159. 'mp4hd2': '1',
  160. 'mp4hd3': '1',
  161. 'hd2': '2',
  162. 'hd3': '3',
  163. }
  164. return hd_id_dict[fm]
  165. def parse_ext_l(self, fm):
  166. ext_dict = {
  167. '3gp': 'flv',
  168. '3gphd': 'mp4',
  169. 'flv': 'flv',
  170. 'flvhd': 'flv',
  171. 'mp4': 'mp4',
  172. 'mp4hd': 'mp4',
  173. 'mp4hd2': 'flv',
  174. 'mp4hd3': 'flv',
  175. 'hd2': 'flv',
  176. 'hd3': 'flv',
  177. }
  178. return ext_dict[fm]
  179. def get_format_name(self, fm):
  180. _dict = {
  181. '3gp': 'h6',
  182. '3gphd': 'h5',
  183. 'flv': 'h4',
  184. 'flvhd': 'h4',
  185. 'mp4': 'h3',
  186. 'mp4hd': 'h3',
  187. 'mp4hd2': 'h4',
  188. 'mp4hd3': 'h4',
  189. 'hd2': 'h2',
  190. 'hd3': 'h1',
  191. }
  192. return _dict[fm]
  193. def _real_extract(self, url):
  194. video_id = self._match_id(url)
  195. self._set_cookie('youku.com', '__ysuid', self.get_ysuid())
  196. def retrieve_data(req_url, note):
  197. headers = {
  198. 'Referer': req_url,
  199. }
  200. headers.update(self.geo_verification_headers())
  201. self._set_cookie('youku.com', 'xreferrer', 'http://www.youku.com')
  202. raw_data = self._download_json(req_url, video_id, note=note, headers=headers)
  203. return raw_data['data']
  204. video_password = self._downloader.params.get('videopassword')
  205. # request basic data
  206. basic_data_url = 'http://play.youku.com/play/get.json?vid=%s&ct=12' % video_id
  207. if video_password:
  208. basic_data_url += '&pwd=%s' % video_password
  209. data = retrieve_data(basic_data_url, 'Downloading JSON metadata')
  210. error = data.get('error')
  211. if error:
  212. error_note = error.get('note')
  213. if error_note is not None and '因版权原因无法观看此视频' in error_note:
  214. raise ExtractorError(
  215. 'Youku said: Sorry, this video is available in China only', expected=True)
  216. elif error_note and '该视频被设为私密' in error_note:
  217. raise ExtractorError(
  218. 'Youku said: Sorry, this video is private', expected=True)
  219. else:
  220. msg = 'Youku server reported error %i' % error.get('code')
  221. if error_note is not None:
  222. msg += ': ' + error_note
  223. raise ExtractorError(msg)
  224. # get video title
  225. title = data['video']['title']
  226. # generate video_urls_dict
  227. video_urls_dict = self.construct_video_urls(data)
  228. # construct info
  229. entries = [{
  230. 'id': '%s_part%d' % (video_id, i + 1),
  231. 'title': title,
  232. 'formats': [],
  233. # some formats are not available for all parts, we have to detect
  234. # which one has all
  235. } for i in range(max(len(v.get('segs')) for v in data['stream']))]
  236. for stream in data['stream']:
  237. if stream.get('channel_type') == 'tail':
  238. continue
  239. fm = stream.get('stream_type')
  240. video_urls = video_urls_dict[fm]
  241. for video_url, seg, entry in zip(video_urls, stream['segs'], entries):
  242. entry['formats'].append({
  243. 'url': video_url,
  244. 'format_id': self.get_format_name(fm),
  245. 'ext': self.parse_ext_l(fm),
  246. 'filesize': int(seg['size']),
  247. 'width': stream.get('width'),
  248. 'height': stream.get('height'),
  249. })
  250. return {
  251. '_type': 'multi_video',
  252. 'id': video_id,
  253. 'title': title,
  254. 'entries': entries,
  255. }
  256. class YoukuShowIE(InfoExtractor):
  257. _VALID_URL = r'https?://(?:www\.)?youku\.com/show_page/id_(?P<id>[0-9a-z]+)\.html'
  258. IE_NAME = 'youku:show'
  259. _TEST = {
  260. 'url': 'http://www.youku.com/show_page/id_zc7c670be07ff11e48b3f.html',
  261. 'info_dict': {
  262. 'id': 'zc7c670be07ff11e48b3f',
  263. 'title': '花千骨 未删减版',
  264. 'description': 'md5:578d4f2145ae3f9128d9d4d863312910',
  265. },
  266. 'playlist_count': 50,
  267. }
  268. _PAGE_SIZE = 40
  269. def _find_videos_in_page(self, webpage):
  270. videos = re.findall(
  271. r'<li><a[^>]+href="(?P<url>https?://v\.youku\.com/[^"]+)"[^>]+title="(?P<title>[^"]+)"', webpage)
  272. return [
  273. self.url_result(video_url, YoukuIE.ie_key(), title)
  274. for video_url, title in videos]
  275. def _real_extract(self, url):
  276. show_id = self._match_id(url)
  277. webpage = self._download_webpage(url, show_id)
  278. entries = self._find_videos_in_page(webpage)
  279. playlist_title = self._html_search_regex(
  280. r'<span[^>]+class="name">([^<]+)</span>', webpage, 'playlist title', fatal=False)
  281. detail_div = get_element_by_attribute('class', 'detail', webpage) or ''
  282. playlist_description = self._html_search_regex(
  283. r'<span[^>]+style="display:none"[^>]*>([^<]+)</span>',
  284. detail_div, 'playlist description', fatal=False)
  285. for idx in itertools.count(1):
  286. episodes_page = self._download_webpage(
  287. 'http://www.youku.com/show_episode/id_%s.html' % show_id,
  288. show_id, query={'divid': 'reload_%d' % (idx * self._PAGE_SIZE + 1)},
  289. note='Downloading episodes page %d' % idx)
  290. new_entries = self._find_videos_in_page(episodes_page)
  291. entries.extend(new_entries)
  292. if len(new_entries) < self._PAGE_SIZE:
  293. break
  294. return self.playlist_result(entries, show_id, playlist_title, playlist_description)