[ivi:compilation] Fix extraction
[youtube-dl] / youtube_dl / extractor / ivi.py
1 # encoding: 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     sanitized_Request,
12 )
13
14
15 class IviIE(InfoExtractor):
16     IE_DESC = 'ivi.ru'
17     IE_NAME = 'ivi'
18     _VALID_URL = r'https?://(?:www\.)?ivi\.ru/(?:watch/(?:[^/]+/)?|video/player\?.*?videoId=)(?P<id>\d+)'
19
20     _TESTS = [
21         # Single movie
22         {
23             'url': 'http://www.ivi.ru/watch/53141',
24             'md5': '6ff5be2254e796ed346251d117196cf4',
25             'info_dict': {
26                 'id': '53141',
27                 'ext': 'mp4',
28                 'title': 'Иван Васильевич меняет профессию',
29                 'description': 'md5:b924063ea1677c8fe343d8a72ac2195f',
30                 'duration': 5498,
31                 'thumbnail': 're:^https?://.*\.jpg$',
32             },
33             'skip': 'Only works from Russia',
34         },
35         # Serial's serie
36         {
37             'url': 'http://www.ivi.ru/watch/dvoe_iz_lartsa/9549',
38             'md5': '221f56b35e3ed815fde2df71032f4b3e',
39             'info_dict': {
40                 'id': '9549',
41                 'ext': 'mp4',
42                 'title': 'Двое из ларца - Дело Гольдберга (1 часть)',
43                 'series': 'Двое из ларца',
44                 'episode': 'Дело Гольдберга (1 часть)',
45                 'episode_number': 1,
46                 'duration': 2655,
47                 'thumbnail': 're:^https?://.*\.jpg$',
48             },
49             'skip': 'Only works from Russia',
50         }
51     ]
52
53     # Sorted by quality
54     _KNOWN_FORMATS = ['MP4-low-mobile', 'MP4-mobile', 'FLV-lo', 'MP4-lo', 'FLV-hi', 'MP4-hi', 'MP4-SHQ']
55
56     def _real_extract(self, url):
57         video_id = self._match_id(url)
58
59         data = {
60             'method': 'da.content.get',
61             'params': [
62                 video_id, {
63                     'site': 's183',
64                     'referrer': 'http://www.ivi.ru/watch/%s' % video_id,
65                     'contentid': video_id
66                 }
67             ]
68         }
69
70         request = sanitized_Request(
71             'http://api.digitalaccess.ru/api/json/', json.dumps(data))
72         video_json = self._download_json(
73             request, video_id, 'Downloading video JSON')
74
75         if 'error' in video_json:
76             error = video_json['error']
77             if error['origin'] == 'NoRedisValidData':
78                 raise ExtractorError('Video %s does not exist' % video_id, expected=True)
79             raise ExtractorError(
80                 'Unable to download video %s: %s' % (video_id, error['message']),
81                 expected=True)
82
83         result = video_json['result']
84
85         formats = [{
86             'url': x['url'],
87             'format_id': x['content_format'],
88             'preference': self._KNOWN_FORMATS.index(x['content_format']),
89         } for x in result['files'] if x['content_format'] in self._KNOWN_FORMATS]
90
91         self._sort_formats(formats)
92
93         title = result['title']
94
95         duration = int_or_none(result.get('duration'))
96         compilation = result.get('compilation')
97         episode = title if compilation else None
98
99         title = '%s - %s' % (compilation, title) if compilation is not None else title
100
101         thumbnails = [{
102             'url': preview['url'],
103             'id': preview.get('content_format'),
104         } for preview in result.get('preview', []) if preview.get('url')]
105
106         webpage = self._download_webpage(url, video_id)
107
108         episode_number = int_or_none(self._search_regex(
109             r'<meta[^>]+itemprop="episode"[^>]*>\s*<meta[^>]+itemprop="episodeNumber"[^>]+content="(\d+)',
110             webpage, 'episode number', default=None))
111
112         description = self._og_search_description(webpage, default=None) or self._html_search_meta(
113             'description', webpage, 'description', default=None)
114
115         return {
116             'id': video_id,
117             'title': title,
118             'series': compilation,
119             'episode': episode,
120             'episode_number': episode_number,
121             'thumbnails': thumbnails,
122             'description': description,
123             'duration': duration,
124             'formats': formats,
125         }
126
127
128 class IviCompilationIE(InfoExtractor):
129     IE_DESC = 'ivi.ru compilations'
130     IE_NAME = 'ivi:compilation'
131     _VALID_URL = r'https?://(?:www\.)?ivi\.ru/watch/(?!\d+)(?P<compilationid>[a-z\d_-]+)(?:/season(?P<seasonid>\d+))?$'
132     _TESTS = [{
133         'url': 'http://www.ivi.ru/watch/dvoe_iz_lartsa',
134         'info_dict': {
135             'id': 'dvoe_iz_lartsa',
136             'title': 'Двое из ларца (2006 - 2008)',
137         },
138         'playlist_mincount': 24,
139     }, {
140         'url': 'http://www.ivi.ru/watch/dvoe_iz_lartsa/season1',
141         'info_dict': {
142             'id': 'dvoe_iz_lartsa/season1',
143             'title': 'Двое из ларца (2006 - 2008) 1 сезон',
144         },
145         'playlist_mincount': 12,
146     }]
147
148     def _extract_entries(self, html, compilation_id):
149         return [
150             self.url_result(
151                 'http://www.ivi.ru/watch/%s/%s' % (compilation_id, serie), IviIE.ie_key())
152             for serie in re.findall(
153                 r'<a href="/watch/%s/(\d+)"[^>]+data-id="\1"' % compilation_id, html)]
154
155     def _real_extract(self, url):
156         mobj = re.match(self._VALID_URL, url)
157         compilation_id = mobj.group('compilationid')
158         season_id = mobj.group('seasonid')
159
160         if season_id is not None:  # Season link
161             season_page = self._download_webpage(
162                 url, compilation_id, 'Downloading season %s web page' % season_id)
163             playlist_id = '%s/season%s' % (compilation_id, season_id)
164             playlist_title = self._html_search_meta('title', season_page, 'title')
165             entries = self._extract_entries(season_page, compilation_id)
166         else:  # Compilation link
167             compilation_page = self._download_webpage(url, compilation_id, 'Downloading compilation web page')
168             playlist_id = compilation_id
169             playlist_title = self._html_search_meta('title', compilation_page, 'title')
170             seasons = re.findall(
171                 r'<a href="/watch/%s/season(\d+)' % compilation_id, compilation_page)
172             if not seasons:  # No seasons in this compilation
173                 entries = self._extract_entries(compilation_page, compilation_id)
174             else:
175                 entries = []
176                 for season_id in seasons:
177                     season_page = self._download_webpage(
178                         'http://www.ivi.ru/watch/%s/season%s' % (compilation_id, season_id),
179                         compilation_id, 'Downloading season %s web page' % season_id)
180                     entries.extend(self._extract_entries(season_page, compilation_id))
181
182         return self.playlist_result(entries, playlist_id, playlist_title)