[ie/wistia] Support password-protected videos (#11100)
[yt-dlp3.git] / yt_dlp / extractor / rutube.py
blob2c416811af35306cc8a8ef07f97437e3532558bf
1 import itertools
3 from .common import InfoExtractor
4 from ..utils import (
5 bool_or_none,
6 determine_ext,
7 int_or_none,
8 parse_qs,
9 traverse_obj,
10 try_get,
11 unified_timestamp,
12 url_or_none,
16 class RutubeBaseIE(InfoExtractor):
17 def _download_api_info(self, video_id, query=None):
18 if not query:
19 query = {}
20 query['format'] = 'json'
21 return self._download_json(
22 f'http://rutube.ru/api/video/{video_id}/',
23 video_id, 'Downloading video JSON',
24 'Unable to download video JSON', query=query)
26 def _extract_info(self, video, video_id=None, require_title=True):
27 title = video['title'] if require_title else video.get('title')
29 age_limit = video.get('is_adult')
30 if age_limit is not None:
31 age_limit = 18 if age_limit is True else 0
33 uploader_id = try_get(video, lambda x: x['author']['id'])
34 category = try_get(video, lambda x: x['category']['name'])
35 description = video.get('description')
36 duration = int_or_none(video.get('duration'))
38 return {
39 'id': video.get('id') or video_id if video_id else video['id'],
40 'title': title,
41 'description': description,
42 'thumbnail': video.get('thumbnail_url'),
43 'duration': duration,
44 'uploader': try_get(video, lambda x: x['author']['name']),
45 'uploader_id': str(uploader_id) if uploader_id else None,
46 'timestamp': unified_timestamp(video.get('created_ts')),
47 'categories': [category] if category else None,
48 'age_limit': age_limit,
49 'view_count': int_or_none(video.get('hits')),
50 'comment_count': int_or_none(video.get('comments_count')),
51 'is_live': bool_or_none(video.get('is_livestream')),
52 'chapters': self._extract_chapters_from_description(description, duration),
55 def _download_and_extract_info(self, video_id, query=None):
56 return self._extract_info(
57 self._download_api_info(video_id, query=query), video_id)
59 def _download_api_options(self, video_id, query=None):
60 if not query:
61 query = {}
62 query['format'] = 'json'
63 return self._download_json(
64 f'http://rutube.ru/api/play/options/{video_id}/',
65 video_id, 'Downloading options JSON',
66 'Unable to download options JSON',
67 headers=self.geo_verification_headers(), query=query)
69 def _extract_formats(self, options, video_id):
70 formats = []
71 for format_id, format_url in options['video_balancer'].items():
72 ext = determine_ext(format_url)
73 if ext == 'm3u8':
74 formats.extend(self._extract_m3u8_formats(
75 format_url, video_id, 'mp4', m3u8_id=format_id, fatal=False))
76 elif ext == 'f4m':
77 formats.extend(self._extract_f4m_formats(
78 format_url, video_id, f4m_id=format_id, fatal=False))
79 else:
80 formats.append({
81 'url': format_url,
82 'format_id': format_id,
84 for hls_url in traverse_obj(options, ('live_streams', 'hls', ..., 'url', {url_or_none})):
85 formats.extend(self._extract_m3u8_formats(hls_url, video_id, ext='mp4', fatal=False))
86 return formats
88 def _download_and_extract_formats(self, video_id, query=None):
89 return self._extract_formats(
90 self._download_api_options(video_id, query=query), video_id)
93 class RutubeIE(RutubeBaseIE):
94 IE_NAME = 'rutube'
95 IE_DESC = 'Rutube videos'
96 _VALID_URL = r'https?://rutube\.ru/(?:(?:live/)?video(?:/private)?|(?:play/)?embed)/(?P<id>[\da-z]{32})'
97 _EMBED_REGEX = [r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//rutube\.ru/(?:play/)?embed/[\da-z]{32}.*?)\1']
99 _TESTS = [{
100 'url': 'http://rutube.ru/video/3eac3b4561676c17df9132a9a1e62e3e/',
101 'md5': 'e33ac625efca66aba86cbec9851f2692',
102 'info_dict': {
103 'id': '3eac3b4561676c17df9132a9a1e62e3e',
104 'ext': 'mp4',
105 'title': 'Раненный кенгуру забежал в аптеку',
106 'description': 'http://www.ntdtv.ru ',
107 'duration': 81,
108 'uploader': 'NTDRussian',
109 'uploader_id': '29790',
110 'timestamp': 1381943602,
111 'upload_date': '20131016',
112 'age_limit': 0,
113 'view_count': int,
114 'thumbnail': 'http://pic.rutubelist.ru/video/d2/a0/d2a0aec998494a396deafc7ba2c82add.jpg',
115 'categories': ['Новости и СМИ'],
116 'chapters': [],
118 'expected_warnings': ['Unable to download f4m'],
119 }, {
120 'url': 'http://rutube.ru/play/embed/a10e53b86e8f349080f718582ce4c661',
121 'only_matching': True,
122 }, {
123 'url': 'http://rutube.ru/embed/a10e53b86e8f349080f718582ce4c661',
124 'only_matching': True,
125 }, {
126 'url': 'http://rutube.ru/video/3eac3b4561676c17df9132a9a1e62e3e/?pl_id=4252',
127 'only_matching': True,
128 }, {
129 'url': 'https://rutube.ru/video/10b3a03fc01d5bbcc632a2f3514e8aab/?pl_type=source',
130 'only_matching': True,
131 }, {
132 'url': 'https://rutube.ru/video/private/884fb55f07a97ab673c7d654553e0f48/?p=x2QojCumHTS3rsKHWXN8Lg',
133 'md5': 'd106225f15d625538fe22971158e896f',
134 'info_dict': {
135 'id': '884fb55f07a97ab673c7d654553e0f48',
136 'ext': 'mp4',
137 'title': 'Яцуноками, Nioh2',
138 'description': 'Nioh2: финал сражения с боссом Яцуноками',
139 'duration': 15,
140 'uploader': 'mexus',
141 'uploader_id': '24222106',
142 'timestamp': 1670646232,
143 'upload_date': '20221210',
144 'age_limit': 0,
145 'view_count': int,
146 'thumbnail': 'http://pic.rutubelist.ru/video/f2/d4/f2d42b54be0a6e69c1c22539e3152156.jpg',
147 'categories': ['Видеоигры'],
148 'chapters': [],
150 'expected_warnings': ['Unable to download f4m'],
151 }, {
152 'url': 'https://rutube.ru/video/c65b465ad0c98c89f3b25cb03dcc87c6/',
153 'info_dict': {
154 'id': 'c65b465ad0c98c89f3b25cb03dcc87c6',
155 'ext': 'mp4',
156 'chapters': 'count:4',
157 'categories': ['Бизнес и предпринимательство'],
158 'description': 'md5:252feac1305257d8c1bab215cedde75d',
159 'thumbnail': 'http://pic.rutubelist.ru/video/71/8f/718f27425ea9706073eb80883dd3787b.png',
160 'duration': 782,
161 'age_limit': 0,
162 'uploader_id': '23491359',
163 'timestamp': 1677153329,
164 'view_count': int,
165 'upload_date': '20230223',
166 'title': 'Бизнес с нуля: найм сотрудников. Интервью с директором строительной компании',
167 'uploader': 'Стас Быков',
169 'expected_warnings': ['Unable to download f4m'],
170 }, {
171 'url': 'https://rutube.ru/live/video/c58f502c7bb34a8fcdd976b221fca292/',
172 'info_dict': {
173 'id': 'c58f502c7bb34a8fcdd976b221fca292',
174 'ext': 'mp4',
175 'categories': ['Телепередачи'],
176 'description': '',
177 'thumbnail': 'http://pic.rutubelist.ru/video/14/19/14190807c0c48b40361aca93ad0867c7.jpg',
178 'live_status': 'is_live',
179 'age_limit': 0,
180 'uploader_id': '23460655',
181 'timestamp': 1652972968,
182 'view_count': int,
183 'upload_date': '20220519',
184 'title': r're:Первый канал. Прямой эфир \d{4}-\d{2}-\d{2} \d{2}:\d{2}$',
185 'uploader': 'Первый канал',
187 }, {
188 'url': 'https://rutube.ru/video/5ab908fccfac5bb43ef2b1e4182256b0/',
189 'only_matching': True,
190 }, {
191 'url': 'https://rutube.ru/live/video/private/c58f502c7bb34a8fcdd976b221fca292/',
192 'only_matching': True,
195 @classmethod
196 def suitable(cls, url):
197 return False if RutubePlaylistIE.suitable(url) else super().suitable(url)
199 def _real_extract(self, url):
200 video_id = self._match_id(url)
201 query = parse_qs(url)
202 info = self._download_and_extract_info(video_id, query)
203 info['formats'] = self._download_and_extract_formats(video_id, query)
204 return info
207 class RutubeEmbedIE(RutubeBaseIE):
208 IE_NAME = 'rutube:embed'
209 IE_DESC = 'Rutube embedded videos'
210 _VALID_URL = r'https?://rutube\.ru/(?:video|play)/embed/(?P<id>[0-9]+)'
212 _TESTS = [{
213 'url': 'http://rutube.ru/video/embed/6722881?vk_puid37=&vk_puid38=',
214 'info_dict': {
215 'id': 'a10e53b86e8f349080f718582ce4c661',
216 'ext': 'mp4',
217 'timestamp': 1387830582,
218 'upload_date': '20131223',
219 'uploader_id': '297833',
220 'description': 'Видео группы ★http://vk.com/foxkidsreset★ музей Fox Kids и Jetix<br/><br/> восстановлено и сделано в шикоформате subziro89 http://vk.com/subziro89',
221 'uploader': 'subziro89 ILya',
222 'title': 'Мистический городок Эйри в Индиан 5 серия озвучка subziro89',
224 'params': {
225 'skip_download': True,
227 }, {
228 'url': 'http://rutube.ru/play/embed/8083783',
229 'only_matching': True,
230 }, {
231 # private video
232 'url': 'https://rutube.ru/play/embed/10631925?p=IbAigKqWd1do4mjaM5XLIQ',
233 'only_matching': True,
236 def _real_extract(self, url):
237 embed_id = self._match_id(url)
238 # Query may contain private videos token and should be passed to API
239 # requests (see #19163)
240 query = parse_qs(url)
241 options = self._download_api_options(embed_id, query)
242 video_id = options['effective_video']
243 formats = self._extract_formats(options, video_id)
244 info = self._download_and_extract_info(video_id, query)
245 info.update({
246 'extractor_key': 'Rutube',
247 'formats': formats,
249 return info
252 class RutubePlaylistBaseIE(RutubeBaseIE):
253 def _next_page_url(self, page_num, playlist_id, *args, **kwargs):
254 return self._PAGE_TEMPLATE % (playlist_id, page_num)
256 def _entries(self, playlist_id, *args, **kwargs):
257 next_page_url = None
258 for pagenum in itertools.count(1):
259 page = self._download_json(
260 next_page_url or self._next_page_url(
261 pagenum, playlist_id, *args, **kwargs),
262 playlist_id, f'Downloading page {pagenum}')
264 results = page.get('results')
265 if not results or not isinstance(results, list):
266 break
268 for result in results:
269 video_url = url_or_none(result.get('video_url'))
270 if not video_url:
271 continue
272 entry = self._extract_info(result, require_title=False)
273 entry.update({
274 '_type': 'url',
275 'url': video_url,
276 'ie_key': RutubeIE.ie_key(),
278 yield entry
280 next_page_url = page.get('next')
281 if not next_page_url or not page.get('has_next'):
282 break
284 def _extract_playlist(self, playlist_id, *args, **kwargs):
285 return self.playlist_result(
286 self._entries(playlist_id, *args, **kwargs),
287 playlist_id, kwargs.get('playlist_name'))
289 def _real_extract(self, url):
290 return self._extract_playlist(self._match_id(url))
293 class RutubeTagsIE(RutubePlaylistBaseIE):
294 IE_NAME = 'rutube:tags'
295 IE_DESC = 'Rutube tags'
296 _VALID_URL = r'https?://rutube\.ru/tags/video/(?P<id>\d+)'
297 _TESTS = [{
298 'url': 'http://rutube.ru/tags/video/1800/',
299 'info_dict': {
300 'id': '1800',
302 'playlist_mincount': 68,
305 _PAGE_TEMPLATE = 'http://rutube.ru/api/tags/video/%s/?page=%s&format=json'
308 class RutubeMovieIE(RutubePlaylistBaseIE):
309 IE_NAME = 'rutube:movie'
310 IE_DESC = 'Rutube movies'
311 _VALID_URL = r'https?://rutube\.ru/metainfo/tv/(?P<id>\d+)'
313 _MOVIE_TEMPLATE = 'http://rutube.ru/api/metainfo/tv/%s/?format=json'
314 _PAGE_TEMPLATE = 'http://rutube.ru/api/metainfo/tv/%s/video?page=%s&format=json'
316 def _real_extract(self, url):
317 movie_id = self._match_id(url)
318 movie = self._download_json(
319 self._MOVIE_TEMPLATE % movie_id, movie_id,
320 'Downloading movie JSON')
321 return self._extract_playlist(
322 movie_id, playlist_name=movie.get('name'))
325 class RutubePersonIE(RutubePlaylistBaseIE):
326 IE_NAME = 'rutube:person'
327 IE_DESC = 'Rutube person videos'
328 _VALID_URL = r'https?://rutube\.ru/video/person/(?P<id>\d+)'
329 _TESTS = [{
330 'url': 'http://rutube.ru/video/person/313878/',
331 'info_dict': {
332 'id': '313878',
334 'playlist_mincount': 37,
337 _PAGE_TEMPLATE = 'http://rutube.ru/api/video/person/%s/?page=%s&format=json'
340 class RutubePlaylistIE(RutubePlaylistBaseIE):
341 IE_NAME = 'rutube:playlist'
342 IE_DESC = 'Rutube playlists'
343 _VALID_URL = r'https?://rutube\.ru/(?:video|(?:play/)?embed)/[\da-z]{32}/\?.*?\bpl_id=(?P<id>\d+)'
344 _TESTS = [{
345 'url': 'https://rutube.ru/video/cecd58ed7d531fc0f3d795d51cee9026/?pl_id=3097&pl_type=tag',
346 'info_dict': {
347 'id': '3097',
349 'playlist_count': 27,
350 }, {
351 'url': 'https://rutube.ru/video/10b3a03fc01d5bbcc632a2f3514e8aab/?pl_id=4252&pl_type=source',
352 'only_matching': True,
355 _PAGE_TEMPLATE = 'http://rutube.ru/api/playlist/%s/%s/?page=%s&format=json'
357 @classmethod
358 def suitable(cls, url):
359 from ..utils import int_or_none, parse_qs
361 if not super().suitable(url):
362 return False
363 params = parse_qs(url)
364 return params.get('pl_type', [None])[0] and int_or_none(params.get('pl_id', [None])[0])
366 def _next_page_url(self, page_num, playlist_id, item_kind):
367 return self._PAGE_TEMPLATE % (item_kind, playlist_id, page_num)
369 def _real_extract(self, url):
370 qs = parse_qs(url)
371 playlist_kind = qs['pl_type'][0]
372 playlist_id = qs['pl_id'][0]
373 return self._extract_playlist(playlist_id, item_kind=playlist_kind)
376 class RutubeChannelIE(RutubePlaylistBaseIE):
377 IE_NAME = 'rutube:channel'
378 IE_DESC = 'Rutube channel'
379 _VALID_URL = r'https?://rutube\.ru/channel/(?P<id>\d+)/videos'
380 _TESTS = [{
381 'url': 'https://rutube.ru/channel/639184/videos/',
382 'info_dict': {
383 'id': '639184',
385 'playlist_mincount': 133,
388 _PAGE_TEMPLATE = 'http://rutube.ru/api/video/person/%s/?page=%s&format=json'