leeco.py 13 KB

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