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.

368 lines
13 KiB

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