youku.py 11 KB

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