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