youku.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import random
  2. import re
  3. import string
  4. import time
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. ExtractorError,
  8. get_element_by_class,
  9. js_to_json,
  10. str_or_none,
  11. strip_jsonp,
  12. )
  13. class YoukuIE(InfoExtractor):
  14. IE_NAME = 'youku'
  15. IE_DESC = '优酷'
  16. _VALID_URL = r'''(?x)
  17. (?:
  18. https?://(
  19. (?:v|player)\.youku\.com/(?:v_show/id_|player\.php/sid/)|
  20. video\.tudou\.com/v/)|
  21. youku:)
  22. (?P<id>[A-Za-z0-9]+)(?:\.html|/v\.swf|)
  23. '''
  24. _TESTS = [{
  25. # MD5 is unstable
  26. 'url': 'http://v.youku.com/v_show/id_XMTc1ODE5Njcy.html',
  27. 'info_dict': {
  28. 'id': 'XMTc1ODE5Njcy',
  29. 'title': '★Smile﹗♡ Git Fresh -Booty Music舞蹈.',
  30. 'ext': 'mp4',
  31. 'duration': 74.73,
  32. 'thumbnail': r're:^https?://.*',
  33. 'uploader': '。躲猫猫、',
  34. 'uploader_id': '36017967',
  35. 'uploader_url': 'http://i.youku.com/u/UMTQ0MDcxODY4',
  36. 'tags': list,
  37. }
  38. }, {
  39. 'url': 'http://player.youku.com/player.php/sid/XNDgyMDQ2NTQw/v.swf',
  40. 'only_matching': True,
  41. }, {
  42. 'url': 'http://v.youku.com/v_show/id_XODgxNjg1Mzk2_ev_1.html',
  43. 'info_dict': {
  44. 'id': 'XODgxNjg1Mzk2',
  45. 'ext': 'mp4',
  46. 'title': '武媚娘传奇 85',
  47. 'duration': 1999.61,
  48. 'thumbnail': r're:^https?://.*',
  49. 'uploader': '疯狂豆花',
  50. 'uploader_id': '62583473',
  51. 'uploader_url': 'http://i.youku.com/u/UMjUwMzMzODky',
  52. 'tags': list,
  53. },
  54. }, {
  55. 'url': 'http://v.youku.com/v_show/id_XMTI1OTczNDM5Mg==.html',
  56. 'info_dict': {
  57. 'id': 'XMTI1OTczNDM5Mg',
  58. 'ext': 'mp4',
  59. 'title': '花千骨 04',
  60. 'duration': 2363,
  61. 'thumbnail': r're:^https?://.*',
  62. 'uploader': '放剧场-花千骨',
  63. 'uploader_id': '772849359',
  64. 'uploader_url': 'http://i.youku.com/u/UMzA5MTM5NzQzNg==',
  65. 'tags': list,
  66. },
  67. }, {
  68. 'url': 'http://v.youku.com/v_show/id_XNjA1NzA2Njgw.html',
  69. 'note': 'Video protected with password',
  70. 'info_dict': {
  71. 'id': 'XNjA1NzA2Njgw',
  72. 'ext': 'mp4',
  73. 'title': '邢義田复旦讲座之想象中的胡人—从“左衽孔子”说起',
  74. 'duration': 7264.5,
  75. 'thumbnail': r're:^https?://.*',
  76. 'uploader': 'FoxJin1006',
  77. 'uploader_id': '322014285',
  78. 'uploader_url': 'http://i.youku.com/u/UMTI4ODA1NzE0MA==',
  79. 'tags': list,
  80. },
  81. 'params': {
  82. 'videopassword': '100600',
  83. },
  84. }, {
  85. # /play/get.json contains streams with "channel_type":"tail"
  86. 'url': 'http://v.youku.com/v_show/id_XOTUxMzg4NDMy.html',
  87. 'info_dict': {
  88. 'id': 'XOTUxMzg4NDMy',
  89. 'ext': 'mp4',
  90. 'title': '我的世界☆明月庄主☆车震猎杀☆杀人艺术Minecraft',
  91. 'duration': 702.08,
  92. 'thumbnail': r're:^https?://.*',
  93. 'uploader': '明月庄主moon',
  94. 'uploader_id': '38465621',
  95. 'uploader_url': 'http://i.youku.com/u/UMTUzODYyNDg0',
  96. 'tags': list,
  97. },
  98. }, {
  99. 'url': 'http://video.tudou.com/v/XMjIyNzAzMTQ4NA==.html?f=46177805',
  100. 'info_dict': {
  101. 'id': 'XMjIyNzAzMTQ4NA',
  102. 'ext': 'mp4',
  103. 'title': '卡马乔国足开大脚长传冲吊集锦',
  104. 'duration': 289,
  105. 'thumbnail': r're:^https?://.*',
  106. 'uploader': '阿卜杜拉之星',
  107. 'uploader_id': '2382249',
  108. 'uploader_url': 'http://i.youku.com/u/UOTUyODk5Ng==',
  109. 'tags': list,
  110. },
  111. }, {
  112. 'url': 'http://video.tudou.com/v/XMjE4ODI3OTg2MA==.html',
  113. 'only_matching': True,
  114. }]
  115. @staticmethod
  116. def get_ysuid():
  117. return '%d%s' % (int(time.time()), ''.join([
  118. random.choice(string.ascii_letters) for i in range(3)]))
  119. def get_format_name(self, fm):
  120. _dict = {
  121. '3gp': 'h6',
  122. '3gphd': 'h5',
  123. 'flv': 'h4',
  124. 'flvhd': 'h4',
  125. 'mp4': 'h3',
  126. 'mp4hd': 'h3',
  127. 'mp4hd2': 'h4',
  128. 'mp4hd3': 'h4',
  129. 'hd2': 'h2',
  130. 'hd3': 'h1',
  131. }
  132. return _dict.get(fm)
  133. def _real_extract(self, url):
  134. video_id = self._match_id(url)
  135. self._set_cookie('youku.com', '__ysuid', self.get_ysuid())
  136. self._set_cookie('youku.com', 'xreferrer', 'http://www.youku.com')
  137. _, urlh = self._download_webpage_handle(
  138. 'https://log.mmstat.com/eg.js', video_id, 'Retrieving cna info')
  139. # The etag header is '"foobar"'; let's remove the double quotes
  140. cna = urlh.headers['etag'][1:-1]
  141. # request basic data
  142. basic_data_params = {
  143. 'vid': video_id,
  144. 'ccode': '0532',
  145. 'client_ip': '192.168.1.1',
  146. 'utid': cna,
  147. 'client_ts': time.time() / 1000,
  148. }
  149. video_password = self.get_param('videopassword')
  150. if video_password:
  151. basic_data_params['password'] = video_password
  152. headers = {
  153. 'Referer': url,
  154. }
  155. headers.update(self.geo_verification_headers())
  156. data = self._download_json(
  157. 'https://ups.youku.com/ups/get.json', video_id,
  158. 'Downloading JSON metadata',
  159. query=basic_data_params, headers=headers)['data']
  160. error = data.get('error')
  161. if error:
  162. error_note = error.get('note')
  163. if error_note is not None and '因版权原因无法观看此视频' in error_note:
  164. raise ExtractorError(
  165. 'Youku said: Sorry, this video is available in China only', expected=True)
  166. elif error_note and '该视频被设为私密' in error_note:
  167. raise ExtractorError(
  168. 'Youku said: Sorry, this video is private', expected=True)
  169. else:
  170. msg = 'Youku server reported error %i' % error.get('code')
  171. if error_note is not None:
  172. msg += ': ' + error_note
  173. raise ExtractorError(msg)
  174. # get video title
  175. video_data = data['video']
  176. title = video_data['title']
  177. formats = [{
  178. 'url': stream['m3u8_url'],
  179. 'format_id': self.get_format_name(stream.get('stream_type')),
  180. 'ext': 'mp4',
  181. 'protocol': 'm3u8_native',
  182. 'filesize': int(stream.get('size')),
  183. 'width': stream.get('width'),
  184. 'height': stream.get('height'),
  185. } for stream in data['stream'] if stream.get('channel_type') != 'tail']
  186. return {
  187. 'id': video_id,
  188. 'title': title,
  189. 'formats': formats,
  190. 'duration': video_data.get('seconds'),
  191. 'thumbnail': video_data.get('logo'),
  192. 'uploader': video_data.get('username'),
  193. 'uploader_id': str_or_none(video_data.get('userid')),
  194. 'uploader_url': data.get('uploader', {}).get('homepage'),
  195. 'tags': video_data.get('tags'),
  196. }
  197. class YoukuShowIE(InfoExtractor):
  198. _VALID_URL = r'https?://list\.youku\.com/show/id_(?P<id>[0-9a-z]+)\.html'
  199. IE_NAME = 'youku:show'
  200. _TESTS = [{
  201. 'url': 'http://list.youku.com/show/id_zc7c670be07ff11e48b3f.html',
  202. 'info_dict': {
  203. 'id': 'zc7c670be07ff11e48b3f',
  204. 'title': '花千骨 DVD版',
  205. 'description': 'md5:a1ae6f5618571bbeb5c9821f9c81b558',
  206. },
  207. 'playlist_count': 50,
  208. }, {
  209. # Episode number not starting from 1
  210. 'url': 'http://list.youku.com/show/id_zefbfbd70efbfbd780bef.html',
  211. 'info_dict': {
  212. 'id': 'zefbfbd70efbfbd780bef',
  213. 'title': '超级飞侠3',
  214. 'description': 'md5:275715156abebe5ccc2a1992e9d56b98',
  215. },
  216. 'playlist_count': 24,
  217. }, {
  218. # Ongoing playlist. The initial page is the last one
  219. 'url': 'http://list.youku.com/show/id_za7c275ecd7b411e1a19e.html',
  220. 'only_matching': True,
  221. }, {
  222. # No data-id value.
  223. 'url': 'http://list.youku.com/show/id_zefbfbd61237fefbfbdef.html',
  224. 'only_matching': True,
  225. }, {
  226. # Wrong number of reload_id.
  227. 'url': 'http://list.youku.com/show/id_z20eb4acaf5c211e3b2ad.html',
  228. 'only_matching': True,
  229. }]
  230. def _extract_entries(self, playlist_data_url, show_id, note, query):
  231. query['callback'] = 'cb'
  232. playlist_data = self._download_json(
  233. playlist_data_url, show_id, query=query, note=note,
  234. transform_source=lambda s: js_to_json(strip_jsonp(s))).get('html')
  235. if playlist_data is None:
  236. return [None, None]
  237. drama_list = (get_element_by_class('p-drama-grid', playlist_data)
  238. or get_element_by_class('p-drama-half-row', playlist_data))
  239. if drama_list is None:
  240. raise ExtractorError('No episodes found')
  241. video_urls = re.findall(r'<a[^>]+href="([^"]+)"', drama_list)
  242. return playlist_data, [
  243. self.url_result(self._proto_relative_url(video_url, 'http:'), YoukuIE.ie_key())
  244. for video_url in video_urls]
  245. def _real_extract(self, url):
  246. show_id = self._match_id(url)
  247. webpage = self._download_webpage(url, show_id)
  248. entries = []
  249. page_config = self._parse_json(self._search_regex(
  250. r'var\s+PageConfig\s*=\s*({.+});', webpage, 'page config'),
  251. show_id, transform_source=js_to_json)
  252. first_page, initial_entries = self._extract_entries(
  253. 'http://list.youku.com/show/module', show_id,
  254. note='Downloading initial playlist data page',
  255. query={
  256. 'id': page_config['showid'],
  257. 'tab': 'showInfo',
  258. })
  259. first_page_reload_id = self._html_search_regex(
  260. r'<div[^>]+id="(reload_\d+)', first_page, 'first page reload id')
  261. # The first reload_id has the same items as first_page
  262. reload_ids = re.findall('<li[^>]+data-id="([^"]+)">', first_page)
  263. entries.extend(initial_entries)
  264. for idx, reload_id in enumerate(reload_ids):
  265. if reload_id == first_page_reload_id:
  266. continue
  267. _, new_entries = self._extract_entries(
  268. 'http://list.youku.com/show/episode', show_id,
  269. note='Downloading playlist data page %d' % (idx + 1),
  270. query={
  271. 'id': page_config['showid'],
  272. 'stage': reload_id,
  273. })
  274. if new_entries is not None:
  275. entries.extend(new_entries)
  276. desc = self._html_search_meta('description', webpage, fatal=False)
  277. playlist_title = desc.split(',')[0] if desc else None
  278. detail_li = get_element_by_class('p-intro', webpage)
  279. playlist_description = get_element_by_class(
  280. 'intro-more', detail_li) if detail_li else None
  281. return self.playlist_result(
  282. entries, show_id, playlist_title, playlist_description)