Document how to group format selectors
[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 os.path
7 import random
8 import re
9 import time
10 import uuid
11 import zlib
12
13 from .common import InfoExtractor
14 from ..compat import compat_urllib_parse
15 from ..utils import (
16     ExtractorError,
17     url_basename,
18 )
19
20
21 class IqiyiIE(InfoExtractor):
22     IE_NAME = 'iqiyi'
23
24     _VALID_URL = r'http://(?:www\.)iqiyi.com/v_.+?\.html'
25
26     _TESTS = [{
27         'url': 'http://www.iqiyi.com/v_19rrojlavg.html',
28         'md5': '2cb594dc2781e6c941a110d8f358118b',
29         'info_dict': {
30             'id': '9c1fb1b99d192b21c559e5a1a2cb3c73',
31             'title': '美国德州空中惊现奇异云团 酷似UFO',
32             'ext': 'f4v',
33         }
34     }, {
35         'url': 'http://www.iqiyi.com/v_19rrhnnclk.html',
36         'info_dict': {
37             'id': 'e3f585b550a280af23c98b6cb2be19fb',
38             'title': '名侦探柯南第752集',
39         },
40         'playlist': [{
41             'md5': '7e49376fecaffa115d951634917fe105',
42             'info_dict': {
43                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part1',
44                 'ext': 'f4v',
45                 'title': '名侦探柯南第752集',
46             },
47         }, {
48             'md5': '41b75ba13bb7ac0e411131f92bc4f6ca',
49             'info_dict': {
50                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part2',
51                 'ext': 'f4v',
52                 'title': '名侦探柯南第752集',
53             },
54         }, {
55             'md5': '0cee1dd0a3d46a83e71e2badeae2aab0',
56             'info_dict': {
57                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part3',
58                 'ext': 'f4v',
59                 'title': '名侦探柯南第752集',
60             },
61         }, {
62             'md5': '4f8ad72373b0c491b582e7c196b0b1f9',
63             'info_dict': {
64                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part4',
65                 'ext': 'f4v',
66                 'title': '名侦探柯南第752集',
67             },
68         }, {
69             'md5': 'd89ad028bcfad282918e8098e811711d',
70             'info_dict': {
71                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part5',
72                 'ext': 'f4v',
73                 'title': '名侦探柯南第752集',
74             },
75         }, {
76             'md5': '9cb1e5c95da25dff0660c32ae50903b7',
77             'info_dict': {
78                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part6',
79                 'ext': 'f4v',
80                 'title': '名侦探柯南第752集',
81             },
82         }, {
83             'md5': '155116e0ff1867bbc9b98df294faabc9',
84             'info_dict': {
85                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part7',
86                 'ext': 'f4v',
87                 'title': '名侦探柯南第752集',
88             },
89         }, {
90             'md5': '53f5db77622ae14fa493ed2a278a082b',
91             'info_dict': {
92                 'id': 'e3f585b550a280af23c98b6cb2be19fb_part8',
93                 'ext': 'f4v',
94                 'title': '名侦探柯南第752集',
95             },
96         }],
97     }]
98
99     _FORMATS_MAP = [
100         ('1', 'h6'),
101         ('2', 'h5'),
102         ('3', 'h4'),
103         ('4', 'h3'),
104         ('5', 'h2'),
105         ('10', 'h1'),
106     ]
107
108     def construct_video_urls(self, data, video_id, _uuid):
109         def do_xor(x, y):
110             a = y % 3
111             if a == 1:
112                 return x ^ 121
113             if a == 2:
114                 return x ^ 72
115             return x ^ 103
116
117         def get_encode_code(l):
118             a = 0
119             b = l.split('-')
120             c = len(b)
121             s = ''
122             for i in range(c - 1, -1, -1):
123                 a = do_xor(int(b[c - i - 1], 16), i)
124                 s += chr(a)
125             return s[::-1]
126
127         def get_path_key(x, format_id, segment_index):
128             mg = ')(*&^flash@#$%a'
129             tm = self._download_json(
130                 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id,
131                 note='Download path key of segment %d for format %s' % (segment_index + 1, format_id)
132             )['t']
133             t = str(int(math.floor(int(tm) / (600.0))))
134             return hashlib.md5((t + mg + x).encode('utf8')).hexdigest()
135
136         video_urls_dict = {}
137         for format_item in data['vp']['tkl'][0]['vs']:
138             if 0 < int(format_item['bid']) <= 10:
139                 format_id = self.get_format(format_item['bid'])
140             else:
141                 continue
142
143             video_urls = []
144
145             video_urls_info = format_item['fs']
146             if not format_item['fs'][0]['l'].startswith('/'):
147                 t = get_encode_code(format_item['fs'][0]['l'])
148                 if t.endswith('mp4'):
149                     video_urls_info = format_item['flvs']
150
151             for segment_index, segment in enumerate(video_urls_info):
152                 vl = segment['l']
153                 if not vl.startswith('/'):
154                     vl = get_encode_code(vl)
155                 key = get_path_key(
156                     vl.split('/')[-1].split('.')[0], format_id, segment_index)
157                 filesize = segment['b']
158                 base_url = data['vp']['du'].split('/')
159                 base_url.insert(-1, key)
160                 base_url = '/'.join(base_url)
161                 param = {
162                     'su': _uuid,
163                     'qyid': uuid.uuid4().hex,
164                     'client': '',
165                     'z': '',
166                     'bt': '',
167                     'ct': '',
168                     'tn': str(int(time.time()))
169                 }
170                 api_video_url = base_url + vl + '?' + \
171                     compat_urllib_parse.urlencode(param)
172                 js = self._download_json(
173                     api_video_url, video_id,
174                     note='Download video info of segment %d for format %s' % (segment_index + 1, format_id))
175                 video_url = js['l']
176                 video_urls.append(
177                     (video_url, filesize))
178
179             video_urls_dict[format_id] = video_urls
180         return video_urls_dict
181
182     def get_format(self, bid):
183         matched_format_ids = [_format_id for _bid, _format_id in self._FORMATS_MAP if _bid == str(bid)]
184         return matched_format_ids[0] if len(matched_format_ids) else None
185
186     def get_bid(self, format_id):
187         matched_bids = [_bid for _bid, _format_id in self._FORMATS_MAP if _format_id == format_id]
188         return matched_bids[0] if len(matched_bids) else None
189
190     def get_raw_data(self, tvid, video_id, enc_key, _uuid):
191         tm = str(int(time.time()))
192         param = {
193             'key': 'fvip',
194             'src': hashlib.md5(b'youtube-dl').hexdigest(),
195             'tvId': tvid,
196             'vid': video_id,
197             'vinfo': 1,
198             'tm': tm,
199             'enc': hashlib.md5(
200                 (enc_key + tm + tvid).encode('utf8')).hexdigest(),
201             'qyid': _uuid,
202             'tn': random.random(),
203             'um': 0,
204             'authkey': hashlib.md5(
205                 (tm + tvid).encode('utf8')).hexdigest()
206         }
207
208         api_url = 'http://cache.video.qiyi.com/vms' + '?' + \
209             compat_urllib_parse.urlencode(param)
210         raw_data = self._download_json(api_url, video_id)
211         return raw_data
212
213     def get_enc_key(self, swf_url, video_id):
214         filename, _ = os.path.splitext(url_basename(swf_url))
215         enc_key_json = self._downloader.cache.load('iqiyi-enc-key', filename)
216         if enc_key_json is not None:
217             return enc_key_json[0]
218
219         req = self._request_webpage(
220             swf_url, video_id, note='download swf content')
221         cn = req.read()
222         cn = zlib.decompress(cn[8:])
223         pt = re.compile(b'MixerRemote\x08(?P<enc_key>.+?)\$&vv')
224         enc_key = self._search_regex(pt, cn, 'enc_key').decode('utf8')
225
226         self._downloader.cache.store('iqiyi-enc-key', filename, [enc_key])
227
228         return enc_key
229
230     def _real_extract(self, url):
231         webpage = self._download_webpage(
232             url, 'temp_id', note='download video page')
233         tvid = self._search_regex(
234             r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid')
235         video_id = self._search_regex(
236             r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id')
237         swf_url = self._search_regex(
238             r'(http://[^\'"]+MainPlayer[^.]+\.swf)', webpage, 'swf player URL')
239         _uuid = uuid.uuid4().hex
240
241         enc_key = self.get_enc_key(swf_url, video_id)
242
243         raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid)
244
245         if raw_data['code'] != 'A000000':
246             raise ExtractorError('Unable to load data. Error code: ' + raw_data['code'])
247
248         if not raw_data['data']['vp']['tkl']:
249             raise ExtractorError('No support iQiqy VIP video')
250
251         data = raw_data['data']
252
253         title = data['vi']['vn']
254
255         # generate video_urls_dict
256         video_urls_dict = self.construct_video_urls(
257             data, video_id, _uuid)
258
259         # construct info
260         entries = []
261         for format_id in video_urls_dict:
262             video_urls = video_urls_dict[format_id]
263             for i, video_url_info in enumerate(video_urls):
264                 if len(entries) < i + 1:
265                     entries.append({'formats': []})
266                 entries[i]['formats'].append(
267                     {
268                         'url': video_url_info[0],
269                         'filesize': video_url_info[-1],
270                         'format_id': format_id,
271                         'preference': int(self.get_bid(format_id))
272                     }
273                 )
274
275         for i in range(len(entries)):
276             self._sort_formats(entries[i]['formats'])
277             entries[i].update(
278                 {
279                     'id': '%s_part%d' % (video_id, i + 1),
280                     'title': title,
281                 }
282             )
283
284         if len(entries) > 1:
285             info = {
286                 '_type': 'multi_video',
287                 'id': video_id,
288                 'title': title,
289                 'entries': entries,
290             }
291         else:
292             info = entries[0]
293             info['id'] = video_id
294             info['title'] = title
295
296         return info