[iqiyi] Reorder imports
[youtube-dl] / youtube_dl / extractor / iqiyi.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import hashlib
5 import math
6 import random
7 import re
8 import time
9 import uuid
10 import zlib
11
12 from .common import InfoExtractor
13 from ..compat import compat_urllib_parse
14 from ..utils import ExtractorError
15
16
17 class IqiyiIE(InfoExtractor):
18     IE_NAME = 'iqiyi'
19
20     _VALID_URL = r'http://(?:www\.)iqiyi.com/.+?\.html'
21
22     _TEST = {
23         'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
24         'md5': '2cb594dc2781e6c941a110d8f358118b',
25         'info_dict': {
26             'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
27             'title': '美国德州空中惊现奇异云团 酷似UFO',
28             'ext': 'f4v',
29         }
30     }
31
32     def construct_video_urls(self, data, video_id, _uuid):
33         def do_xor(x, y):
34             a = y % 3
35             if a == 1:
36                 return x ^ 121
37             if a == 2:
38                 return x ^ 72
39             return x ^ 103
40
41         def get_encode_code(l):
42             a = 0
43             b = l.split('-')
44             c = len(b)
45             s = ''
46             for i in range(c - 1, -1, -1):
47                 a = do_xor(int(b[c - i - 1], 16), i)
48                 s += chr(a)
49             return s[::-1]
50
51         def get_path_key(x):
52             mg = ')(*&^flash@#$%a'
53             tm = self._download_json(
54                 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id)['t']
55             t = str(int(math.floor(int(tm) / (600.0))))
56             return hashlib.md5((t + mg + x).encode('utf8')).hexdigest()
57
58         video_urls_dict = {}
59         for i in data['vp']['tkl'][0]['vs']:
60             if 0 < int(i['bid']) <= 10:
61                 format_id = self.get_format(i['bid'])
62             else:
63                 continue
64
65             video_urls = []
66
67             video_urls_info = i['fs']
68             if not i['fs'][0]['l'].startswith('/'):
69                 t = get_encode_code(i['fs'][0]['l'])
70                 if t.endswith('mp4'):
71                     video_urls_info = i['flvs']
72
73             for ii in video_urls_info:
74                 vl = ii['l']
75                 if not vl.startswith('/'):
76                     vl = get_encode_code(vl)
77                 key = get_path_key(
78                     vl.split('/')[-1].split('.')[0])
79                 filesize = ii['b']
80                 base_url = data['vp']['du'].split('/')
81                 base_url.insert(-1, key)
82                 base_url = '/'.join(base_url)
83                 param = {
84                     'su': _uuid,
85                     'qyid': uuid.uuid4().hex,
86                     'client': '',
87                     'z': '',
88                     'bt': '',
89                     'ct': '',
90                     'tn': str(int(time.time()))
91                 }
92                 api_video_url = base_url + vl + '?' + \
93                     compat_urllib_parse.urlencode(param)
94                 js = self._download_json(api_video_url, video_id)
95                 video_url = js['l']
96                 video_urls.append(
97                     (video_url, filesize))
98
99             video_urls_dict[format_id] = video_urls
100         return video_urls_dict
101
102     def get_format(self, bid):
103         _dict = {
104             '1': 'h6',
105             '2': 'h5',
106             '3': 'h4',
107             '4': 'h3',
108             '5': 'h2',
109             '10': 'h1'
110         }
111         return _dict.get(str(bid), None)
112
113     def get_bid(self, format_id):
114         _dict = {
115             'h6': '1',
116             'h5': '2',
117             'h4': '3',
118             'h3': '4',
119             'h2': '5',
120             'h1': '10',
121             'best': 'best'
122         }
123         return _dict.get(format_id, None)
124
125     def get_raw_data(self, tvid, video_id, enc_key, _uuid):
126         tm = str(int(time.time()))
127         param = {
128             'key': 'fvip',
129             'src': hashlib.md5(b'youtube-dl').hexdigest(),
130             'tvId': tvid,
131             'vid': video_id,
132             'vinfo': 1,
133             'tm': tm,
134             'enc': hashlib.md5(
135                 (enc_key + tm + tvid).encode('utf8')).hexdigest(),
136             'qyid': _uuid,
137             'tn': random.random(),
138             'um': 0,
139             'authkey': hashlib.md5(
140                 (tm + tvid).encode('utf8')).hexdigest()
141         }
142
143         api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
144             compat_urllib_parse.urlencode(param)
145         raw_data = self._download_json(api_url, video_id)
146         return raw_data
147
148     def get_enc_key(self, swf_url, video_id):
149         req = self._request_webpage(
150             swf_url, video_id, note='download swf content')
151         cn = req.read()
152         cn = zlib.decompress(cn[8:])
153         pt = re.compile(b'MixerRemote\x08(?P<enc_key>.+?)\$&vv')
154         enc_key = self._search_regex(pt, cn, 'enc_key').decode('utf8')
155         return enc_key
156
157     def _real_extract(self, url):
158         webpage = self._download_webpage(
159             url, 'temp_id', note='download video page')
160         tvid = self._search_regex(
161             r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
162         video_id = self._search_regex(
163             r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
164         swf_url = self._search_regex(
165             r'(http://.+?MainPlayer.+?\.swf)', webpage, 'swf player URL')
166         _uuid = uuid.uuid4().hex
167
168         enc_key = self.get_enc_key(swf_url, video_id)
169
170         raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
171
172         if raw_data['code'] != 'A000000':
173             raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
174
175         if not raw_data['data']['vp']['tkl']:
176             raise ExtractorError('No support iQiqy VIP video')
177
178         data = raw_data['data']
179
180         title = data['vi']['vn']
181
182         # generate video_urls_dict
183         video_urls_dict = self.construct_video_urls(
184             data, video_id, _uuid)
185
186         # construct info
187         entries = []
188         for format_id in video_urls_dict:
189             video_urls = video_urls_dict[format_id]
190             for i, video_url_info in enumerate(video_urls):
191                 if len(entries) < i + 1:
192                     entries.append({'formats': []})
193                 entries[i]['formats'].append(
194                     {
195                         'url': video_url_info[0],
196                         'filesize': video_url_info[-1],
197                         'format_id': format_id,
198                         'preference': int(self.get_bid(format_id))
199                     }
200                 )
201
202         for i in range(len(entries)):
203             self._sort_formats(entries[i]['formats'])
204             entries[i].update(
205                 {
206                     'id': '_part%d' % (i + 1),
207                     'title': title,
208                 }
209             )
210
211         if len(entries) > 1:
212             info = {
213                 '_type': 'multi_video',
214                 'id': video_id,
215                 'title': title,
216                 'entries': entries,
217             }
218         else:
219             info = entries[0]
220             info['id'] = video_id
221             info['title'] = title
222
223         return info