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