]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/vk.py
Release 2023.06.22
[yt-dlp.git] / yt_dlp / extractor / vk.py
CommitLineData
51815886 1import collections
59f63c8f 2import hashlib
60d142aa 3import re
60d142aa
JMF
4
5from .common import InfoExtractor
59f63c8f
M
6from .dailymotion import DailymotionIE
7from .odnoklassniki import OdnoklassnikiIE
8from .pladform import PladformIE
7991ae57 9from .sibnet import SibnetEmbedIE
59f63c8f
M
10from .vimeo import VimeoIE
11from .youtube import YoutubeIE
60d142aa 12from ..utils import (
9032dc28 13 ExtractorError,
59f63c8f 14 clean_html,
2d19fb50 15 get_element_by_class,
a9c68545 16 get_element_html_by_id,
bf4b3b6b 17 int_or_none,
a9c68545 18 join_nonempty,
ad1bc71a 19 str_or_none,
8117df4c 20 str_to_int,
a9c68545 21 try_call,
60d142aa 22 unescapeHTML,
a7ee8a00 23 unified_timestamp,
59f63c8f 24 update_url_query,
3052a30d 25 url_or_none,
6e6bc8da 26 urlencode_postdata,
a9c68545 27 urljoin,
1cc79574 28)
60d142aa
JMF
29
30
2d19fb50
S
31class VKBaseIE(InfoExtractor):
32 _NETRC_MACHINE = 'vk'
33
59f63c8f
M
34 def _download_webpage_handle(self, url_or_request, video_id, *args, fatal=True, **kwargs):
35 response = super()._download_webpage_handle(url_or_request, video_id, *args, fatal=fatal, **kwargs)
36 challenge_url, cookie = response[1].geturl() if response else '', None
37 if challenge_url.startswith('https://vk.com/429.html?'):
38 cookie = self._get_cookies(challenge_url).get('hash429')
39 if not cookie:
40 return response
41
42 hash429 = hashlib.md5(cookie.value.encode('ascii')).hexdigest()
43 self._request_webpage(
44 update_url_query(challenge_url, {'key': hash429}), video_id, fatal=fatal,
45 note='Resolving WAF challenge', errnote='Failed to bypass WAF challenge')
46 return super()._download_webpage_handle(url_or_request, video_id, *args, fatal=True, **kwargs)
47
52efa4b3 48 def _perform_login(self, username, password):
2d19fb50
S
49 login_page, url_handle = self._download_webpage_handle(
50 'https://vk.com', None, 'Downloading login page')
51
52 login_form = self._hidden_inputs(login_page)
53
54 login_form.update({
55 'email': username.encode('cp1251'),
56 'pass': password.encode('cp1251'),
57 })
58
e3c1266f
S
59 # vk serves two same remixlhk cookies in Set-Cookie header and expects
60 # first one to be actually set
61 self._apply_first_set_cookie_header(url_handle, 'remixlhk')
2d19fb50
S
62
63 login_page = self._download_webpage(
f0ffaa16 64 'https://vk.com/login', None,
e4d95865 65 note='Logging in',
2d19fb50
S
66 data=urlencode_postdata(login_form))
67
68 if re.search(r'onLoginFailed', login_page):
69 raise ExtractorError(
70 'Unable to login, incorrect username and/or password', expected=True)
71
3c989818 72 def _download_payload(self, path, video_id, data, fatal=True):
59f63c8f 73 endpoint = f'https://vk.com/{path}.php'
3c989818
RA
74 data['al'] = 1
75 code, payload = self._download_json(
59f63c8f
M
76 endpoint, video_id, data=urlencode_postdata(data), fatal=fatal,
77 headers={
78 'Referer': endpoint,
79 'X-Requested-With': 'XMLHttpRequest',
80 })['payload']
3c989818
RA
81 if code == '3':
82 self.raise_login_required()
83 elif code == '8':
84 raise ExtractorError(clean_html(payload[0][1:-1]), expected=True)
85 return payload
86
2d19fb50
S
87
88class VKIE(VKBaseIE):
1ecb5d1d
S
89 IE_NAME = 'vk'
90 IE_DESC = 'VK'
bfd973ec 91 _EMBED_REGEX = [r'<iframe[^>]+?src=(["\'])(?P<url>https?://vk\.com/video_ext\.php.+?)\1']
cf9cf7dd
S
92 _VALID_URL = r'''(?x)
93 https?://
94 (?:
04e88ca2 95 (?:
bdafd88d 96 (?:(?:m|new)\.)?vk\.com/video_|
04e88ca2 97 (?:www\.)?daxab.com/
98 )
99 ext\.php\?(?P<embed_query>.*?\boid=(?P<oid>-?\d+).*?\bid=(?P<id>\d+).*)|
cf9cf7dd 100 (?:
21df2117 101 (?:(?:m|new)\.)?vk\.com/(?:.+?\?.*?z=)?(?:video|clip)|
04e88ca2 102 (?:www\.)?daxab.com/embed/
cf9cf7dd 103 )
af3cbd87 104 (?P<videoid>-?\d+_\d+)(?:.*\blist=(?P<list_id>([\da-f]+)|(ln-[\da-zA-Z]+)))?
cf9cf7dd
S
105 )
106 '''
7991ae57 107
9032dc28
S
108 _TESTS = [
109 {
110 'url': 'http://vk.com/videos-77521?z=video-77521_162222515%2Fclub77521',
9032dc28 111 'info_dict': {
220828f2 112 'id': '-77521_162222515',
09f934b0 113 'ext': 'mp4',
9032dc28 114 'title': 'ProtivoGunz - Хуёвая песня',
36300346 115 'uploader': 're:(?:Noize MC|Alexander Ilyashenko).*',
59f63c8f 116 'uploader_id': '39545378',
9032dc28 117 'duration': 195,
ad1bc71a 118 'timestamp': 1329049880,
42e1ff86 119 'upload_date': '20120212',
59f63c8f
M
120 'comment_count': int,
121 'like_count': int,
a9c68545 122 'thumbnail': r're:https?://.+(?:\.jpg|getVideoPreview.*)$',
9032dc28 123 },
59f63c8f 124 'params': {'skip_download': 'm3u8'},
60d142aa 125 },
9032dc28 126 {
c52331f3 127 'url': 'http://vk.com/video205387401_165548505',
9032dc28 128 'info_dict': {
220828f2 129 'id': '205387401_165548505',
9032dc28 130 'ext': 'mp4',
c52331f3 131 'title': 'No name',
ad1bc71a
RA
132 'uploader': 'Tom Cruise',
133 'uploader_id': '205387401',
c52331f3 134 'duration': 9,
ad1bc71a
RA
135 'timestamp': 1374364108,
136 'upload_date': '20130720',
59f63c8f
M
137 'comment_count': int,
138 'like_count': int,
a9c68545 139 'thumbnail': r're:https?://.+(?:\.jpg|getVideoPreview.*)$',
9032dc28
S
140 }
141 },
ca97a56e
S
142 {
143 'note': 'Embedded video',
3c989818 144 'url': 'https://vk.com/video_ext.php?oid=-77521&id=162222515&hash=87b046504ccd8bfa',
ca97a56e 145 'info_dict': {
3c989818 146 'id': '-77521_162222515',
ca97a56e 147 'ext': 'mp4',
3c989818
RA
148 'uploader': 're:(?:Noize MC|Alexander Ilyashenko).*',
149 'title': 'ProtivoGunz - Хуёвая песня',
150 'duration': 195,
151 'upload_date': '20120212',
152 'timestamp': 1329049880,
59f63c8f 153 'uploader_id': '39545378',
a9c68545 154 'thumbnail': r're:https?://.+(?:\.jpg|getVideoPreview.*)$',
04e88ca2 155 },
59f63c8f 156 'params': {'skip_download': 'm3u8'},
ca97a56e 157 },
af3cbd87 158 {
159 'url': 'https://vk.com/video-93049196_456239755?list=ln-cBjJ7S4jYYx3ADnmDT',
160 'info_dict': {
161 'id': '-93049196_456239755',
162 'ext': 'mp4',
163 'title': '8 серия (озвучка)',
164 'duration': 8383,
59f63c8f
M
165 'comment_count': int,
166 'uploader': 'Dizi2021',
167 'like_count': int,
168 'timestamp': 1640162189,
af3cbd87 169 'upload_date': '20211222',
59f63c8f 170 'uploader_id': '-93049196',
a9c68545 171 'thumbnail': r're:https?://.+(?:\.jpg|getVideoPreview.*)$',
af3cbd87 172 },
173 },
79913fde 174 {
a9c68545 175 'note': 'youtube embed',
9281f6d2
S
176 'url': 'https://vk.com/video276849682_170681728',
177 'info_dict': {
178 'id': 'V3K4mi0SYkc',
220828f2 179 'ext': 'mp4',
9281f6d2 180 'title': "DSWD Awards 'Children's Joy Foundation, Inc.' Certificate of Registration and License to Operate",
ad1bc71a 181 'description': 'md5:bf9c26cfa4acdfb146362682edd3827a',
220828f2 182 'duration': 178,
59f63c8f 183 'upload_date': '20130117',
ad1bc71a 184 'uploader': "Children's Joy Foundation Inc.",
9281f6d2
S
185 'uploader_id': 'thecjf',
186 'view_count': int,
59f63c8f
M
187 'channel_id': 'UCgzCNQ11TmR9V97ECnhi3gw',
188 'availability': 'public',
189 'like_count': int,
190 'live_status': 'not_live',
191 'playable_in_embed': True,
192 'channel': 'Children\'s Joy Foundation Inc.',
193 'uploader_url': 'http://www.youtube.com/user/thecjf',
194 'thumbnail': r're:https?://.+\.jpg$',
195 'tags': 'count:27',
196 'start_time': 0.0,
197 'categories': ['Nonprofits & Activism'],
198 'channel_url': 'https://www.youtube.com/channel/UCgzCNQ11TmR9V97ECnhi3gw',
a9c68545
M
199 'channel_follower_count': int,
200 'age_limit': 0,
201 },
202 },
203 {
204 'note': 'dailymotion embed',
205 'url': 'https://vk.com/video-95168827_456239103?list=cca524a0f0d5557e16',
206 'info_dict': {
207 'id': 'x8gfli0',
208 'ext': 'mp4',
209 'title': 'md5:45410f60ccd4b2760da98cb5fc777d70',
210 'description': 'md5:2e71c5c9413735cfa06cf1a166f16c84',
211 'uploader': 'Movies and cinema.',
212 'upload_date': '20221218',
213 'uploader_id': 'x1jdavv',
214 'timestamp': 1671387617,
59f63c8f 215 'age_limit': 0,
a9c68545
M
216 'duration': 2918,
217 'like_count': int,
218 'view_count': int,
219 'thumbnail': r're:https?://.+x1080$',
220 'tags': list
9281f6d2
S
221 },
222 },
e3845525 223 {
a9c68545 224 'url': 'https://vk.com/clips-74006511?z=clip-74006511_456247211',
e3845525 225 'info_dict': {
a9c68545 226 'id': '-74006511_456247211',
e3845525 227 'ext': 'mp4',
a9c68545
M
228 'comment_count': int,
229 'duration': 9,
230 'like_count': int,
231 'thumbnail': r're:https?://.+(?:\.jpg|getVideoPreview.*)$',
232 'timestamp': 1664995597,
233 'title': 'Clip by @madempress',
234 'upload_date': '20221005',
235 'uploader': 'Шальная императрица',
236 'uploader_id': '-74006511',
e3845525 237 },
e3845525 238 },
bf4b3b6b
S
239 {
240 # video key is extra_data not url\d+
241 'url': 'http://vk.com/video-110305615_171782105',
242 'md5': 'e13fcda136f99764872e739d13fac1d1',
243 'info_dict': {
220828f2 244 'id': '-110305615_171782105',
bf4b3b6b
S
245 'ext': 'mp4',
246 'title': 'S-Dance, репетиции к The way show',
247 'uploader': 'THE WAY SHOW | 17 апреля',
ad1bc71a
RA
248 'uploader_id': '-110305615',
249 'timestamp': 1454859345,
bf4b3b6b 250 'upload_date': '20160207',
ad1bc71a 251 },
59f63c8f 252 'skip': 'Removed',
bf4b3b6b 253 },
93aa0b63 254 {
a9c68545 255 'note': 'finished live stream, postlive_mp4',
93aa0b63 256 'url': 'https://vk.com/videos-387766?z=video-387766_456242764%2Fpl_-387766_-2',
93aa0b63 257 'info_dict': {
220828f2 258 'id': '-387766_456242764',
93aa0b63 259 'ext': 'mp4',
220828f2 260 'title': 'ИгроМир 2016 День 1 — Игромания Утром',
93aa0b63
S
261 'uploader': 'Игромания',
262 'duration': 5239,
220828f2
RA
263 'upload_date': '20160929',
264 'uploader_id': '-387766',
265 'timestamp': 1475137527,
59f63c8f
M
266 'thumbnail': r're:https?://.+\.jpg$',
267 'comment_count': int,
268 'like_count': int,
93aa0b63 269 },
3c989818
RA
270 'params': {
271 'skip_download': True,
272 },
93aa0b63 273 },
475f8a45 274 {
424ed37e 275 # live stream, hls and rtmp links, most likely already finished live
475f8a45
S
276 # stream by the time you are reading this comment
277 'url': 'https://vk.com/video-140332_456239111',
278 'only_matching': True,
279 },
a8363f3a
PH
280 {
281 # removed video, just testing that we match the pattern
282 'url': 'http://vk.com/feed?z=video-43215063_166094326%2Fbb50cacd3177146d7a',
283 'only_matching': True,
284 },
e58066e2
S
285 {
286 # age restricted video, requires vk account credentials
287 'url': 'https://vk.com/video205387401_164765225',
288 'only_matching': True,
289 },
a5e52a1f
S
290 {
291 # pladform embed
292 'url': 'https://vk.com/video-76116461_171554880',
293 'only_matching': True,
bdafd88d
S
294 },
295 {
296 'url': 'http://new.vk.com/video205387401_165548505',
297 'only_matching': True,
643dc0fc
CP
298 },
299 {
300 # This video is no longer available, because its author has been blocked.
301 'url': 'https://vk.com/video-10639516_456240611',
302 'only_matching': True,
a640c4d2 303 },
304 {
305 # The video is not available in your region.
306 'url': 'https://vk.com/video-51812607_171445436',
307 'only_matching': True,
21df2117 308 },
309 {
310 'url': 'https://vk.com/clip30014565_456240946',
311 'only_matching': True,
a640c4d2 312 }]
9032dc28 313
60d142aa 314 def _real_extract(self, url):
5ad28e7f 315 mobj = self._match_valid_url(url)
ca97a56e
S
316 video_id = mobj.group('videoid')
317
3c989818 318 mv_data = {}
04e88ca2 319 if video_id:
3c989818 320 data = {
59f63c8f 321 'act': 'show',
3c989818
RA
322 'video': video_id,
323 }
04e88ca2 324 # Some videos (removed?) can only be downloaded with list id specified
325 list_id = mobj.group('list_id')
326 if list_id:
3c989818
RA
327 data['list'] = list_id
328
329 payload = self._download_payload('al_video', video_id, data)
330 info_page = payload[1]
331 opts = payload[-1]
332 mv_data = opts.get('mvData') or {}
333 player = opts.get('player') or {}
04e88ca2 334 else:
ca97a56e 335 video_id = '%s_%s' % (mobj.group('oid'), mobj.group('id'))
9032dc28 336
3c989818
RA
337 info_page = self._download_webpage(
338 'http://vk.com/video_ext.php?' + mobj.group('embed_query'), video_id)
9032dc28 339
3c989818
RA
340 error_message = self._html_search_regex(
341 [r'(?s)<!><div[^>]+class="video_layer_message"[^>]*>(.+?)</div>',
342 r'(?s)<div[^>]+id="video_ext_msg"[^>]*>(.+?)</div>'],
343 info_page, 'error message', default=None)
344 if error_message:
345 raise ExtractorError(error_message, expected=True)
ee48b6a8 346
3c989818
RA
347 if re.search(r'<!>/login\.php\?.*\bact=security_check', info_page):
348 raise ExtractorError(
349 'You are trying to log in from an unusual location. You should confirm ownership at vk.com to log in with this IP.',
350 expected=True)
7f220b2f 351
3c989818 352 ERROR_COPYRIGHT = 'Video %s has been removed from public access due to rightholder complaint.'
1d1d60f6 353
3c989818
RA
354 ERRORS = {
355 r'>Видеозапись .*? была изъята из публичного доступа в связи с обращением правообладателя.<':
356 ERROR_COPYRIGHT,
1d1d60f6 357
3c989818
RA
358 r'>The video .*? was removed from public access by request of the copyright holder.<':
359 ERROR_COPYRIGHT,
3d36cea4 360
3c989818
RA
361 r'<!>Please log in or <':
362 'Video %s is only available for registered users, '
363 'use --username and --password options to provide account credentials.',
3d36cea4 364
3c989818
RA
365 r'<!>Unknown error':
366 'Video %s does not exist.',
1aa5172f 367
3c989818
RA
368 r'<!>Видео временно недоступно':
369 'Video %s is temporarily unavailable.',
d919fa33 370
3c989818
RA
371 r'<!>Access denied':
372 'Access denied to video %s.',
643dc0fc 373
3c989818
RA
374 r'<!>Видеозапись недоступна, так как её автор был заблокирован.':
375 'Video %s is no longer available, because its author has been blocked.',
643dc0fc 376
3c989818
RA
377 r'<!>This video is no longer available, because its author has been blocked.':
378 'Video %s is no longer available, because its author has been blocked.',
ad1bc71a 379
3c989818
RA
380 r'<!>This video is no longer available, because it has been deleted.':
381 'Video %s is no longer available, because it has been deleted.',
a640c4d2 382
3c989818
RA
383 r'<!>The video .+? is not available in your region.':
384 'Video %s is not available in your region.',
385 }
386
387 for error_re, error_msg in ERRORS.items():
388 if re.search(error_re, info_page):
389 raise ExtractorError(error_msg % video_id, expected=True)
9032dc28 390
3c989818
RA
391 player = self._parse_json(self._search_regex(
392 r'var\s+playerParams\s*=\s*({.+?})\s*;\s*\n',
393 info_page, 'player params'), video_id)
9334f8f1 394
5113b691 395 youtube_url = YoutubeIE._extract_url(info_page)
46478456 396 if youtube_url:
3c989818 397 return self.url_result(youtube_url, YoutubeIE.ie_key())
849086a1 398
09b9c45e 399 vimeo_url = VimeoIE._extract_url(url, info_page)
84663361 400 if vimeo_url is not None:
3c989818 401 return self.url_result(vimeo_url, VimeoIE.ie_key())
84663361 402
c4737bea
S
403 pladform_url = PladformIE._extract_url(info_page)
404 if pladform_url:
3c989818 405 return self.url_result(pladform_url, PladformIE.ie_key())
c4737bea 406
7a1818c9 407 m_rutube = re.search(
35972ba1 408 r'\ssrc="((?:https?:)?//rutube\.ru\\?/(?:video|play)\\?/embed(?:.*?))\\?"', info_page)
7a1818c9 409 if m_rutube is not None:
7a1818c9
PH
410 rutube_url = self._proto_relative_url(
411 m_rutube.group(1).replace('\\', ''))
412 return self.url_result(rutube_url)
413
43aebb7d 414 dailymotion_url = next(DailymotionIE._extract_embed_urls(url, info_page), None)
415 if dailymotion_url:
416 return self.url_result(dailymotion_url, DailymotionIE.ie_key())
e3845525 417
3c989818
RA
418 odnoklassniki_url = OdnoklassnikiIE._extract_url(info_page)
419 if odnoklassniki_url:
420 return self.url_result(odnoklassniki_url, OdnoklassnikiIE.ie_key())
421
7991ae57 422 sibnet_url = next(SibnetEmbedIE._extract_embed_urls(url, info_page), None)
43aebb7d 423 if sibnet_url:
424 return self.url_result(sibnet_url)
b73612a2 425
054932f4 426 m_opts = re.search(r'(?s)var\s+opts\s*=\s*({.+?});', info_page)
849086a1 427 if m_opts:
054932f4 428 m_opts_url = re.search(r"url\s*:\s*'((?!/\b)[^']+)", m_opts.group(1))
849086a1
S
429 if m_opts_url:
430 opts_url = m_opts_url.group(1)
431 if opts_url.startswith('//'):
432 opts_url = 'http:' + opts_url
433 return self.url_result(opts_url)
434
3c989818 435 data = player['params'][0]
475f8a45
S
436 title = unescapeHTML(data['md_title'])
437
424ed37e
S
438 # 2 = live
439 # 3 = post live (finished live)
9cdb0a33 440 is_live = data.get('live') == 2
475f8a45 441
a7ee8a00 442 timestamp = unified_timestamp(self._html_search_regex(
70d7b323 443 r'class=["\']mv_info_date[^>]+>([^<]+)(?:<|from)', info_page,
ad1bc71a 444 'upload date', default=None)) or int_or_none(data.get('date'))
3aa3953d 445
70d7b323
S
446 view_count = str_to_int(self._search_regex(
447 r'class=["\']mv_views_count[^>]+>\s*([\d,.]+)',
498a8a4c 448 info_page, 'view count', default=None))
8117df4c 449
bf4b3b6b 450 formats = []
475f8a45 451 for format_id, format_url in data.items():
3052a30d
S
452 format_url = url_or_none(format_url)
453 if not format_url or not format_url.startswith(('http', '//', 'rtmp')):
bf4b3b6b 454 continue
3089bc74
S
455 if (format_id.startswith(('url', 'cache'))
456 or format_id in ('extra_data', 'live_mp4', 'postlive_mp4')):
475f8a45
S
457 height = int_or_none(self._search_regex(
458 r'^(?:url|cache)(\d+)', format_id, 'height', default=None))
459 formats.append({
460 'format_id': format_id,
461 'url': format_url,
462 'height': height,
463 })
464 elif format_id == 'hls':
465 formats.extend(self._extract_m3u8_formats(
fb4fc449 466 format_url, video_id, 'mp4', 'm3u8_native',
9cdb0a33 467 m3u8_id=format_id, fatal=False, live=is_live))
475f8a45
S
468 elif format_id == 'rtmp':
469 formats.append({
470 'format_id': format_id,
471 'url': format_url,
472 'ext': 'flv',
473 })
913f3292 474
5b6cb562 475 subtitles = {}
476 for sub in data.get('subs') or {}:
477 subtitles.setdefault(sub.get('lang', 'en'), []).append({
478 'ext': sub.get('title', '.srt').split('.')[-1],
479 'url': url_or_none(sub.get('url')),
480 })
481
60d142aa 482 return {
220828f2 483 'id': video_id,
913f3292 484 'formats': formats,
475f8a45 485 'title': title,
913f3292
PH
486 'thumbnail': data.get('jpg'),
487 'uploader': data.get('md_author'),
3c989818
RA
488 'uploader_id': str_or_none(data.get('author_id') or mv_data.get('authorId')),
489 'duration': int_or_none(data.get('duration') or mv_data.get('duration')),
a7ee8a00 490 'timestamp': timestamp,
8117df4c 491 'view_count': view_count,
3c989818
RA
492 'like_count': int_or_none(mv_data.get('likes')),
493 'comment_count': int_or_none(mv_data.get('commcount')),
9cdb0a33 494 'is_live': is_live,
5b6cb562 495 'subtitles': subtitles,
60d142aa 496 }
469d4c89
WS
497
498
2d19fb50 499class VKUserVideosIE(VKBaseIE):
1ecb5d1d
S
500 IE_NAME = 'vk:uservideos'
501 IE_DESC = "VK - User's Videos"
5d14b734 502 _VALID_URL = r'https?://(?:(?:m|new)\.)?vk\.com/video/(?:playlist/)?(?P<id>[^?$#/&]+)(?!\?.*\bz=video)(?:[/?#&](?:.*?\bsection=(?P<section>\w+))?|$)'
469d4c89 503 _TEMPLATE_URL = 'https://vk.com/videos'
dc786d3d 504 _TESTS = [{
a70b71e8 505 'url': 'https://vk.com/video/@mobidevices',
0e6ec3ca 506 'info_dict': {
a70b71e8 507 'id': '-17892518_all',
0e6ec3ca 508 },
a70b71e8 509 'playlist_mincount': 1355,
0e6ec3ca 510 }, {
a70b71e8 511 'url': 'https://vk.com/video/@mobidevices?section=uploaded',
15ec6693 512 'info_dict': {
a70b71e8 513 'id': '-17892518_uploaded',
15ec6693 514 },
a70b71e8 515 'playlist_mincount': 182,
5d14b734
M
516 }, {
517 'url': 'https://vk.com/video/playlist/-174476437_2',
518 'info_dict': {
a9c68545 519 'id': '-174476437_playlist_2',
5d14b734
M
520 'title': 'Анонсы'
521 },
522 'playlist_mincount': 108,
dc786d3d 523 }]
0e6ec3ca 524 _VIDEO = collections.namedtuple('Video', ['owner_id', 'id'])
dc786d3d 525
a70b71e8
AG
526 def _entries(self, page_id, section):
527 video_list_json = self._download_payload('al_video', page_id, {
3c989818 528 'act': 'load_videos_silent',
a70b71e8 529 'offset': 0,
3c989818 530 'oid': page_id,
0e6ec3ca 531 'section': section,
a70b71e8
AG
532 })[0][section]
533 count = video_list_json['count']
534 total = video_list_json['total']
535 video_list = video_list_json['list']
536
537 while True:
538 for video in video_list:
539 v = self._VIDEO._make(video[:2])
540 video_id = '%d_%d' % (v.owner_id, v.id)
541 yield self.url_result(
542 'http://vk.com/video' + video_id, VKIE.ie_key(), video_id)
543 if count >= total:
544 break
545 video_list_json = self._download_payload('al_video', page_id, {
546 'act': 'load_videos_silent',
547 'offset': count,
548 'oid': page_id,
549 'section': section,
550 })[0][section]
551 count += video_list_json['count']
552 video_list = video_list_json['list']
0e6ec3ca
RA
553
554 def _real_extract(self, url):
a70b71e8
AG
555 u_id, section = self._match_valid_url(url).groups()
556 webpage = self._download_webpage(url, u_id)
5d14b734
M
557
558 if u_id.startswith('@'):
559 page_id = self._search_regex(r'data-owner-id\s?=\s?"([^"]+)"', webpage, 'page_id')
560 elif '_' in u_id:
561 page_id, section = u_id.split('_', 1)
a9c68545 562 section = f'playlist_{section}'
5d14b734
M
563 else:
564 raise ExtractorError('Invalid URL', expected=True)
565
0e6ec3ca
RA
566 if not section:
567 section = 'all'
568
5d14b734
M
569 playlist_title = clean_html(get_element_by_class('VideoInfoPanel__title', webpage))
570 return self.playlist_result(self._entries(page_id, section), '%s_%s' % (page_id, section), playlist_title)
2d19fb50
S
571
572
573class VKWallPostIE(VKBaseIE):
574 IE_NAME = 'vk:wallpost'
575 _VALID_URL = r'https?://(?:(?:(?:(?:m|new)\.)?vk\.com/(?:[^?]+\?.*\bw=)?wall(?P<id>-?\d+_\d+)))'
576 _TESTS = [{
577 # public page URL, audio playlist
578 'url': 'https://vk.com/bs.official?w=wall-23538238_35',
579 'info_dict': {
3c989818
RA
580 'id': '-23538238_35',
581 'title': 'Black Shadow - Wall post -23538238_35',
a9c68545 582 'description': 'md5:190c78f905a53e0de793d83933c6e67f',
2d19fb50
S
583 },
584 'playlist': [{
585 'md5': '5ba93864ec5b85f7ce19a9af4af080f6',
586 'info_dict': {
587 'id': '135220665_111806521',
a9c68545 588 'ext': 'm4a',
2d19fb50
S
589 'title': 'Black Shadow - Слепое Верование',
590 'duration': 370,
591 'uploader': 'Black Shadow',
592 'artist': 'Black Shadow',
593 'track': 'Слепое Верование',
594 },
595 }, {
596 'md5': '4cc7e804579122b17ea95af7834c9233',
597 'info_dict': {
598 'id': '135220665_111802303',
a9c68545 599 'ext': 'm4a',
2d19fb50
S
600 'title': 'Black Shadow - Война - Негасимое Бездны Пламя!',
601 'duration': 423,
602 'uploader': 'Black Shadow',
603 'artist': 'Black Shadow',
604 'track': 'Война - Негасимое Бездны Пламя!',
605 },
2d19fb50 606 }],
51815886 607 'params': {
3c989818 608 'skip_download': True,
51815886 609 },
2d19fb50 610 }, {
a9c68545
M
611 # single YouTube embed with irrelevant reaction videos
612 'url': 'https://vk.com/wall-32370614_7173954',
2d19fb50 613 'info_dict': {
a9c68545
M
614 'id': '-32370614_7173954',
615 'title': 'md5:9f93c405bbc00061d34007d78c75e3bc',
616 'description': 'md5:953b811f26fa9f21ee5856e2ea8e68fc',
2d19fb50
S
617 },
618 'playlist_count': 1,
2d19fb50
S
619 }, {
620 # wall page URL
621 'url': 'https://vk.com/wall-23538238_35',
622 'only_matching': True,
623 }, {
624 # mobile wall page URL
625 'url': 'https://m.vk.com/wall-23538238_35',
626 'only_matching': True,
627 }]
3c989818 628 _BASE64_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/='
0e6ec3ca 629 _AUDIO = collections.namedtuple('Audio', ['id', 'owner_id', 'url', 'title', 'performer', 'duration', 'album_id', 'unk', 'author_link', 'lyrics', 'flags', 'context', 'extra', 'hashes', 'cover_url', 'ads'])
3c989818
RA
630
631 def _decode(self, enc):
632 dec = ''
633 e = n = 0
634 for c in enc:
635 r = self._BASE64_CHARS.index(c)
636 cond = n % 4
637 e = 64 * e + r if cond else r
638 n += 1
639 if cond:
640 dec += chr(255 & e >> (-2 * n & 6))
641 return dec
642
643 def _unmask_url(self, mask_url, vk_id):
644 if 'audio_api_unavailable' in mask_url:
645 extra = mask_url.split('?extra=')[1].split('#')
646 func, base = self._decode(extra[1]).split(chr(11))
3c989818
RA
647 mask_url = list(self._decode(extra[0]))
648 url_len = len(mask_url)
649 indexes = [None] * url_len
650 index = int(base) ^ vk_id
651 for n in range(url_len - 1, -1, -1):
652 index = (url_len * (n + 1) ^ index + n) % url_len
653 indexes[n] = index
654 for n in range(1, url_len):
655 c = mask_url[n]
656 index = indexes[url_len - 1 - n]
657 mask_url[n] = mask_url[index]
658 mask_url[index] = c
659 mask_url = ''.join(mask_url)
660 return mask_url
2d19fb50
S
661
662 def _real_extract(self, url):
663 post_id = self._match_id(url)
664
3c989818
RA
665 webpage = self._download_payload('wkview', post_id, {
666 'act': 'show',
667 'w': 'wall' + post_id,
668 })[1]
2d19fb50 669
a9c68545 670 uploader = clean_html(get_element_by_class('PostHeaderTitle__authorName', webpage))
2d19fb50
S
671
672 entries = []
673
3c989818
RA
674 for audio in re.findall(r'data-audio="([^"]+)', webpage):
675 audio = self._parse_json(unescapeHTML(audio), post_id)
a9c68545 676 if not audio['url']:
3c989818 677 continue
a9c68545
M
678 title = unescapeHTML(audio.get('title'))
679 artist = unescapeHTML(audio.get('artist'))
3c989818 680 entries.append({
a9c68545
M
681 'id': f'{audio["owner_id"]}_{audio["id"]}',
682 'title': join_nonempty(artist, title, delim=' - '),
683 'thumbnails': try_call(lambda: [{'url': u} for u in audio['coverUrl'].split(',')]),
684 'duration': int_or_none(audio.get('duration')),
3c989818 685 'uploader': uploader,
a9c68545 686 'artist': artist,
3c989818 687 'track': title,
a9c68545
M
688 'formats': [{
689 'url': audio['url'],
690 'ext': 'm4a',
691 'vcodec': 'none',
692 'acodec': 'mp3',
693 'container': 'm4a_dash',
694 }],
3c989818 695 })
2d19fb50 696
a9c68545
M
697 entries.extend(self.url_result(urljoin(url, entry), VKIE) for entry in set(re.findall(
698 r'<a[^>]+href=(?:["\'])(/video(?:-?[\d_]+)[^"\']*)',
699 get_element_html_by_id('wl_post_body', webpage))))
2d19fb50
S
700
701 return self.playlist_result(
a9c68545
M
702 entries, post_id, join_nonempty(uploader, f'Wall post {post_id}', delim=' - '),
703 clean_html(get_element_by_class('wall_post_text', webpage)))