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.

406 lines
14 KiB

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 datetime
  5. import hashlib
  6. import re
  7. import time
  8. from .common import InfoExtractor
  9. from ..compat import (
  10. compat_ord,
  11. compat_str,
  12. compat_urllib_parse_urlencode,
  13. )
  14. from ..utils import (
  15. determine_ext,
  16. encode_data_uri,
  17. ExtractorError,
  18. int_or_none,
  19. orderedSet,
  20. parse_iso8601,
  21. str_or_none,
  22. url_basename,
  23. urshift,
  24. update_url_query,
  25. )
  26. class LeIE(InfoExtractor):
  27. IE_DESC = '乐视网'
  28. _VALID_URL = r'https?://(?:www\.le\.com/ptv/vplay|(?:sports\.le|(?:www\.)?lesports)\.com/(?:match|video))/(?P<id>\d+)\.html'
  29. _URL_TEMPLATE = 'http://www.le.com/ptv/vplay/%s.html'
  30. _TESTS = [{
  31. 'url': 'http://www.le.com/ptv/vplay/22005890.html',
  32. 'md5': 'edadcfe5406976f42f9f266057ee5e40',
  33. 'info_dict': {
  34. 'id': '22005890',
  35. 'ext': 'mp4',
  36. 'title': '第87届奥斯卡颁奖礼完美落幕 《鸟人》成最大赢家',
  37. 'description': 'md5:a9cb175fd753e2962176b7beca21a47c',
  38. },
  39. 'params': {
  40. 'hls_prefer_native': True,
  41. },
  42. }, {
  43. 'url': 'http://www.le.com/ptv/vplay/1415246.html',
  44. 'info_dict': {
  45. 'id': '1415246',
  46. 'ext': 'mp4',
  47. 'title': '美人天下01',
  48. 'description': 'md5:f88573d9d7225ada1359eaf0dbf8bcda',
  49. },
  50. 'params': {
  51. 'hls_prefer_native': True,
  52. },
  53. }, {
  54. 'note': 'This video is available only in Mainland China, thus a proxy is needed',
  55. 'url': 'http://www.le.com/ptv/vplay/1118082.html',
  56. 'md5': '2424c74948a62e5f31988438979c5ad1',
  57. 'info_dict': {
  58. 'id': '1118082',
  59. 'ext': 'mp4',
  60. 'title': '与龙共舞 完整版',
  61. 'description': 'md5:7506a5eeb1722bb9d4068f85024e3986',
  62. },
  63. 'params': {
  64. 'hls_prefer_native': True,
  65. },
  66. 'skip': 'Only available in China',
  67. }, {
  68. 'url': 'http://sports.le.com/video/25737697.html',
  69. 'only_matching': True,
  70. }, {
  71. 'url': 'http://www.lesports.com/match/1023203003.html',
  72. 'only_matching': True,
  73. }, {
  74. 'url': 'http://sports.le.com/match/1023203003.html',
  75. 'only_matching': True,
  76. }]
  77. # ror() and calc_time_key() are reversed from a embedded swf file in KLetvPlayer.swf
  78. def ror(self, param1, param2):
  79. _loc3_ = 0
  80. while _loc3_ < param2:
  81. param1 = urshift(param1, 1) + ((param1 & 1) << 31)
  82. _loc3_ += 1
  83. return param1
  84. def calc_time_key(self, param1):
  85. _loc2_ = 773625421
  86. _loc3_ = self.ror(param1, _loc2_ % 13)
  87. _loc3_ = _loc3_ ^ _loc2_
  88. _loc3_ = self.ror(_loc3_, _loc2_ % 17)
  89. return _loc3_
  90. # reversed from http://jstatic.letvcdn.com/sdk/player.js
  91. def get_mms_key(self, time):
  92. return self.ror(time, 8) ^ 185025305
  93. # see M3U8Encryption class in KLetvPlayer.swf
  94. @staticmethod
  95. def decrypt_m3u8(encrypted_data):
  96. if encrypted_data[:5].decode('utf-8').lower() != 'vc_01':
  97. return encrypted_data
  98. encrypted_data = encrypted_data[5:]
  99. _loc4_ = bytearray(2 * len(encrypted_data))
  100. for idx, val in enumerate(encrypted_data):
  101. b = compat_ord(val)
  102. _loc4_[2 * idx] = b // 16
  103. _loc4_[2 * idx + 1] = b % 16
  104. idx = len(_loc4_) - 11
  105. _loc4_ = _loc4_[idx:] + _loc4_[:idx]
  106. _loc7_ = bytearray(len(encrypted_data))
  107. for i in range(len(encrypted_data)):
  108. _loc7_[i] = _loc4_[2 * i] * 16 + _loc4_[2 * i + 1]
  109. return bytes(_loc7_)
  110. def _check_errors(self, play_json):
  111. # Check for errors
  112. playstatus = play_json['playstatus']
  113. if playstatus['status'] == 0:
  114. flag = playstatus['flag']
  115. if flag == 1:
  116. msg = 'Country %s auth error' % playstatus['country']
  117. else:
  118. msg = 'Generic error. flag = %d' % flag
  119. raise ExtractorError(msg, expected=True)
  120. def _real_extract(self, url):
  121. media_id = self._match_id(url)
  122. page = self._download_webpage(url, media_id)
  123. play_json_h5 = self._download_json(
  124. 'http://api.le.com/mms/out/video/playJsonH5',
  125. media_id, 'Downloading html5 playJson data', query={
  126. 'id': media_id,
  127. 'platid': 3,
  128. 'splatid': 304,
  129. 'format': 1,
  130. 'tkey': self.get_mms_key(int(time.time())),
  131. 'domain': 'www.le.com',
  132. 'tss': 'no',
  133. },
  134. headers=self.geo_verification_headers())
  135. self._check_errors(play_json_h5)
  136. play_json_flash = self._download_json(
  137. 'http://api.le.com/mms/out/video/playJson',
  138. media_id, 'Downloading flash playJson data', query={
  139. 'id': media_id,
  140. 'platid': 1,
  141. 'splatid': 101,
  142. 'format': 1,
  143. 'tkey': self.calc_time_key(int(time.time())),
  144. 'domain': 'www.le.com',
  145. },
  146. headers=self.geo_verification_headers())
  147. self._check_errors(play_json_flash)
  148. def get_h5_urls(media_url, format_id):
  149. location = self._download_json(
  150. media_url, media_id,
  151. 'Download JSON metadata for format %s' % format_id, query={
  152. 'format': 1,
  153. 'expect': 3,
  154. 'tss': 'no',
  155. })['location']
  156. return {
  157. 'http': update_url_query(location, {'tss': 'no'}),
  158. 'hls': update_url_query(location, {'tss': 'ios'}),
  159. }
  160. def get_flash_urls(media_url, format_id):
  161. media_url += '&' + compat_urllib_parse_urlencode({
  162. 'm3v': 1,
  163. 'format': 1,
  164. 'expect': 3,
  165. 'rateid': format_id,
  166. })
  167. nodes_data = self._download_json(
  168. media_url, media_id,
  169. 'Download JSON metadata for format %s' % format_id)
  170. req = self._request_webpage(
  171. nodes_data['nodelist'][0]['location'], media_id,
  172. note='Downloading m3u8 information for format %s' % format_id)
  173. m3u8_data = self.decrypt_m3u8(req.read())
  174. return {
  175. 'hls': encode_data_uri(m3u8_data, 'application/vnd.apple.mpegurl'),
  176. }
  177. extracted_formats = []
  178. formats = []
  179. for play_json, get_urls in ((play_json_h5, get_h5_urls), (play_json_flash, get_flash_urls)):
  180. playurl = play_json['playurl']
  181. play_domain = playurl['domain'][0]
  182. for format_id, format_data in playurl.get('dispatch', []).items():
  183. if format_id in extracted_formats:
  184. continue
  185. extracted_formats.append(format_id)
  186. media_url = play_domain + format_data[0]
  187. for protocol, format_url in get_urls(media_url, format_id).items():
  188. f = {
  189. 'url': format_url,
  190. 'ext': determine_ext(format_data[1]),
  191. 'format_id': '%s-%s' % (protocol, format_id),
  192. 'protocol': 'm3u8_native' if protocol == 'hls' else 'http',
  193. 'quality': int_or_none(format_id),
  194. }
  195. if format_id[-1:] == 'p':
  196. f['height'] = int_or_none(format_id[:-1])
  197. formats.append(f)
  198. self._sort_formats(formats, ('height', 'quality', 'format_id'))
  199. publish_time = parse_iso8601(self._html_search_regex(
  200. r'发布时间&nbsp;([^<>]+) ', page, 'publish time', default=None),
  201. delimiter=' ', timezone=datetime.timedelta(hours=8))
  202. description = self._html_search_meta('description', page, fatal=False)
  203. return {
  204. 'id': media_id,
  205. 'formats': formats,
  206. 'title': playurl['title'],
  207. 'thumbnail': playurl['pic'],
  208. 'description': description,
  209. 'timestamp': publish_time,
  210. }
  211. class LePlaylistIE(InfoExtractor):
  212. _VALID_URL = r'https?://[a-z]+\.le\.com/(?!video)[a-z]+/(?P<id>[a-z0-9_]+)'
  213. _TESTS = [{
  214. 'url': 'http://www.le.com/tv/46177.html',
  215. 'info_dict': {
  216. 'id': '46177',
  217. 'title': '美人天下',
  218. 'description': 'md5:395666ff41b44080396e59570dbac01c'
  219. },
  220. 'playlist_count': 35
  221. }, {
  222. 'url': 'http://tv.le.com/izt/wuzetian/index.html',
  223. 'info_dict': {
  224. 'id': 'wuzetian',
  225. 'title': '武媚娘传奇',
  226. 'description': 'md5:e12499475ab3d50219e5bba00b3cb248'
  227. },
  228. # This playlist contains some extra videos other than the drama itself
  229. 'playlist_mincount': 96
  230. }, {
  231. 'url': 'http://tv.le.com/pzt/lswjzzjc/index.shtml',
  232. # This series is moved to http://www.le.com/tv/10005297.html
  233. 'only_matching': True,
  234. }, {
  235. 'url': 'http://www.le.com/comic/92063.html',
  236. 'only_matching': True,
  237. }, {
  238. 'url': 'http://list.le.com/listn/c1009_sc532002_d2_p1_o1.html',
  239. 'only_matching': True,
  240. }]
  241. @classmethod
  242. def suitable(cls, url):
  243. return False if LeIE.suitable(url) else super(LePlaylistIE, cls).suitable(url)
  244. def _real_extract(self, url):
  245. playlist_id = self._match_id(url)
  246. page = self._download_webpage(url, playlist_id)
  247. # Currently old domain names are still used in playlists
  248. media_ids = orderedSet(re.findall(
  249. r'<a[^>]+href="http://www\.letv\.com/ptv/vplay/(\d+)\.html', page))
  250. entries = [self.url_result(LeIE._URL_TEMPLATE % media_id, ie='Le')
  251. for media_id in media_ids]
  252. title = self._html_search_meta('keywords', page,
  253. fatal=False).split('')[0]
  254. description = self._html_search_meta('description', page, fatal=False)
  255. return self.playlist_result(entries, playlist_id, playlist_title=title,
  256. playlist_description=description)
  257. class LetvCloudIE(InfoExtractor):
  258. # Most of *.letv.com is changed to *.le.com on 2016/01/02
  259. # but yuntv.letv.com is kept, so also keep the extractor name
  260. IE_DESC = '乐视云'
  261. _VALID_URL = r'https?://yuntv\.letv\.com/bcloud.html\?.+'
  262. _TESTS = [{
  263. 'url': 'http://yuntv.letv.com/bcloud.html?uu=p7jnfw5hw9&vu=467623dedf',
  264. 'md5': '26450599afd64c513bc77030ad15db44',
  265. 'info_dict': {
  266. 'id': 'p7jnfw5hw9_467623dedf',
  267. 'ext': 'mp4',
  268. 'title': 'Video p7jnfw5hw9_467623dedf',
  269. },
  270. }, {
  271. 'url': 'http://yuntv.letv.com/bcloud.html?uu=p7jnfw5hw9&vu=ec93197892&pu=2c7cd40209&auto_play=1&gpcflag=1&width=640&height=360',
  272. 'md5': 'e03d9cc8d9c13191e1caf277e42dbd31',
  273. 'info_dict': {
  274. 'id': 'p7jnfw5hw9_ec93197892',
  275. 'ext': 'mp4',
  276. 'title': 'Video p7jnfw5hw9_ec93197892',
  277. },
  278. }, {
  279. 'url': 'http://yuntv.letv.com/bcloud.html?uu=p7jnfw5hw9&vu=187060b6fd',
  280. 'md5': 'cb988699a776b22d4a41b9d43acfb3ac',
  281. 'info_dict': {
  282. 'id': 'p7jnfw5hw9_187060b6fd',
  283. 'ext': 'mp4',
  284. 'title': 'Video p7jnfw5hw9_187060b6fd',
  285. },
  286. }]
  287. @staticmethod
  288. def sign_data(obj):
  289. if obj['cf'] == 'flash':
  290. salt = '2f9d6924b33a165a6d8b5d3d42f4f987'
  291. items = ['cf', 'format', 'ran', 'uu', 'ver', 'vu']
  292. elif obj['cf'] == 'html5':
  293. salt = 'fbeh5player12c43eccf2bec3300344'
  294. items = ['cf', 'ran', 'uu', 'bver', 'vu']
  295. input_data = ''.join([item + obj[item] for item in items]) + salt
  296. obj['sign'] = hashlib.md5(input_data.encode('utf-8')).hexdigest()
  297. def _get_formats(self, cf, uu, vu, media_id):
  298. def get_play_json(cf, timestamp):
  299. data = {
  300. 'cf': cf,
  301. 'ver': '2.2',
  302. 'bver': 'firefox44.0',
  303. 'format': 'json',
  304. 'uu': uu,
  305. 'vu': vu,
  306. 'ran': compat_str(timestamp),
  307. }
  308. self.sign_data(data)
  309. return self._download_json(
  310. 'http://api.letvcloud.com/gpc.php?' + compat_urllib_parse_urlencode(data),
  311. media_id, 'Downloading playJson data for type %s' % cf)
  312. play_json = get_play_json(cf, time.time())
  313. # The server time may be different from local time
  314. if play_json.get('code') == 10071:
  315. play_json = get_play_json(cf, play_json['timestamp'])
  316. if not play_json.get('data'):
  317. if play_json.get('message'):
  318. raise ExtractorError('Letv cloud said: %s' % play_json['message'], expected=True)
  319. elif play_json.get('code'):
  320. raise ExtractorError('Letv cloud returned error %d' % play_json['code'], expected=True)
  321. else:
  322. raise ExtractorError('Letv cloud returned an unknwon error')
  323. def b64decode(s):
  324. return base64.b64decode(s.encode('utf-8')).decode('utf-8')
  325. formats = []
  326. for media in play_json['data']['video_info']['media'].values():
  327. play_url = media['play_url']
  328. url = b64decode(play_url['main_url'])
  329. decoded_url = b64decode(url_basename(url))
  330. formats.append({
  331. 'url': url,
  332. 'ext': determine_ext(decoded_url),
  333. 'format_id': str_or_none(play_url.get('vtype')),
  334. 'format_note': str_or_none(play_url.get('definition')),
  335. 'width': int_or_none(play_url.get('vwidth')),
  336. 'height': int_or_none(play_url.get('vheight')),
  337. })
  338. return formats
  339. def _real_extract(self, url):
  340. uu_mobj = re.search(r'uu=([\w]+)', url)
  341. vu_mobj = re.search(r'vu=([\w]+)', url)
  342. if not uu_mobj or not vu_mobj:
  343. raise ExtractorError('Invalid URL: %s' % url, expected=True)
  344. uu = uu_mobj.group(1)
  345. vu = vu_mobj.group(1)
  346. media_id = uu + '_' + vu
  347. formats = self._get_formats('flash', uu, vu, media_id) + self._get_formats('html5', uu, vu, media_id)
  348. self._sort_formats(formats)
  349. return {
  350. 'id': media_id,
  351. 'title': 'Video %s' % media_id,
  352. 'formats': formats,
  353. }