youku.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import random
  5. import re
  6. import string
  7. import time
  8. from .common import InfoExtractor
  9. from ..utils import (
  10. ExtractorError,
  11. get_element_by_class,
  12. js_to_json,
  13. strip_jsonp,
  14. urljoin,
  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',
  30. 'title': '★Smile﹗♡ Git Fresh -Booty Music舞蹈.',
  31. 'ext': 'mp4',
  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. 'ext': 'mp4',
  41. 'title': '武媚娘传奇 85',
  42. },
  43. }, {
  44. 'url': 'http://v.youku.com/v_show/id_XMTI1OTczNDM5Mg==.html',
  45. 'info_dict': {
  46. 'id': 'XMTI1OTczNDM5Mg',
  47. 'ext': 'mp4',
  48. 'title': '花千骨 04',
  49. },
  50. }, {
  51. 'url': 'http://v.youku.com/v_show/id_XNjA1NzA2Njgw.html',
  52. 'note': 'Video protected with password',
  53. 'info_dict': {
  54. 'id': 'XNjA1NzA2Njgw',
  55. 'ext': 'mp4',
  56. 'title': '邢義田复旦讲座之想象中的胡人—从“左衽孔子”说起',
  57. },
  58. 'params': {
  59. 'videopassword': '100600',
  60. },
  61. }, {
  62. # /play/get.json contains streams with "channel_type":"tail"
  63. 'url': 'http://v.youku.com/v_show/id_XOTUxMzg4NDMy.html',
  64. 'info_dict': {
  65. 'id': 'XOTUxMzg4NDMy',
  66. 'ext': 'mp4',
  67. 'title': '我的世界☆明月庄主☆车震猎杀☆杀人艺术Minecraft',
  68. },
  69. }]
  70. @staticmethod
  71. def get_ysuid():
  72. return '%d%s' % (int(time.time()), ''.join([
  73. random.choice(string.ascii_letters) for i in range(3)]))
  74. def get_format_name(self, fm):
  75. _dict = {
  76. '3gp': 'h6',
  77. '3gphd': 'h5',
  78. 'flv': 'h4',
  79. 'flvhd': 'h4',
  80. 'mp4': 'h3',
  81. 'mp4hd': 'h3',
  82. 'mp4hd2': 'h4',
  83. 'mp4hd3': 'h4',
  84. 'hd2': 'h2',
  85. 'hd3': 'h1',
  86. }
  87. return _dict.get(fm)
  88. def _real_extract(self, url):
  89. video_id = self._match_id(url)
  90. self._set_cookie('youku.com', '__ysuid', self.get_ysuid())
  91. self._set_cookie('youku.com', 'xreferrer', 'http://www.youku.com')
  92. _, urlh = self._download_webpage_handle(
  93. 'https://log.mmstat.com/eg.js', video_id, 'Retrieving cna info')
  94. # The etag header is '"foobar"'; let's remove the double quotes
  95. cna = urlh.headers['etag'][1:-1]
  96. # request basic data
  97. basic_data_params = {
  98. 'vid': video_id,
  99. 'ccode': '0401',
  100. 'client_ip': '192.168.1.1',
  101. 'utid': cna,
  102. 'client_ts': time.time() / 1000,
  103. }
  104. video_password = self._downloader.params.get('videopassword')
  105. if video_password:
  106. basic_data_params['password'] = video_password
  107. headers = {
  108. 'Referer': url,
  109. }
  110. headers.update(self.geo_verification_headers())
  111. data = self._download_json(
  112. 'https://ups.youku.com/ups/get.json', video_id,
  113. 'Downloading JSON metadata',
  114. query=basic_data_params, headers=headers)['data']
  115. error = data.get('error')
  116. if error:
  117. error_note = error.get('note')
  118. if error_note is not None and '因版权原因无法观看此视频' in error_note:
  119. raise ExtractorError(
  120. 'Youku said: Sorry, this video is available in China only', expected=True)
  121. elif error_note and '该视频被设为私密' in error_note:
  122. raise ExtractorError(
  123. 'Youku said: Sorry, this video is private', expected=True)
  124. else:
  125. msg = 'Youku server reported error %i' % error.get('code')
  126. if error_note is not None:
  127. msg += ': ' + error_note
  128. raise ExtractorError(msg)
  129. # get video title
  130. title = data['video']['title']
  131. formats = [{
  132. 'url': stream['m3u8_url'],
  133. 'format_id': self.get_format_name(stream.get('stream_type')),
  134. 'ext': 'mp4',
  135. 'protocol': 'm3u8_native',
  136. 'filesize': int(stream.get('size')),
  137. 'width': stream.get('width'),
  138. 'height': stream.get('height'),
  139. } for stream in data['stream'] if stream.get('channel_type') != 'tail']
  140. self._sort_formats(formats)
  141. return {
  142. 'id': video_id,
  143. 'title': title,
  144. 'formats': formats,
  145. }
  146. class YoukuShowIE(InfoExtractor):
  147. _VALID_URL = r'https?://list\.youku\.com/show/id_(?P<id>[0-9a-z]+)\.html'
  148. IE_NAME = 'youku:show'
  149. _TEST = {
  150. 'url': 'http://list.youku.com/show/id_zc7c670be07ff11e48b3f.html',
  151. 'info_dict': {
  152. 'id': 'zc7c670be07ff11e48b3f',
  153. 'title': '花千骨 未删减版',
  154. 'description': 'md5:a1ae6f5618571bbeb5c9821f9c81b558',
  155. },
  156. 'playlist_count': 50,
  157. }
  158. _PAGE_SIZE = 40
  159. def _real_extract(self, url):
  160. show_id = self._match_id(url)
  161. webpage = self._download_webpage(url, show_id)
  162. entries = []
  163. page_config = self._parse_json(self._search_regex(
  164. r'var\s+PageConfig\s*=\s*({.+});', webpage, 'page config'),
  165. show_id, transform_source=js_to_json)
  166. for idx in itertools.count(0):
  167. if idx == 0:
  168. playlist_data_url = 'http://list.youku.com/show/module'
  169. query = {'id': page_config['showid'], 'tab': 'point'}
  170. else:
  171. playlist_data_url = 'http://list.youku.com/show/point'
  172. query = {
  173. 'id': page_config['showid'],
  174. 'stage': 'reload_%d' % (self._PAGE_SIZE * idx + 1),
  175. }
  176. query['callback'] = 'cb'
  177. playlist_data = self._download_json(
  178. playlist_data_url, show_id, query=query,
  179. note='Downloading playlist data page %d' % (idx + 1),
  180. transform_source=lambda s: js_to_json(strip_jsonp(s)))['html']
  181. video_urls = re.findall(
  182. r'<div[^>]+class="p-thumb"[^<]+<a[^>]+href="([^"]+)"',
  183. playlist_data)
  184. new_entries = [
  185. self.url_result(urljoin(url, video_url), YoukuIE.ie_key())
  186. for video_url in video_urls]
  187. entries.extend(new_entries)
  188. if len(new_entries) < self._PAGE_SIZE:
  189. break
  190. desc = self._html_search_meta('description', webpage, fatal=False)
  191. playlist_title = desc.split(',')[0] if desc else None
  192. detail_li = get_element_by_class('p-intro', webpage)
  193. playlist_description = get_element_by_class(
  194. 'intro-more', detail_li) if detail_li else None
  195. return self.playlist_result(
  196. entries, show_id, playlist_title, playlist_description)