leeco.py 14 KB

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