youku.py 10 KB

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