5 from .common
import InfoExtractor
6 from .dailymotion
import DailymotionIE
7 from .odnoklassniki
import OdnoklassnikiIE
8 from .pladform
import PladformIE
9 from .vimeo
import VimeoIE
10 from .youtube
import YoutubeIE
11 from ..compat
import compat_urlparse
28 class VKBaseIE(InfoExtractor
):
31 def _download_webpage_handle(self
, url_or_request
, video_id
, *args
, fatal
=True, **kwargs
):
32 response
= super()._download
_webpage
_handle
(url_or_request
, video_id
, *args
, fatal
=fatal
, **kwargs
)
33 challenge_url
, cookie
= response
[1].geturl() if response
else '', None
34 if challenge_url
.startswith('https://vk.com/429.html?'):
35 cookie
= self
._get
_cookies
(challenge_url
).get('hash429')
39 hash429
= hashlib
.md5(cookie
.value
.encode('ascii')).hexdigest()
40 self
._request
_webpage
(
41 update_url_query(challenge_url
, {'key': hash429}
), video_id
, fatal
=fatal
,
42 note
='Resolving WAF challenge', errnote
='Failed to bypass WAF challenge')
43 return super()._download
_webpage
_handle
(url_or_request
, video_id
, *args
, fatal
=True, **kwargs
)
45 def _perform_login(self
, username
, password
):
46 login_page
, url_handle
= self
._download
_webpage
_handle
(
47 'https://vk.com', None, 'Downloading login page')
49 login_form
= self
._hidden
_inputs
(login_page
)
52 'email': username
.encode('cp1251'),
53 'pass': password
.encode('cp1251'),
56 # vk serves two same remixlhk cookies in Set-Cookie header and expects
57 # first one to be actually set
58 self
._apply
_first
_set
_cookie
_header
(url_handle
, 'remixlhk')
60 login_page
= self
._download
_webpage
(
61 'https://vk.com/login', None,
63 data
=urlencode_postdata(login_form
))
65 if re
.search(r
'onLoginFailed', login_page
):
67 'Unable to login, incorrect username and/or password', expected
=True)
69 def _download_payload(self
, path
, video_id
, data
, fatal
=True):
70 endpoint
= f
'https://vk.com/{path}.php'
72 code
, payload
= self
._download
_json
(
73 endpoint
, video_id
, data
=urlencode_postdata(data
), fatal
=fatal
,
76 'X-Requested-With': 'XMLHttpRequest',
79 self
.raise_login_required()
81 raise ExtractorError(clean_html(payload
[0][1:-1]), expected
=True)
88 _EMBED_REGEX
= [r
'<iframe[^>]+?src=(["\'])(?P
<url
>https?
://vk\
.com
/video_ext\
.php
.+?
)\
1']
93 (?:(?:m|new)\.)?vk\.com/video_|
96 ext\.php\?(?P<embed_query>.*?\boid=(?P<oid>-?\d+).*?\bid=(?P<id>\d+).*)|
98 (?:(?:m|new)\.)?vk\.com/(?:.+?\?.*?z=)?(?:video|clip)|
99 (?:www\.)?daxab.com/embed/
101 (?P<videoid>-?\d+_\d+)(?:.*\blist=(?P<list_id>([\da-f]+)|(ln-[\da-zA-Z]+)))?
104 # https://help.sibnet.ru/?sibnet_video_embed
105 _EMBED_REGEX = [r'<iframe
\b[^
>]+\bsrc
=(["\'])(?P<url>(?:https?:)?//video\.sibnet\.ru/shell\.php\?.*?\bvideoid=\d+.*?)\1']
108 'url': 'http://vk.com/videos-77521?z=video-77521_162222515%2Fclub77521',
110 'id': '-77521_162222515',
112 'title': 'ProtivoGunz - Хуёвая песня',
113 'uploader': 're:(?:Noize MC|Alexander Ilyashenko).*',
114 'uploader_id': '39545378',
116 'timestamp': 1329049880,
117 'upload_date': '20120212',
118 'comment_count': int,
120 'thumbnail': r're:https?://.+\.jpg$',
122 'params': {'skip_download': 'm3u8'},
125 'url': 'http://vk.com/video205387401_165548505',
127 'id': '205387401_165548505',
130 'uploader': 'Tom Cruise',
131 'uploader_id': '205387401',
133 'timestamp': 1374364108,
134 'upload_date': '20130720',
135 'comment_count': int,
137 'thumbnail': r're:https?://.+\.jpg$',
141 'note': 'Embedded video',
142 'url': 'https://vk.com/video_ext.php?oid=-77521&id=162222515&hash=87b046504ccd8bfa',
144 'id': '-77521_162222515',
146 'uploader': 're:(?:Noize MC|Alexander Ilyashenko).*',
147 'title': 'ProtivoGunz - Хуёвая песня',
149 'upload_date': '20120212',
150 'timestamp': 1329049880,
151 'uploader_id': '39545378',
152 'thumbnail': r're:https?://.+\.jpg$',
154 'params': {'skip_download': 'm3u8'},
158 # please update if you find a video whose URL follows the same pattern
159 'url': 'http://vk.com/video-8871596_164049491',
160 'md5': 'a590bcaf3d543576c9bd162812387666',
161 'note': 'Only available for registered users',
163 'id': '-8871596_164049491',
165 'uploader': 'Триллеры',
166 'title': '► Бойцовский клуб / Fight Club 1999 [HD 720]',
168 'upload_date': '20121218',
174 'url': 'http://vk.com/hd_kino_mania?z=video-43215063_168067957%2F15c66b9b533119788d',
176 'id': '-43215063_168067957',
178 'uploader': 'Bro Mazter',
181 'upload_date': '20140328',
182 'uploader_id': '223413403',
183 'timestamp': 1396018030,
185 'skip': 'Requires vk account credentials',
188 'url': 'http://m.vk.com/video-43215063_169084319?list=125c627d1aa1cebb83&from=wall-43215063_2566540',
189 'md5': '0c45586baa71b7cb1d0784ee3f4e00a6',
190 'note': 'ivi.ru embed',
192 'id': '-43215063_169084319',
194 'title': 'Книга Илая',
196 'upload_date': '20140626',
202 'url': 'https://vk.com/video-93049196_456239755?list=ln-cBjJ7S4jYYx3ADnmDT',
204 'id': '-93049196_456239755',
206 'title': '8 серия (озвучка)',
208 'comment_count': int,
209 'uploader': 'Dizi2021',
211 'timestamp': 1640162189,
212 'upload_date': '20211222',
213 'uploader_id': '-93049196',
214 'thumbnail': r're:https?://.+\.jpg$',
218 # video (removed?) only available with list id
219 'url': 'https://vk.com/video30481095_171201961?list=8764ae2d21f14088d4',
220 'md5': '091287af5402239a1051c37ec7b92913',
222 'id': '30481095_171201961',
224 'title': 'ТюменцевВВ_09.07.2015',
225 'uploader': 'Anton Ivanov',
227 'upload_date': '20150709',
234 'url': 'https://vk.com/video276849682_170681728',
238 'title': "DSWD Awards
'Children's Joy Foundation
, Inc
.' Certificate of Registration and License to Operate",
239 'description
': 'md5
:bf9c26cfa4acdfb146362682edd3827a
',
241 'upload_date
': '20130117',
242 'uploader
': "Children's Joy Foundation Inc
.",
243 'uploader_id': 'thecjf',
245 'channel_id': 'UCgzCNQ11TmR9V97ECnhi3gw',
246 'availability': 'public',
248 'live_status': 'not_live',
249 'playable_in_embed': True,
250 'channel': 'Children\'s Joy Foundation Inc.',
251 'uploader_url': 'http://www.youtube.com/user/thecjf',
252 'thumbnail': r're:https?://.+\.jpg$',
255 'categories': ['Nonprofits & Activism'],
256 'channel_url': 'https://www.youtube.com/channel/UCgzCNQ11TmR9V97ECnhi3gw',
262 'url': 'https://vk.com/video-37468416_456239855',
264 'id': 'k3lz2cmXyRuJQSjGHUv',
266 'title': 'md5:d52606645c20b0ddbb21655adaa4f56f',
267 'description': 'md5:424b8e88cc873217f520e582ba28bb36',
268 'uploader': 'AniLibria.Tv',
269 'upload_date': '20160914',
270 'uploader_id': 'x1p5vl5',
271 'timestamp': 1473877246,
276 # video key is extra_data not url\d+
277 'url': 'http://vk.com/video-110305615_171782105',
278 'md5': 'e13fcda136f99764872e739d13fac1d1',
280 'id': '-110305615_171782105',
282 'title': 'S-Dance, репетиции к The way show',
283 'uploader': 'THE WAY SHOW | 17 апреля',
284 'uploader_id': '-110305615',
285 'timestamp': 1454859345,
286 'upload_date': '20160207',
291 # finished live stream, postlive_mp4
292 'url': 'https://vk.com/videos-387766?z=video-387766_456242764%2Fpl_-387766_-2',
294 'id': '-387766_456242764',
296 'title': 'ИгроМир 2016 День 1 — Игромания Утром',
297 'uploader': 'Игромания',
299 'upload_date': '20160929',
300 'uploader_id': '-387766',
301 'timestamp': 1475137527,
302 'thumbnail': r're:https?://.+\.jpg$',
303 'comment_count': int,
307 'skip_download': True,
311 # live stream, hls and rtmp links, most likely already finished live
312 # stream by the time you are reading this comment
313 'url': 'https://vk.com/video-140332_456239111',
314 'only_matching': True,
317 # removed video, just testing that we match the pattern
318 'url': 'http://vk.com/feed?z=video-43215063_166094326%2Fbb50cacd3177146d7a',
319 'only_matching': True,
322 # age restricted video, requires vk account credentials
323 'url': 'https://vk.com/video205387401_164765225',
324 'only_matching': True,
328 'url': 'https://vk.com/video-76116461_171554880',
329 'only_matching': True,
332 'url': 'http://new.vk.com/video205387401_165548505',
333 'only_matching': True,
336 # This video is no longer available, because its author has been blocked.
337 'url': 'https://vk.com/video-10639516_456240611',
338 'only_matching': True,
341 # The video is not available in your region.
342 'url': 'https://vk.com/video-51812607_171445436',
343 'only_matching': True,
346 'url': 'https://vk.com/clip30014565_456240946',
347 'only_matching': True,
350 def _real_extract(self, url):
351 mobj = self._match_valid_url(url)
352 video_id = mobj.group('videoid')
360 # Some videos (removed?) can only be downloaded with list id specified
361 list_id = mobj.group('list_id')
363 data['list'] = list_id
365 payload = self._download_payload('al_video', video_id, data)
366 info_page = payload[1]
368 mv_data = opts.get('mvData') or {}
369 player = opts.get('player') or {}
371 video_id = '%s_%s' % (mobj.group('oid'), mobj.group('id'))
373 info_page = self._download_webpage(
374 'http://vk.com/video_ext.php?' + mobj.group('embed_query'), video_id)
376 error_message = self._html_search_regex(
377 [r'(?s)<!><div[^>]+class="video_layer_message
"[^>]*>(.+?)</div>',
378 r'(?s)<div[^>]+id="video_ext_msg
"[^>]*>(.+?)</div>'],
379 info_page, 'error message', default=None)
381 raise ExtractorError(error_message, expected=True)
383 if re.search(r'<!>/login\.php\?.*\bact=security_check', info_page):
384 raise ExtractorError(
385 'You are trying to log in from an unusual location. You should confirm ownership at vk.com to log in with this IP.',
388 ERROR_COPYRIGHT = 'Video %s has been removed from public access due to rightholder complaint.'
391 r'>Видеозапись .*? была изъята из публичного доступа в связи с обращением правообладателя.<':
394 r'>The video .*? was removed from public access by request of the copyright holder.<':
397 r'<!>Please log in or <':
398 'Video %s is only available for registered users, '
399 'use --username and --password options to provide account credentials.',
402 'Video %s does not exist.',
404 r'<!>Видео временно недоступно':
405 'Video %s is temporarily unavailable.',
408 'Access denied to video %s.',
410 r'<!>Видеозапись недоступна, так как её автор был заблокирован.':
411 'Video %s is no longer available, because its author has been blocked.',
413 r'<!>This video is no longer available, because its author has been blocked.':
414 'Video %s is no longer available, because its author has been blocked.',
416 r'<!>This video is no longer available, because it has been deleted.':
417 'Video %s is no longer available, because it has been deleted.',
419 r'<!>The video .+? is not available in your region.':
420 'Video %s is not available in your region.',
423 for error_re, error_msg in ERRORS.items():
424 if re.search(error_re, info_page):
425 raise ExtractorError(error_msg % video_id, expected=True)
427 player = self._parse_json(self._search_regex(
428 r'var\s+playerParams\s*=\s*({.+?})\s*;\s*\n',
429 info_page, 'player params'), video_id)
431 youtube_url = YoutubeIE._extract_url(info_page)
433 return self.url_result(youtube_url, YoutubeIE.ie_key())
435 vimeo_url = VimeoIE._extract_url(url, info_page)
436 if vimeo_url is not None:
437 return self.url_result(vimeo_url, VimeoIE.ie_key())
439 pladform_url = PladformIE._extract_url(info_page)
441 return self.url_result(pladform_url, PladformIE.ie_key())
443 m_rutube = re.search(
444 r'\ssrc="((?
:https?
:)?
//rutube\
.ru
\\?
/(?
:video|play
)\\?
/embed(?
:.*?
))\\?
"', info_page)
445 if m_rutube is not None:
446 rutube_url = self._proto_relative_url(
447 m_rutube.group(1).replace('\\', ''))
448 return self.url_result(rutube_url)
450 dailymotion_url = next(DailymotionIE._extract_embed_urls(url, info_page), None)
452 return self.url_result(dailymotion_url, DailymotionIE.ie_key())
454 odnoklassniki_url = OdnoklassnikiIE._extract_url(info_page)
455 if odnoklassniki_url:
456 return self.url_result(odnoklassniki_url, OdnoklassnikiIE.ie_key())
458 sibnet_url = next(self._extract_embed_urls(url, info_page), None)
460 return self.url_result(sibnet_url)
462 m_opts = re.search(r'(?s)var\s+opts\s*=\s*({.+?});', info_page)
464 m_opts_url = re.search(r"url\s
*:\s
*'((?!/\b)[^']+)", m_opts.group(1))
466 opts_url = m_opts_url.group(1)
467 if opts_url.startswith('//'):
468 opts_url = 'http:' + opts_url
469 return self.url_result(opts_url)
471 data = player['params'][0]
472 title = unescapeHTML(data['md_title'])
475 # 3 = post live (finished live)
476 is_live = data.get('live') == 2
478 timestamp = unified_timestamp(self._html_search_regex(
479 r'class=["\']mv_info_date
[^
>]+>([^
<]+)(?
:<|
from)', info_page,
480 'upload date
', default=None)) or int_or_none(data.get('date
'))
482 view_count = str_to_int(self._search_regex(
483 r'class=["\']mv_views_count[^>]+>\s*([\d,.]+)',
484 info_page, 'view count', default=None))
487 for format_id, format_url in data.items():
488 format_url = url_or_none(format_url)
489 if not format_url or not format_url.startswith(('http', '//', 'rtmp')):
491 if (format_id.startswith(('url', 'cache'))
492 or format_id in ('extra_data', 'live_mp4', 'postlive_mp4')):
493 height = int_or_none(self._search_regex(
494 r'^(?:url|cache)(\d+)', format_id, 'height', default=None))
496 'format_id': format_id,
500 elif format_id == 'hls':
501 formats.extend(self._extract_m3u8_formats(
502 format_url, video_id, 'mp4', 'm3u8_native',
503 m3u8_id=format_id, fatal=False, live=is_live))
504 elif format_id == 'rtmp':
506 'format_id': format_id,
510 self._sort_formats(formats)
513 for sub in data.get('subs') or {}:
514 subtitles.setdefault(sub.get('lang', 'en'), []).append({
515 'ext': sub.get('title', '.srt').split('.')[-1],
516 'url': url_or_none(sub.get('url')),
523 'thumbnail': data.get('jpg'),
524 'uploader': data.get('md_author'),
525 'uploader_id': str_or_none(data.get('author_id') or mv_data.get('authorId')),
526 'duration': int_or_none(data.get('duration') or mv_data.get('duration')),
527 'timestamp': timestamp,
528 'view_count': view_count,
529 'like_count': int_or_none(mv_data.get('likes')),
530 'comment_count': int_or_none(mv_data.get('commcount')),
532 'subtitles': subtitles,
536 class VKUserVideosIE(VKBaseIE):
537 IE_NAME = 'vk:uservideos'
538 IE_DESC = "VK
- User
's Videos"
539 _VALID_URL = r'https?
://(?
:(?
:m|new
)\
.)?vk\
.com
/video
/(?
:playlist
/)?
(?P
<id>[^?$
#/&]+)(?!\?.*\bz=video)(?:[/?#&](?:.*?\bsection=(?P<section>\w+))?|$)'
540 _TEMPLATE_URL
= 'https://vk.com/videos'
542 'url': 'https://vk.com/video/@mobidevices',
544 'id': '-17892518_all',
546 'playlist_mincount': 1355,
548 'url': 'https://vk.com/video/@mobidevices?section=uploaded',
550 'id': '-17892518_uploaded',
552 'playlist_mincount': 182,
554 'url': 'https://vk.com/video/playlist/-174476437_2',
556 'id': '-174476437_2',
559 'playlist_mincount': 108,
561 _VIDEO
= collections
.namedtuple('Video', ['owner_id', 'id'])
563 def _entries(self
, page_id
, section
):
564 video_list_json
= self
._download
_payload
('al_video', page_id
, {
565 'act': 'load_videos_silent',
570 count
= video_list_json
['count']
571 total
= video_list_json
['total']
572 video_list
= video_list_json
['list']
575 for video
in video_list
:
576 v
= self
._VIDEO
._make
(video
[:2])
577 video_id
= '%d_%d' % (v
.owner_id
, v
.id)
578 yield self
.url_result(
579 'http://vk.com/video' + video_id
, VKIE
.ie_key(), video_id
)
582 video_list_json
= self
._download
_payload
('al_video', page_id
, {
583 'act': 'load_videos_silent',
588 count
+= video_list_json
['count']
589 video_list
= video_list_json
['list']
591 def _real_extract(self
, url
):
592 u_id
, section
= self
._match
_valid
_url
(url
).groups()
593 webpage
= self
._download
_webpage
(url
, u_id
)
595 if u_id
.startswith('@'):
596 page_id
= self
._search
_regex
(r
'data-owner-id\s?=\s?"([^"]+)"', webpage
, 'page_id')
598 page_id
, section
= u_id
.split('_', 1)
600 raise ExtractorError('Invalid URL', expected
=True)
605 playlist_title
= clean_html(get_element_by_class('VideoInfoPanel__title', webpage
))
606 return self
.playlist_result(self
._entries
(page_id
, section
), '%s_%s' % (page_id
, section
), playlist_title
)
609 class VKWallPostIE(VKBaseIE
):
610 IE_NAME
= 'vk:wallpost'
611 _VALID_URL
= r
'https?://(?:(?:(?:(?:m|new)\.)?vk\.com/(?:[^?]+\?.*\bw=)?wall(?P<id>-?\d+_\d+)))'
613 # public page URL, audio playlist
614 'url': 'https://vk.com/bs.official?w=wall-23538238_35',
616 'id': '-23538238_35',
617 'title': 'Black Shadow - Wall post -23538238_35',
618 'description': 'md5:3f84b9c4f9ef499731cf1ced9998cc0c',
621 'md5': '5ba93864ec5b85f7ce19a9af4af080f6',
623 'id': '135220665_111806521',
625 'title': 'Black Shadow - Слепое Верование',
627 'uploader': 'Black Shadow',
628 'artist': 'Black Shadow',
629 'track': 'Слепое Верование',
632 'md5': '4cc7e804579122b17ea95af7834c9233',
634 'id': '135220665_111802303',
636 'title': 'Black Shadow - Война - Негасимое Бездны Пламя!',
638 'uploader': 'Black Shadow',
639 'artist': 'Black Shadow',
640 'track': 'Война - Негасимое Бездны Пламя!',
644 'skip_download': True,
646 'skip': 'Requires vk account credentials',
648 # single YouTube embed, no leading -
649 'url': 'https://vk.com/wall85155021_6319',
651 'id': '85155021_6319',
652 'title': 'Сергей Горбунов - Wall post 85155021_6319',
655 'skip': 'Requires vk account credentials',
658 'url': 'https://vk.com/wall-23538238_35',
659 'only_matching': True,
661 # mobile wall page URL
662 'url': 'https://m.vk.com/wall-23538238_35',
663 'only_matching': True,
665 _BASE64_CHARS
= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/='
666 _AUDIO
= collections
.namedtuple('Audio', ['id', 'owner_id', 'url', 'title', 'performer', 'duration', 'album_id', 'unk', 'author_link', 'lyrics', 'flags', 'context', 'extra', 'hashes', 'cover_url', 'ads'])
668 def _decode(self
, enc
):
672 r
= self
._BASE
64_CHARS
.index(c
)
674 e
= 64 * e
+ r
if cond
else r
677 dec
+= chr(255 & e
>> (-2 * n
& 6))
680 def _unmask_url(self
, mask_url
, vk_id
):
681 if 'audio_api_unavailable' in mask_url
:
682 extra
= mask_url
.split('?extra=')[1].split('#')
683 func
, base
= self
._decode
(extra
[1]).split(chr(11))
684 mask_url
= list(self
._decode
(extra
[0]))
685 url_len
= len(mask_url
)
686 indexes
= [None] * url_len
687 index
= int(base
) ^ vk_id
688 for n
in range(url_len
- 1, -1, -1):
689 index
= (url_len
* (n
+ 1) ^ index
+ n
) % url_len
691 for n
in range(1, url_len
):
693 index
= indexes
[url_len
- 1 - n
]
694 mask_url
[n
] = mask_url
[index
]
696 mask_url
= ''.join(mask_url
)
699 def _real_extract(self
, url
):
700 post_id
= self
._match
_id
(url
)
702 webpage
= self
._download
_payload
('wkview', post_id
, {
704 'w': 'wall' + post_id
,
707 description
= clean_html(get_element_by_class('wall_post_text', webpage
))
708 uploader
= clean_html(get_element_by_class('author', webpage
))
712 for audio
in re
.findall(r
'data-audio="([^"]+)', webpage
):
713 audio
= self
._parse
_json
(unescapeHTML(audio
), post_id
)
714 a
= self
._AUDIO
._make
(audio
[:16])
717 title
= unescapeHTML(a
.title
)
718 performer
= unescapeHTML(a
.performer
)
720 'id': '%s_%s' % (a
.owner_id
, a
.id),
721 'url': self
._unmask
_url
(a
.url
, a
.ads
['vk_id']),
722 'title': '%s - %s' % (performer
, title
) if performer
else title
,
723 'thumbnails': [{'url': c_url}
for c_url
in a
.cover_url
.split(',')] if a
.cover_url
else None,
724 'duration': int_or_none(a
.duration
),
725 'uploader': uploader
,
729 'protocol': 'm3u8_native',
732 for video
in re
.finditer(
733 r
'<a[^>]+href=(["\'])(?P
<url
>/video(?
:-?
[\d_
]+).*?
)\
1', webpage):
734 entries.append(self.url_result(
735 compat_urlparse.urljoin(url, video.group('url
')), VKIE.ie_key()))
737 title = 'Wall post
%s' % post_id
739 return self.playlist_result(
740 orderedSet(entries), post_id,
741 '%s - %s' % (uploader, title) if uploader else title,