leeco.py 13 KB

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