]> jfr.im git - yt-dlp.git/blob - youtube_dlc/extractor/ivi.py
Cleanup some code and fix typos
[yt-dlp.git] / youtube_dlc / extractor / ivi.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import re
6 import sys
7
8 from .common import InfoExtractor
9 from ..utils import (
10 ExtractorError,
11 int_or_none,
12 qualities,
13 )
14
15
16 class IviIE(InfoExtractor):
17 IE_DESC = 'ivi.ru'
18 IE_NAME = 'ivi'
19 _VALID_URL = r'https?://(?:www\.)?ivi\.(?:ru|tv)/(?:watch/(?:[^/]+/)?|video/player\?.*?videoId=)(?P<id>\d+)'
20 _GEO_BYPASS = False
21 _GEO_COUNTRIES = ['RU']
22 _LIGHT_KEY = b'\xf1\x02\x32\xb7\xbc\x5c\x7a\xe8\xf7\x96\xc1\x33\x2b\x27\xa1\x8c'
23 _LIGHT_URL = 'https://api.ivi.ru/light/'
24
25 _TESTS = [
26 # Single movie
27 {
28 'url': 'http://www.ivi.ru/watch/53141',
29 'md5': '6ff5be2254e796ed346251d117196cf4',
30 'info_dict': {
31 'id': '53141',
32 'ext': 'mp4',
33 'title': 'Иван Васильевич меняет профессию',
34 'description': 'md5:b924063ea1677c8fe343d8a72ac2195f',
35 'duration': 5498,
36 'thumbnail': r're:^https?://.*\.jpg$',
37 },
38 'skip': 'Only works from Russia',
39 },
40 # Serial's series
41 {
42 'url': 'http://www.ivi.ru/watch/dvoe_iz_lartsa/9549',
43 'md5': '221f56b35e3ed815fde2df71032f4b3e',
44 'info_dict': {
45 'id': '9549',
46 'ext': 'mp4',
47 'title': 'Двое из ларца - Дело Гольдберга (1 часть)',
48 'series': 'Двое из ларца',
49 'season': 'Сезон 1',
50 'season_number': 1,
51 'episode': 'Дело Гольдберга (1 часть)',
52 'episode_number': 1,
53 'duration': 2655,
54 'thumbnail': r're:^https?://.*\.jpg$',
55 },
56 'skip': 'Only works from Russia',
57 },
58 {
59 # with MP4-HD720 format
60 'url': 'http://www.ivi.ru/watch/146500',
61 'md5': 'd63d35cdbfa1ea61a5eafec7cc523e1e',
62 'info_dict': {
63 'id': '146500',
64 'ext': 'mp4',
65 'title': 'Кукла',
66 'description': 'md5:ffca9372399976a2d260a407cc74cce6',
67 'duration': 5599,
68 'thumbnail': r're:^https?://.*\.jpg$',
69 },
70 'skip': 'Only works from Russia',
71 },
72 {
73 'url': 'https://www.ivi.tv/watch/33560/',
74 'only_matching': True,
75 },
76 ]
77
78 # Sorted by quality
79 _KNOWN_FORMATS = (
80 'MP4-low-mobile', 'MP4-mobile', 'FLV-lo', 'MP4-lo', 'FLV-hi', 'MP4-hi',
81 'MP4-SHQ', 'MP4-HD720', 'MP4-HD1080')
82
83 def _real_extract(self, url):
84 video_id = self._match_id(url)
85
86 data = json.dumps({
87 'method': 'da.content.get',
88 'params': [
89 video_id, {
90 'site': 's%d',
91 'referrer': 'http://www.ivi.ru/watch/%s' % video_id,
92 'contentid': video_id
93 }
94 ]
95 })
96
97 bundled = hasattr(sys, 'frozen')
98
99 for site in (353, 183):
100 content_data = (data % site).encode()
101 if site == 353:
102 if bundled:
103 continue
104 try:
105 from Cryptodome.Cipher import Blowfish
106 from Cryptodome.Hash import CMAC
107 pycryptodomex_found = True
108 except ImportError:
109 pycryptodomex_found = False
110 continue
111
112 timestamp = (self._download_json(
113 self._LIGHT_URL, video_id,
114 'Downloading timestamp JSON', data=json.dumps({
115 'method': 'da.timestamp.get',
116 'params': []
117 }).encode(), fatal=False) or {}).get('result')
118 if not timestamp:
119 continue
120
121 query = {
122 'ts': timestamp,
123 'sign': CMAC.new(self._LIGHT_KEY, timestamp.encode() + content_data, Blowfish).hexdigest(),
124 }
125 else:
126 query = {}
127
128 video_json = self._download_json(
129 self._LIGHT_URL, video_id,
130 'Downloading video JSON', data=content_data, query=query)
131
132 error = video_json.get('error')
133 if error:
134 origin = error.get('origin')
135 message = error.get('message') or error.get('user_message')
136 extractor_msg = 'Unable to download video %s'
137 if origin == 'NotAllowedForLocation':
138 self.raise_geo_restricted(message, self._GEO_COUNTRIES)
139 elif origin == 'NoRedisValidData':
140 extractor_msg = 'Video %s does not exist'
141 elif site == 353:
142 continue
143 elif bundled:
144 raise ExtractorError(
145 'This feature does not work from bundled exe. Run youtube-dlc from sources.',
146 expected=True)
147 elif not pycryptodomex_found:
148 raise ExtractorError(
149 'pycryptodomex not found. Please install it.',
150 expected=True)
151 elif message:
152 extractor_msg += ': ' + message
153 raise ExtractorError(extractor_msg % video_id, expected=True)
154 else:
155 break
156
157 result = video_json['result']
158 title = result['title']
159
160 quality = qualities(self._KNOWN_FORMATS)
161
162 formats = []
163 for f in result.get('files', []):
164 f_url = f.get('url')
165 content_format = f.get('content_format')
166 if not f_url:
167 continue
168 if (not self._downloader.params.get('allow_unplayable_formats')
169 and ('-MDRM-' in content_format or '-FPS-' in content_format)):
170 continue
171 formats.append({
172 'url': f_url,
173 'format_id': content_format,
174 'quality': quality(content_format),
175 'filesize': int_or_none(f.get('size_in_bytes')),
176 })
177 self._sort_formats(formats)
178
179 compilation = result.get('compilation')
180 episode = title if compilation else None
181
182 title = '%s - %s' % (compilation, title) if compilation is not None else title
183
184 thumbnails = [{
185 'url': preview['url'],
186 'id': preview.get('content_format'),
187 } for preview in result.get('preview', []) if preview.get('url')]
188
189 webpage = self._download_webpage(url, video_id)
190
191 season = self._search_regex(
192 r'<li[^>]+class="season active"[^>]*><a[^>]+>([^<]+)',
193 webpage, 'season', default=None)
194 season_number = int_or_none(self._search_regex(
195 r'<li[^>]+class="season active"[^>]*><a[^>]+data-season(?:-index)?="(\d+)"',
196 webpage, 'season number', default=None))
197
198 episode_number = int_or_none(self._search_regex(
199 r'[^>]+itemprop="episode"[^>]*>\s*<meta[^>]+itemprop="episodeNumber"[^>]+content="(\d+)',
200 webpage, 'episode number', default=None))
201
202 description = self._og_search_description(webpage, default=None) or self._html_search_meta(
203 'description', webpage, 'description', default=None)
204
205 return {
206 'id': video_id,
207 'title': title,
208 'series': compilation,
209 'season': season,
210 'season_number': season_number,
211 'episode': episode,
212 'episode_number': episode_number,
213 'thumbnails': thumbnails,
214 'description': description,
215 'duration': int_or_none(result.get('duration')),
216 'formats': formats,
217 }
218
219
220 class IviCompilationIE(InfoExtractor):
221 IE_DESC = 'ivi.ru compilations'
222 IE_NAME = 'ivi:compilation'
223 _VALID_URL = r'https?://(?:www\.)?ivi\.ru/watch/(?!\d+)(?P<compilationid>[a-z\d_-]+)(?:/season(?P<seasonid>\d+))?$'
224 _TESTS = [{
225 'url': 'http://www.ivi.ru/watch/dvoe_iz_lartsa',
226 'info_dict': {
227 'id': 'dvoe_iz_lartsa',
228 'title': 'Двое из ларца (2006 - 2008)',
229 },
230 'playlist_mincount': 24,
231 }, {
232 'url': 'http://www.ivi.ru/watch/dvoe_iz_lartsa/season1',
233 'info_dict': {
234 'id': 'dvoe_iz_lartsa/season1',
235 'title': 'Двое из ларца (2006 - 2008) 1 сезон',
236 },
237 'playlist_mincount': 12,
238 }]
239
240 def _extract_entries(self, html, compilation_id):
241 return [
242 self.url_result(
243 'http://www.ivi.ru/watch/%s/%s' % (compilation_id, serie), IviIE.ie_key())
244 for serie in re.findall(
245 r'<a\b[^>]+\bhref=["\']/watch/%s/(\d+)["\']' % compilation_id, html)]
246
247 def _real_extract(self, url):
248 mobj = re.match(self._VALID_URL, url)
249 compilation_id = mobj.group('compilationid')
250 season_id = mobj.group('seasonid')
251
252 if season_id is not None: # Season link
253 season_page = self._download_webpage(
254 url, compilation_id, 'Downloading season %s web page' % season_id)
255 playlist_id = '%s/season%s' % (compilation_id, season_id)
256 playlist_title = self._html_search_meta('title', season_page, 'title')
257 entries = self._extract_entries(season_page, compilation_id)
258 else: # Compilation link
259 compilation_page = self._download_webpage(url, compilation_id, 'Downloading compilation web page')
260 playlist_id = compilation_id
261 playlist_title = self._html_search_meta('title', compilation_page, 'title')
262 seasons = re.findall(
263 r'<a href="/watch/%s/season(\d+)' % compilation_id, compilation_page)
264 if not seasons: # No seasons in this compilation
265 entries = self._extract_entries(compilation_page, compilation_id)
266 else:
267 entries = []
268 for season_id in seasons:
269 season_page = self._download_webpage(
270 'http://www.ivi.ru/watch/%s/season%s' % (compilation_id, season_id),
271 compilation_id, 'Downloading season %s web page' % season_id)
272 entries.extend(self._extract_entries(season_page, compilation_id))
273
274 return self.playlist_result(entries, playlist_id, playlist_title)