letv.py 12 KB

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