]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/ivi.py
Update the changelog.
[youtubedl] / youtube_dl / 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-dl 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 or '-MDRM-' in content_format or '-FPS-' in content_format:
167 continue
168 formats.append({
169 'url': f_url,
170 'format_id': content_format,
171 'quality': quality(content_format),
172 'filesize': int_or_none(f.get('size_in_bytes')),
173 })
174 self._sort_formats(formats)
175
176 compilation = result.get('compilation')
177 episode = title if compilation else None
178
179 title = '%s - %s' % (compilation, title) if compilation is not None else title
180
181 thumbnails = [{
182 'url': preview['url'],
183 'id': preview.get('content_format'),
184 } for preview in result.get('preview', []) if preview.get('url')]
185
186 webpage = self._download_webpage(url, video_id)
187
188 season = self._search_regex(
189 r'<li[^>]+class="season active"[^>]*><a[^>]+>([^<]+)',
190 webpage, 'season', default=None)
191 season_number = int_or_none(self._search_regex(
192 r'<li[^>]+class="season active"[^>]*><a[^>]+data-season(?:-index)?="(\d+)"',
193 webpage, 'season number', default=None))
194
195 episode_number = int_or_none(self._search_regex(
196 r'[^>]+itemprop="episode"[^>]*>\s*<meta[^>]+itemprop="episodeNumber"[^>]+content="(\d+)',
197 webpage, 'episode number', default=None))
198
199 description = self._og_search_description(webpage, default=None) or self._html_search_meta(
200 'description', webpage, 'description', default=None)
201
202 return {
203 'id': video_id,
204 'title': title,
205 'series': compilation,
206 'season': season,
207 'season_number': season_number,
208 'episode': episode,
209 'episode_number': episode_number,
210 'thumbnails': thumbnails,
211 'description': description,
212 'duration': int_or_none(result.get('duration')),
213 'formats': formats,
214 }
215
216
217 class IviCompilationIE(InfoExtractor):
218 IE_DESC = 'ivi.ru compilations'
219 IE_NAME = 'ivi:compilation'
220 _VALID_URL = r'https?://(?:www\.)?ivi\.ru/watch/(?!\d+)(?P<compilationid>[a-z\d_-]+)(?:/season(?P<seasonid>\d+))?$'
221 _TESTS = [{
222 'url': 'http://www.ivi.ru/watch/dvoe_iz_lartsa',
223 'info_dict': {
224 'id': 'dvoe_iz_lartsa',
225 'title': 'Двое из ларца (2006 - 2008)',
226 },
227 'playlist_mincount': 24,
228 }, {
229 'url': 'http://www.ivi.ru/watch/dvoe_iz_lartsa/season1',
230 'info_dict': {
231 'id': 'dvoe_iz_lartsa/season1',
232 'title': 'Двое из ларца (2006 - 2008) 1 сезон',
233 },
234 'playlist_mincount': 12,
235 }]
236
237 def _extract_entries(self, html, compilation_id):
238 return [
239 self.url_result(
240 'http://www.ivi.ru/watch/%s/%s' % (compilation_id, serie), IviIE.ie_key())
241 for serie in re.findall(
242 r'<a\b[^>]+\bhref=["\']/watch/%s/(\d+)["\']' % compilation_id, html)]
243
244 def _real_extract(self, url):
245 mobj = re.match(self._VALID_URL, url)
246 compilation_id = mobj.group('compilationid')
247 season_id = mobj.group('seasonid')
248
249 if season_id is not None: # Season link
250 season_page = self._download_webpage(
251 url, compilation_id, 'Downloading season %s web page' % season_id)
252 playlist_id = '%s/season%s' % (compilation_id, season_id)
253 playlist_title = self._html_search_meta('title', season_page, 'title')
254 entries = self._extract_entries(season_page, compilation_id)
255 else: # Compilation link
256 compilation_page = self._download_webpage(url, compilation_id, 'Downloading compilation web page')
257 playlist_id = compilation_id
258 playlist_title = self._html_search_meta('title', compilation_page, 'title')
259 seasons = re.findall(
260 r'<a href="/watch/%s/season(\d+)' % compilation_id, compilation_page)
261 if not seasons: # No seasons in this compilation
262 entries = self._extract_entries(compilation_page, compilation_id)
263 else:
264 entries = []
265 for season_id in seasons:
266 season_page = self._download_webpage(
267 'http://www.ivi.ru/watch/%s/season%s' % (compilation_id, season_id),
268 compilation_id, 'Downloading season %s web page' % season_id)
269 entries.extend(self._extract_entries(season_page, compilation_id))
270
271 return self.playlist_result(entries, playlist_id, playlist_title)