[rutube] Rework and generalize playlist extractors (closes #13565)
[youtube-dl] / youtube_dl / extractor / rutube.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import itertools
6
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_str,
10     compat_parse_qs,
11     compat_urllib_parse_urlparse,
12 )
13 from ..utils import (
14     determine_ext,
15     unified_timestamp,
16     try_get,
17     int_or_none,
18 )
19
20
21 class RutubeBaseIE(InfoExtractor):
22     def _extract_video(self, video, video_id=None, require_title=True):
23         title = video['title'] if require_title else video.get('title')
24
25         age_limit = video.get('is_adult')
26         if age_limit is not None:
27             age_limit = 18 if age_limit is True else 0
28
29         uploader_id = try_get(video, lambda x: x['author']['id'])
30         category = try_get(video, lambda x: x['category']['name'])
31
32         return {
33             'id': video.get('id') or video_id,
34             'title': title,
35             'description': video.get('description'),
36             'thumbnail': video.get('thumbnail_url'),
37             'duration': int_or_none(video.get('duration')),
38             'uploader': try_get(video, lambda x: x['author']['name']),
39             'uploader_id': compat_str(uploader_id) if uploader_id else None,
40             'timestamp': unified_timestamp(video.get('created_ts')),
41             'category': [category] if category else None,
42             'age_limit': age_limit,
43             'view_count': int_or_none(video.get('hits')),
44             'comment_count': int_or_none(video.get('comments_count')),
45             'is_live': video.get('is_livestream'),
46         }
47
48
49 class RutubeIE(RutubeBaseIE):
50     IE_NAME = 'rutube'
51     IE_DESC = 'Rutube videos'
52     _VALID_URL = r'https?://rutube\.ru/(?:video|(?:play/)?embed)/(?P<id>[\da-z]{32})'
53
54     _TESTS = [{
55         'url': 'http://rutube.ru/video/3eac3b4561676c17df9132a9a1e62e3e/',
56         'md5': '79938ade01294ef7e27574890d0d3769',
57         'info_dict': {
58             'id': '3eac3b4561676c17df9132a9a1e62e3e',
59             'ext': 'flv',
60             'title': 'Раненный кенгуру забежал в аптеку',
61             'description': 'http://www.ntdtv.ru ',
62             'duration': 80,
63             'uploader': 'NTDRussian',
64             'uploader_id': '29790',
65             'timestamp': 1381943602,
66             'upload_date': '20131016',
67             'age_limit': 0,
68         },
69     }, {
70         'url': 'http://rutube.ru/play/embed/a10e53b86e8f349080f718582ce4c661',
71         'only_matching': True,
72     }, {
73         'url': 'http://rutube.ru/embed/a10e53b86e8f349080f718582ce4c661',
74         'only_matching': True,
75     }, {
76         'url': 'http://rutube.ru/video/3eac3b4561676c17df9132a9a1e62e3e/?pl_id=4252',
77         'only_matching': True,
78     }, {
79         'url': 'https://rutube.ru/video/10b3a03fc01d5bbcc632a2f3514e8aab/?pl_type=source',
80         'only_matching': True,
81     }]
82
83     @classmethod
84     def suitable(cls, url):
85         return False if RutubePlaylistIE.suitable(url) else super(RutubeIE, cls).suitable(url)
86
87     @staticmethod
88     def _extract_urls(webpage):
89         return [mobj.group('url') for mobj in re.finditer(
90             r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//rutube\.ru/embed/[\da-z]{32}.*?)\1',
91             webpage)]
92
93     def _real_extract(self, url):
94         video_id = self._match_id(url)
95
96         video = self._download_json(
97             'http://rutube.ru/api/video/%s/?format=json' % video_id,
98             video_id, 'Downloading video JSON')
99
100         info = self._extract_video(video, video_id)
101
102         options = self._download_json(
103             'http://rutube.ru/api/play/options/%s/?format=json' % video_id,
104             video_id, 'Downloading options JSON')
105
106         formats = []
107         for format_id, format_url in options['video_balancer'].items():
108             ext = determine_ext(format_url)
109             if ext == 'm3u8':
110                 formats.extend(self._extract_m3u8_formats(
111                     format_url, video_id, 'mp4', m3u8_id=format_id, fatal=False))
112             elif ext == 'f4m':
113                 formats.extend(self._extract_f4m_formats(
114                     format_url, video_id, f4m_id=format_id, fatal=False))
115             else:
116                 formats.append({
117                     'url': format_url,
118                     'format_id': format_id,
119                 })
120         self._sort_formats(formats)
121
122         info['formats'] = formats
123         return info
124
125
126 class RutubeEmbedIE(InfoExtractor):
127     IE_NAME = 'rutube:embed'
128     IE_DESC = 'Rutube embedded videos'
129     _VALID_URL = r'https?://rutube\.ru/(?:video|play)/embed/(?P<id>[0-9]+)'
130
131     _TESTS = [{
132         'url': 'http://rutube.ru/video/embed/6722881?vk_puid37=&vk_puid38=',
133         'info_dict': {
134             'id': 'a10e53b86e8f349080f718582ce4c661',
135             'ext': 'flv',
136             'timestamp': 1387830582,
137             'upload_date': '20131223',
138             'uploader_id': '297833',
139             'description': 'Видео группы ★http://vk.com/foxkidsreset★ музей Fox Kids и Jetix<br/><br/> восстановлено и сделано в шикоформате subziro89 http://vk.com/subziro89',
140             'uploader': 'subziro89 ILya',
141             'title': 'Мистический городок Эйри в Индиан 5 серия озвучка subziro89',
142         },
143         'params': {
144             'skip_download': True,
145         },
146     }, {
147         'url': 'http://rutube.ru/play/embed/8083783',
148         'only_matching': True,
149     }]
150
151     def _real_extract(self, url):
152         embed_id = self._match_id(url)
153         webpage = self._download_webpage(url, embed_id)
154
155         canonical_url = self._html_search_regex(
156             r'<link\s+rel="canonical"\s+href="([^"]+?)"', webpage,
157             'Canonical URL')
158         return self.url_result(canonical_url, RutubeIE.ie_key())
159
160
161 class RutubePlaylistBaseIE(RutubeBaseIE):
162     def _next_page_url(self, page_num, playlist_id, *args, **kwargs):
163         return self._PAGE_TEMPLATE % (playlist_id, page_num)
164
165     def _entries(self, playlist_id, *args, **kwargs):
166         next_page_url = None
167         for pagenum in itertools.count(1):
168             page = self._download_json(
169                 next_page_url or self._next_page_url(
170                     pagenum, playlist_id, *args, **kwargs),
171                 playlist_id, 'Downloading page %s' % pagenum)
172
173             results = page.get('results')
174             if not results or not isinstance(results, list):
175                 break
176
177             for result in results:
178                 video_url = result.get('video_url')
179                 if not video_url or not isinstance(video_url, compat_str):
180                     continue
181                 entry = self._extract_video(result, require_title=False)
182                 entry.update({
183                     '_type': 'url',
184                     'url': video_url,
185                     'ie_key': RutubeIE.ie_key(),
186                 })
187                 yield entry
188
189             next_page_url = page.get('next')
190             if not next_page_url or not page.get('has_next'):
191                 break
192
193     def _extract_playlist(self, playlist_id, *args, **kwargs):
194         return self.playlist_result(
195             self._entries(playlist_id, *args, **kwargs),
196             playlist_id, kwargs.get('playlist_name'))
197
198     def _real_extract(self, url):
199         return self._extract_playlist(self._match_id(url))
200
201
202 class RutubeChannelIE(RutubePlaylistBaseIE):
203     IE_NAME = 'rutube:channel'
204     IE_DESC = 'Rutube channels'
205     _VALID_URL = r'https?://rutube\.ru/tags/video/(?P<id>\d+)'
206     _TESTS = [{
207         'url': 'http://rutube.ru/tags/video/1800/',
208         'info_dict': {
209             'id': '1800',
210         },
211         'playlist_mincount': 68,
212     }]
213
214     _PAGE_TEMPLATE = 'http://rutube.ru/api/tags/video/%s/?page=%s&format=json'
215
216
217 class RutubeMovieIE(RutubePlaylistBaseIE):
218     IE_NAME = 'rutube:movie'
219     IE_DESC = 'Rutube movies'
220     _VALID_URL = r'https?://rutube\.ru/metainfo/tv/(?P<id>\d+)'
221     _TESTS = []
222
223     _MOVIE_TEMPLATE = 'http://rutube.ru/api/metainfo/tv/%s/?format=json'
224     _PAGE_TEMPLATE = 'http://rutube.ru/api/metainfo/tv/%s/video?page=%s&format=json'
225
226     def _real_extract(self, url):
227         movie_id = self._match_id(url)
228         movie = self._download_json(
229             self._MOVIE_TEMPLATE % movie_id, movie_id,
230             'Downloading movie JSON')
231         return self._extract_playlist(
232             movie_id, playlist_name=movie.get('name'))
233
234
235 class RutubePersonIE(RutubePlaylistBaseIE):
236     IE_NAME = 'rutube:person'
237     IE_DESC = 'Rutube person videos'
238     _VALID_URL = r'https?://rutube\.ru/video/person/(?P<id>\d+)'
239     _TESTS = [{
240         'url': 'http://rutube.ru/video/person/313878/',
241         'info_dict': {
242             'id': '313878',
243         },
244         'playlist_mincount': 37,
245     }]
246
247     _PAGE_TEMPLATE = 'http://rutube.ru/api/video/person/%s/?page=%s&format=json'
248
249
250 class RutubePlaylistIE(RutubePlaylistBaseIE):
251     IE_NAME = 'rutube:playlist'
252     IE_DESC = 'Rutube playlists'
253     _VALID_URL = r'https?://rutube\.ru/(?:video|(?:play/)?embed)/[\da-z]{32}/\?.*?\bpl_id=(?P<id>\d+)'
254     _TESTS = [{
255         'url': 'https://rutube.ru/video/cecd58ed7d531fc0f3d795d51cee9026/?pl_id=3097&pl_type=tag',
256         'info_dict': {
257             'id': '3097',
258         },
259         'playlist_count': 27,
260     }, {
261         'url': 'https://rutube.ru/video/10b3a03fc01d5bbcc632a2f3514e8aab/?pl_id=4252&pl_type=source',
262         'only_matching': True,
263     }]
264
265     _PAGE_TEMPLATE = 'http://rutube.ru/api/playlist/%s/%s/?page=%s&format=json'
266
267     @staticmethod
268     def suitable(url):
269         params = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
270         return params.get('pl_type', [None])[0] and int_or_none(params.get('pl_id', [None])[0])
271
272     def _next_page_url(self, page_num, playlist_id, item_kind):
273         return self._PAGE_TEMPLATE % (item_kind, playlist_id, page_num)
274
275     def _real_extract(self, url):
276         qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
277         playlist_kind = qs['pl_type'][0]
278         playlist_id = qs['pl_id'][0]
279         return self._extract_playlist(playlist_id, item_kind=playlist_kind)