leeco.py 12 KB

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