[Letv] Add playlist support
[youtube-dl] / youtube_dl / extractor / letv.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import os.path
5 import re
6 import time
7 import datetime
8
9 from .common import InfoExtractor
10 from ..compat import (compat_urlparse, compat_urllib_parse)
11 from ..utils import (ExtractorError, parse_iso8601)
12
13
14 class LetvIE(InfoExtractor):
15     _VALID_URL = r'http://www\.letv\.com/ptv/vplay/(?P<id>\d+).html'
16
17     _TESTS = [{
18         'url': 'http://www.letv.com/ptv/vplay/22005890.html',
19         'md5': 'cab23bd68d5a8db9be31c9a222c1e8df',
20         'info_dict': {
21             'id': '22005890',
22             'ext': 'mp4',
23             'title': '第87届奥斯卡颁奖礼完美落幕 《鸟人》成最大赢家',
24             'timestamp': 1424747397,
25             'upload_date': '20150224',
26         }
27     }, {
28         'url': 'http://www.letv.com/ptv/vplay/1118082.html',
29         'info_dict': {
30             'id': '1118082',
31             'ext': 'mp4',
32         }
33     }]
34
35     @staticmethod
36     def urshift(val, n):
37         return val >> n if val >= 0 else (val + 0x100000000) >> n
38
39     # ror() and calcTimeKey() are reversed from a embedded swf file in KLetvPlayer.swf
40     def ror(self, param1, param2):
41         _loc3_ = 0
42         while _loc3_ < param2:
43             param1 = self.urshift(param1, 1) + ((param1 & 1) << 31)
44             _loc3_ += 1
45         return param1
46
47     def calcTimeKey(self, param1):
48         _loc2_ = 773625421
49         _loc3_ = self.ror(param1, _loc2_ % 13)
50         _loc3_ = _loc3_ ^ _loc2_
51         _loc3_ = self.ror(_loc3_, _loc2_ % 17)
52         return _loc3_
53
54     def _real_extract(self, url):
55         media_id = self._match_id(url)
56         page = self._download_webpage(url, media_id)
57         params = {
58             'id': media_id,
59             'platid': 1,
60             'splatid': 101,
61             'format': 1,
62             'tkey': self.calcTimeKey(int(time.time())),
63             'domain': 'www.letv.com'
64         }
65         play_json = self._download_json(
66             'http://api.letv.com/mms/out/video/playJson?' + compat_urllib_parse.urlencode(params),
67             media_id, 'playJson data')
68
69         # Check for errors
70         playstatus = play_json['playstatus']
71         if playstatus['status'] == 0:
72             flag = playstatus['flag']
73             if flag == 1:
74                 msg = 'Country %s auth error' % playstatus['country']
75             else:
76                 msg = 'Generic error. flag = %d' % flag
77             raise ExtractorError(msg, expected=True)
78
79         playurl = play_json['playurl']
80
81         formats = ['350', '1000', '1300', '720p', '1080p']
82         dispatch = playurl['dispatch']
83
84         urls = []
85         for format_id in formats:
86             if format_id in dispatch:
87                 media_url = playurl['domain'][0] + dispatch[format_id][0]
88
89                 # Mimic what flvxz.com do
90                 url_parts = list(compat_urlparse.urlparse(media_url))
91                 qs = dict(compat_urlparse.parse_qs(url_parts[4]))
92                 qs.update({
93                     'platid': '14',
94                     'splatid': '1401',
95                     'tss': 'no',
96                     'retry': 1
97                 })
98                 url_parts[4] = compat_urllib_parse.urlencode(qs)
99                 media_url = compat_urlparse.urlunparse(url_parts)
100
101                 url_info_dict = {
102                     'url': media_url,
103                     'ext': os.path.splitext(dispatch[format_id][1])[1][1:]
104                 }
105
106                 if format_id[-1:] == 'p':
107                     url_info_dict['height'] = format_id[:-1]
108
109                 urls.append(url_info_dict)
110
111         publish_time = parse_iso8601(self._html_search_regex(
112             r'发布时间&nbsp;([^<>]+) ', page, 'publish time', fatal=False),
113             delimiter=' ', timezone=datetime.timedelta(hours=8))
114
115         return {
116             'id': media_id,
117             'formats': urls,
118             'title': playurl['title'],
119             'thumbnail': playurl['pic'],
120             'timestamp': publish_time,
121         }
122
123
124 class LetvTvIE(InfoExtractor):
125     _VALID_URL = r'http://www.letv.com/tv/(?P<id>\d+).html'
126     _TESTS = [{
127         'url': 'http://www.letv.com/tv/46177.html',
128         'info_dict': {
129             'id': '46177',
130             'title': '美人天下',
131             'description': 'md5:395666ff41b44080396e59570dbac01c'
132         },
133         'playlist_count': 35
134     }]
135
136     def _real_extract(self, url):
137         playlist_id = self._match_id(url)
138         page = self._download_webpage(url, playlist_id)
139
140         media_urls = list(set(re.findall(
141             r'http://www.letv.com/ptv/vplay/\d+.html', page)))
142         entries = [self.url_result(media_url, ie='Letv')
143                    for media_url in media_urls]
144
145         title = self._html_search_meta('keywords', page, fatal=False).split(',')[0]
146         description = self._html_search_meta('description', page, fatal=False)
147
148         return self.playlist_result(entries, playlist_id, playlist_title=title,
149                                     playlist_description=description)
150
151
152 class LetvPlaylistIE(LetvTvIE):
153     _VALID_URL = r'http://tv.letv.com/[a-z]+/(?P<id>[a-z]+)/index.s?html'
154     _TESTS = [{
155         'url': 'http://tv.letv.com/izt/wuzetian/index.html',
156         'info_dict': {
157             'id': 'wuzetian',
158             'title': '武媚娘传奇',
159             'description': 'md5:e12499475ab3d50219e5bba00b3cb248'
160         },
161         'playlist_count': 96
162     }, {
163         'url': 'http://tv.letv.com/pzt/lswjzzjc/index.shtml',
164         'info_dict': {
165             'id': 'lswjzzjc',
166             # should be "劲舞青春", but I can't find a simple way to determine
167             # the playlist title
168             'title': '乐视午间自制剧场',
169             'description': 'md5:b1eef244f45589a7b5b1af9ff25a4489'
170         },
171         'playlist_mincount': 7
172     }]