logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

vk.py (26325B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import collections
  4. import functools
  5. import re
  6. from .common import InfoExtractor
  7. from ..compat import compat_urlparse
  8. from ..utils import (
  9. clean_html,
  10. ExtractorError,
  11. get_element_by_class,
  12. int_or_none,
  13. OnDemandPagedList,
  14. orderedSet,
  15. str_or_none,
  16. str_to_int,
  17. unescapeHTML,
  18. unified_timestamp,
  19. url_or_none,
  20. urlencode_postdata,
  21. )
  22. from .dailymotion import DailymotionIE
  23. from .odnoklassniki import OdnoklassnikiIE
  24. from .pladform import PladformIE
  25. from .vimeo import VimeoIE
  26. from .youtube import YoutubeIE
  27. class VKBaseIE(InfoExtractor):
  28. _NETRC_MACHINE = 'vk'
  29. def _login(self):
  30. username, password = self._get_login_info()
  31. if username is None:
  32. return
  33. login_page, url_handle = self._download_webpage_handle(
  34. 'https://vk.com', None, 'Downloading login page')
  35. login_form = self._hidden_inputs(login_page)
  36. login_form.update({
  37. 'email': username.encode('cp1251'),
  38. 'pass': password.encode('cp1251'),
  39. })
  40. # vk serves two same remixlhk cookies in Set-Cookie header and expects
  41. # first one to be actually set
  42. self._apply_first_set_cookie_header(url_handle, 'remixlhk')
  43. login_page = self._download_webpage(
  44. 'https://login.vk.com/?act=login', None,
  45. note='Logging in',
  46. data=urlencode_postdata(login_form))
  47. if re.search(r'onLoginFailed', login_page):
  48. raise ExtractorError(
  49. 'Unable to login, incorrect username and/or password', expected=True)
  50. def _real_initialize(self):
  51. self._login()
  52. def _download_payload(self, path, video_id, data, fatal=True):
  53. data['al'] = 1
  54. code, payload = self._download_json(
  55. 'https://vk.com/%s.php' % path, video_id,
  56. data=urlencode_postdata(data), fatal=fatal,
  57. headers={'X-Requested-With': 'XMLHttpRequest'})['payload']
  58. if code == '3':
  59. self.raise_login_required()
  60. elif code == '8':
  61. raise ExtractorError(clean_html(payload[0][1:-1]), expected=True)
  62. return payload
  63. class VKIE(VKBaseIE):
  64. IE_NAME = 'vk'
  65. IE_DESC = 'VK'
  66. _VALID_URL = r'''(?x)
  67. https?://
  68. (?:
  69. (?:
  70. (?:(?:m|new)\.)?vk\.com/video_|
  71. (?:www\.)?daxab.com/
  72. )
  73. ext\.php\?(?P<embed_query>.*?\boid=(?P<oid>-?\d+).*?\bid=(?P<id>\d+).*)|
  74. (?:
  75. (?:(?:m|new)\.)?vk\.com/(?:.+?\?.*?z=)?video|
  76. (?:www\.)?daxab.com/embed/
  77. )
  78. (?P<videoid>-?\d+_\d+)(?:.*\blist=(?P<list_id>[\da-f]+))?
  79. )
  80. '''
  81. _TESTS = [
  82. {
  83. 'url': 'http://vk.com/videos-77521?z=video-77521_162222515%2Fclub77521',
  84. 'md5': '7babad3b85ea2e91948005b1b8b0cb84',
  85. 'info_dict': {
  86. 'id': '-77521_162222515',
  87. 'ext': 'mp4',
  88. 'title': 'ProtivoGunz - Хуёвая песня',
  89. 'uploader': 're:(?:Noize MC|Alexander Ilyashenko).*',
  90. 'uploader_id': '-77521',
  91. 'duration': 195,
  92. 'timestamp': 1329049880,
  93. 'upload_date': '20120212',
  94. },
  95. },
  96. {
  97. 'url': 'http://vk.com/video205387401_165548505',
  98. 'info_dict': {
  99. 'id': '205387401_165548505',
  100. 'ext': 'mp4',
  101. 'title': 'No name',
  102. 'uploader': 'Tom Cruise',
  103. 'uploader_id': '205387401',
  104. 'duration': 9,
  105. 'timestamp': 1374364108,
  106. 'upload_date': '20130720',
  107. }
  108. },
  109. {
  110. 'note': 'Embedded video',
  111. 'url': 'https://vk.com/video_ext.php?oid=-77521&id=162222515&hash=87b046504ccd8bfa',
  112. 'md5': '7babad3b85ea2e91948005b1b8b0cb84',
  113. 'info_dict': {
  114. 'id': '-77521_162222515',
  115. 'ext': 'mp4',
  116. 'uploader': 're:(?:Noize MC|Alexander Ilyashenko).*',
  117. 'title': 'ProtivoGunz - Хуёвая песня',
  118. 'duration': 195,
  119. 'upload_date': '20120212',
  120. 'timestamp': 1329049880,
  121. 'uploader_id': '-77521',
  122. },
  123. },
  124. {
  125. # VIDEO NOW REMOVED
  126. # please update if you find a video whose URL follows the same pattern
  127. 'url': 'http://vk.com/video-8871596_164049491',
  128. 'md5': 'a590bcaf3d543576c9bd162812387666',
  129. 'note': 'Only available for registered users',
  130. 'info_dict': {
  131. 'id': '-8871596_164049491',
  132. 'ext': 'mp4',
  133. 'uploader': 'Триллеры',
  134. 'title': '► Бойцовский клуб / Fight Club 1999 [HD 720]',
  135. 'duration': 8352,
  136. 'upload_date': '20121218',
  137. 'view_count': int,
  138. },
  139. 'skip': 'Removed',
  140. },
  141. {
  142. 'url': 'http://vk.com/hd_kino_mania?z=video-43215063_168067957%2F15c66b9b533119788d',
  143. 'info_dict': {
  144. 'id': '-43215063_168067957',
  145. 'ext': 'mp4',
  146. 'uploader': 'Bro Mazter',
  147. 'title': ' ',
  148. 'duration': 7291,
  149. 'upload_date': '20140328',
  150. 'uploader_id': '223413403',
  151. 'timestamp': 1396018030,
  152. },
  153. 'skip': 'Requires vk account credentials',
  154. },
  155. {
  156. 'url': 'http://m.vk.com/video-43215063_169084319?list=125c627d1aa1cebb83&from=wall-43215063_2566540',
  157. 'md5': '0c45586baa71b7cb1d0784ee3f4e00a6',
  158. 'note': 'ivi.ru embed',
  159. 'info_dict': {
  160. 'id': '-43215063_169084319',
  161. 'ext': 'mp4',
  162. 'title': 'Книга Илая',
  163. 'duration': 6771,
  164. 'upload_date': '20140626',
  165. 'view_count': int,
  166. },
  167. 'skip': 'Removed',
  168. },
  169. {
  170. # video (removed?) only available with list id
  171. 'url': 'https://vk.com/video30481095_171201961?list=8764ae2d21f14088d4',
  172. 'md5': '091287af5402239a1051c37ec7b92913',
  173. 'info_dict': {
  174. 'id': '30481095_171201961',
  175. 'ext': 'mp4',
  176. 'title': 'ТюменцевВВ_09.07.2015',
  177. 'uploader': 'Anton Ivanov',
  178. 'duration': 109,
  179. 'upload_date': '20150709',
  180. 'view_count': int,
  181. },
  182. 'skip': 'Removed',
  183. },
  184. {
  185. # youtube embed
  186. 'url': 'https://vk.com/video276849682_170681728',
  187. 'info_dict': {
  188. 'id': 'V3K4mi0SYkc',
  189. 'ext': 'mp4',
  190. 'title': "DSWD Awards 'Children's Joy Foundation, Inc.' Certificate of Registration and License to Operate",
  191. 'description': 'md5:bf9c26cfa4acdfb146362682edd3827a',
  192. 'duration': 178,
  193. 'upload_date': '20130116',
  194. 'uploader': "Children's Joy Foundation Inc.",
  195. 'uploader_id': 'thecjf',
  196. 'view_count': int,
  197. },
  198. },
  199. {
  200. # dailymotion embed
  201. 'url': 'https://vk.com/video-37468416_456239855',
  202. 'info_dict': {
  203. 'id': 'k3lz2cmXyRuJQSjGHUv',
  204. 'ext': 'mp4',
  205. 'title': 'md5:d52606645c20b0ddbb21655adaa4f56f',
  206. 'description': 'md5:424b8e88cc873217f520e582ba28bb36',
  207. 'uploader': 'AniLibria.Tv',
  208. 'upload_date': '20160914',
  209. 'uploader_id': 'x1p5vl5',
  210. 'timestamp': 1473877246,
  211. },
  212. 'params': {
  213. 'skip_download': True,
  214. },
  215. },
  216. {
  217. # video key is extra_data not url\d+
  218. 'url': 'http://vk.com/video-110305615_171782105',
  219. 'md5': 'e13fcda136f99764872e739d13fac1d1',
  220. 'info_dict': {
  221. 'id': '-110305615_171782105',
  222. 'ext': 'mp4',
  223. 'title': 'S-Dance, репетиции к The way show',
  224. 'uploader': 'THE WAY SHOW | 17 апреля',
  225. 'uploader_id': '-110305615',
  226. 'timestamp': 1454859345,
  227. 'upload_date': '20160207',
  228. },
  229. 'params': {
  230. 'skip_download': True,
  231. },
  232. },
  233. {
  234. # finished live stream, postlive_mp4
  235. 'url': 'https://vk.com/videos-387766?z=video-387766_456242764%2Fpl_-387766_-2',
  236. 'info_dict': {
  237. 'id': '-387766_456242764',
  238. 'ext': 'mp4',
  239. 'title': 'ИгроМир 2016 День 1 — Игромания Утром',
  240. 'uploader': 'Игромания',
  241. 'duration': 5239,
  242. # TODO: use act=show to extract view_count
  243. # 'view_count': int,
  244. 'upload_date': '20160929',
  245. 'uploader_id': '-387766',
  246. 'timestamp': 1475137527,
  247. },
  248. 'params': {
  249. 'skip_download': True,
  250. },
  251. },
  252. {
  253. # live stream, hls and rtmp links, most likely already finished live
  254. # stream by the time you are reading this comment
  255. 'url': 'https://vk.com/video-140332_456239111',
  256. 'only_matching': True,
  257. },
  258. {
  259. # removed video, just testing that we match the pattern
  260. 'url': 'http://vk.com/feed?z=video-43215063_166094326%2Fbb50cacd3177146d7a',
  261. 'only_matching': True,
  262. },
  263. {
  264. # age restricted video, requires vk account credentials
  265. 'url': 'https://vk.com/video205387401_164765225',
  266. 'only_matching': True,
  267. },
  268. {
  269. # pladform embed
  270. 'url': 'https://vk.com/video-76116461_171554880',
  271. 'only_matching': True,
  272. },
  273. {
  274. 'url': 'http://new.vk.com/video205387401_165548505',
  275. 'only_matching': True,
  276. },
  277. {
  278. # This video is no longer available, because its author has been blocked.
  279. 'url': 'https://vk.com/video-10639516_456240611',
  280. 'only_matching': True,
  281. },
  282. {
  283. # The video is not available in your region.
  284. 'url': 'https://vk.com/video-51812607_171445436',
  285. 'only_matching': True,
  286. }]
  287. @staticmethod
  288. def _extract_sibnet_urls(webpage):
  289. # https://help.sibnet.ru/?sibnet_video_embed
  290. return [unescapeHTML(mobj.group('url')) for mobj in re.finditer(
  291. r'<iframe\b[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//video\.sibnet\.ru/shell\.php\?.*?\bvideoid=\d+.*?)\1',
  292. webpage)]
  293. def _real_extract(self, url):
  294. mobj = re.match(self._VALID_URL, url)
  295. video_id = mobj.group('videoid')
  296. mv_data = {}
  297. if video_id:
  298. data = {
  299. 'act': 'show_inline',
  300. 'video': video_id,
  301. }
  302. # Some videos (removed?) can only be downloaded with list id specified
  303. list_id = mobj.group('list_id')
  304. if list_id:
  305. data['list'] = list_id
  306. payload = self._download_payload('al_video', video_id, data)
  307. info_page = payload[1]
  308. opts = payload[-1]
  309. mv_data = opts.get('mvData') or {}
  310. player = opts.get('player') or {}
  311. else:
  312. video_id = '%s_%s' % (mobj.group('oid'), mobj.group('id'))
  313. info_page = self._download_webpage(
  314. 'http://vk.com/video_ext.php?' + mobj.group('embed_query'), video_id)
  315. error_message = self._html_search_regex(
  316. [r'(?s)<!><div[^>]+class="video_layer_message"[^>]*>(.+?)</div>',
  317. r'(?s)<div[^>]+id="video_ext_msg"[^>]*>(.+?)</div>'],
  318. info_page, 'error message', default=None)
  319. if error_message:
  320. raise ExtractorError(error_message, expected=True)
  321. if re.search(r'<!>/login\.php\?.*\bact=security_check', info_page):
  322. raise ExtractorError(
  323. 'You are trying to log in from an unusual location. You should confirm ownership at vk.com to log in with this IP.',
  324. expected=True)
  325. ERROR_COPYRIGHT = 'Video %s has been removed from public access due to rightholder complaint.'
  326. ERRORS = {
  327. r'>Видеозапись .*? была изъята из публичного доступа в связи с обращением правообладателя.<':
  328. ERROR_COPYRIGHT,
  329. r'>The video .*? was removed from public access by request of the copyright holder.<':
  330. ERROR_COPYRIGHT,
  331. r'<!>Please log in or <':
  332. 'Video %s is only available for registered users, '
  333. 'use --username and --password options to provide account credentials.',
  334. r'<!>Unknown error':
  335. 'Video %s does not exist.',
  336. r'<!>Видео временно недоступно':
  337. 'Video %s is temporarily unavailable.',
  338. r'<!>Access denied':
  339. 'Access denied to video %s.',
  340. r'<!>Видеозапись недоступна, так как её автор был заблокирован.':
  341. 'Video %s is no longer available, because its author has been blocked.',
  342. r'<!>This video is no longer available, because its author has been blocked.':
  343. 'Video %s is no longer available, because its author has been blocked.',
  344. r'<!>This video is no longer available, because it has been deleted.':
  345. 'Video %s is no longer available, because it has been deleted.',
  346. r'<!>The video .+? is not available in your region.':
  347. 'Video %s is not available in your region.',
  348. }
  349. for error_re, error_msg in ERRORS.items():
  350. if re.search(error_re, info_page):
  351. raise ExtractorError(error_msg % video_id, expected=True)
  352. player = self._parse_json(self._search_regex(
  353. r'var\s+playerParams\s*=\s*({.+?})\s*;\s*\n',
  354. info_page, 'player params'), video_id)
  355. youtube_url = YoutubeIE._extract_url(info_page)
  356. if youtube_url:
  357. return self.url_result(youtube_url, YoutubeIE.ie_key())
  358. vimeo_url = VimeoIE._extract_url(url, info_page)
  359. if vimeo_url is not None:
  360. return self.url_result(vimeo_url, VimeoIE.ie_key())
  361. pladform_url = PladformIE._extract_url(info_page)
  362. if pladform_url:
  363. return self.url_result(pladform_url, PladformIE.ie_key())
  364. m_rutube = re.search(
  365. r'\ssrc="((?:https?:)?//rutube\.ru\\?/(?:video|play)\\?/embed(?:.*?))\\?"', info_page)
  366. if m_rutube is not None:
  367. rutube_url = self._proto_relative_url(
  368. m_rutube.group(1).replace('\\', ''))
  369. return self.url_result(rutube_url)
  370. dailymotion_urls = DailymotionIE._extract_urls(info_page)
  371. if dailymotion_urls:
  372. return self.url_result(dailymotion_urls[0], DailymotionIE.ie_key())
  373. odnoklassniki_url = OdnoklassnikiIE._extract_url(info_page)
  374. if odnoklassniki_url:
  375. return self.url_result(odnoklassniki_url, OdnoklassnikiIE.ie_key())
  376. sibnet_urls = self._extract_sibnet_urls(info_page)
  377. if sibnet_urls:
  378. return self.url_result(sibnet_urls[0])
  379. m_opts = re.search(r'(?s)var\s+opts\s*=\s*({.+?});', info_page)
  380. if m_opts:
  381. m_opts_url = re.search(r"url\s*:\s*'((?!/\b)[^']+)", m_opts.group(1))
  382. if m_opts_url:
  383. opts_url = m_opts_url.group(1)
  384. if opts_url.startswith('//'):
  385. opts_url = 'http:' + opts_url
  386. return self.url_result(opts_url)
  387. data = player['params'][0]
  388. title = unescapeHTML(data['md_title'])
  389. # 2 = live
  390. # 3 = post live (finished live)
  391. is_live = data.get('live') == 2
  392. if is_live:
  393. title = self._live_title(title)
  394. timestamp = unified_timestamp(self._html_search_regex(
  395. r'class=["\']mv_info_date[^>]+>([^<]+)(?:<|from)', info_page,
  396. 'upload date', default=None)) or int_or_none(data.get('date'))
  397. view_count = str_to_int(self._search_regex(
  398. r'class=["\']mv_views_count[^>]+>\s*([\d,.]+)',
  399. info_page, 'view count', default=None))
  400. formats = []
  401. for format_id, format_url in data.items():
  402. format_url = url_or_none(format_url)
  403. if not format_url or not format_url.startswith(('http', '//', 'rtmp')):
  404. continue
  405. if (format_id.startswith(('url', 'cache'))
  406. or format_id in ('extra_data', 'live_mp4', 'postlive_mp4')):
  407. height = int_or_none(self._search_regex(
  408. r'^(?:url|cache)(\d+)', format_id, 'height', default=None))
  409. formats.append({
  410. 'format_id': format_id,
  411. 'url': format_url,
  412. 'height': height,
  413. })
  414. elif format_id == 'hls':
  415. formats.extend(self._extract_m3u8_formats(
  416. format_url, video_id, 'mp4', 'm3u8_native',
  417. m3u8_id=format_id, fatal=False, live=is_live))
  418. elif format_id == 'rtmp':
  419. formats.append({
  420. 'format_id': format_id,
  421. 'url': format_url,
  422. 'ext': 'flv',
  423. })
  424. self._sort_formats(formats)
  425. return {
  426. 'id': video_id,
  427. 'formats': formats,
  428. 'title': title,
  429. 'thumbnail': data.get('jpg'),
  430. 'uploader': data.get('md_author'),
  431. 'uploader_id': str_or_none(data.get('author_id') or mv_data.get('authorId')),
  432. 'duration': int_or_none(data.get('duration') or mv_data.get('duration')),
  433. 'timestamp': timestamp,
  434. 'view_count': view_count,
  435. 'like_count': int_or_none(mv_data.get('likes')),
  436. 'comment_count': int_or_none(mv_data.get('commcount')),
  437. 'is_live': is_live,
  438. }
  439. class VKUserVideosIE(VKBaseIE):
  440. IE_NAME = 'vk:uservideos'
  441. IE_DESC = "VK - User's Videos"
  442. _VALID_URL = r'https?://(?:(?:m|new)\.)?vk\.com/videos(?P<id>-?[0-9]+)(?!\?.*\bz=video)(?:[/?#&](?:.*?\bsection=(?P<section>\w+))?|$)'
  443. _TEMPLATE_URL = 'https://vk.com/videos'
  444. _TESTS = [{
  445. 'url': 'https://vk.com/videos-767561',
  446. 'info_dict': {
  447. 'id': '-767561_all',
  448. },
  449. 'playlist_mincount': 1150,
  450. }, {
  451. 'url': 'https://vk.com/videos-767561?section=uploaded',
  452. 'info_dict': {
  453. 'id': '-767561_uploaded',
  454. },
  455. 'playlist_mincount': 425,
  456. }, {
  457. 'url': 'http://vk.com/videos205387401',
  458. 'only_matching': True,
  459. }, {
  460. 'url': 'http://vk.com/videos-77521',
  461. 'only_matching': True,
  462. }, {
  463. 'url': 'http://vk.com/videos-97664626?section=all',
  464. 'only_matching': True,
  465. }, {
  466. 'url': 'http://m.vk.com/videos205387401',
  467. 'only_matching': True,
  468. }, {
  469. 'url': 'http://new.vk.com/videos205387401',
  470. 'only_matching': True,
  471. }]
  472. _PAGE_SIZE = 1000
  473. _VIDEO = collections.namedtuple('Video', ['owner_id', 'id'])
  474. def _fetch_page(self, page_id, section, page):
  475. l = self._download_payload('al_video', page_id, {
  476. 'act': 'load_videos_silent',
  477. 'offset': page * self._PAGE_SIZE,
  478. 'oid': page_id,
  479. 'section': section,
  480. })[0][section]['list']
  481. for video in l:
  482. v = self._VIDEO._make(video[:2])
  483. video_id = '%d_%d' % (v.owner_id, v.id)
  484. yield self.url_result(
  485. 'http://vk.com/video' + video_id, VKIE.ie_key(), video_id)
  486. def _real_extract(self, url):
  487. page_id, section = re.match(self._VALID_URL, url).groups()
  488. if not section:
  489. section = 'all'
  490. entries = OnDemandPagedList(
  491. functools.partial(self._fetch_page, page_id, section),
  492. self._PAGE_SIZE)
  493. return self.playlist_result(entries, '%s_%s' % (page_id, section))
  494. class VKWallPostIE(VKBaseIE):
  495. IE_NAME = 'vk:wallpost'
  496. _VALID_URL = r'https?://(?:(?:(?:(?:m|new)\.)?vk\.com/(?:[^?]+\?.*\bw=)?wall(?P<id>-?\d+_\d+)))'
  497. _TESTS = [{
  498. # public page URL, audio playlist
  499. 'url': 'https://vk.com/bs.official?w=wall-23538238_35',
  500. 'info_dict': {
  501. 'id': '-23538238_35',
  502. 'title': 'Black Shadow - Wall post -23538238_35',
  503. 'description': 'md5:3f84b9c4f9ef499731cf1ced9998cc0c',
  504. },
  505. 'playlist': [{
  506. 'md5': '5ba93864ec5b85f7ce19a9af4af080f6',
  507. 'info_dict': {
  508. 'id': '135220665_111806521',
  509. 'ext': 'mp4',
  510. 'title': 'Black Shadow - Слепое Верование',
  511. 'duration': 370,
  512. 'uploader': 'Black Shadow',
  513. 'artist': 'Black Shadow',
  514. 'track': 'Слепое Верование',
  515. },
  516. }, {
  517. 'md5': '4cc7e804579122b17ea95af7834c9233',
  518. 'info_dict': {
  519. 'id': '135220665_111802303',
  520. 'ext': 'mp4',
  521. 'title': 'Black Shadow - Война - Негасимое Бездны Пламя!',
  522. 'duration': 423,
  523. 'uploader': 'Black Shadow',
  524. 'artist': 'Black Shadow',
  525. 'track': 'Война - Негасимое Бездны Пламя!',
  526. },
  527. }],
  528. 'params': {
  529. 'skip_download': True,
  530. 'usenetrc': True,
  531. },
  532. 'skip': 'Requires vk account credentials',
  533. }, {
  534. # single YouTube embed, no leading -
  535. 'url': 'https://vk.com/wall85155021_6319',
  536. 'info_dict': {
  537. 'id': '85155021_6319',
  538. 'title': 'Сергей Горбунов - Wall post 85155021_6319',
  539. },
  540. 'playlist_count': 1,
  541. 'params': {
  542. 'usenetrc': True,
  543. },
  544. 'skip': 'Requires vk account credentials',
  545. }, {
  546. # wall page URL
  547. 'url': 'https://vk.com/wall-23538238_35',
  548. 'only_matching': True,
  549. }, {
  550. # mobile wall page URL
  551. 'url': 'https://m.vk.com/wall-23538238_35',
  552. 'only_matching': True,
  553. }]
  554. _BASE64_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN0PQRSTUVWXYZO123456789+/='
  555. _AUDIO = collections.namedtuple('Audio', ['id', 'owner_id', 'url', 'title', 'performer', 'duration', 'album_id', 'unk', 'author_link', 'lyrics', 'flags', 'context', 'extra', 'hashes', 'cover_url', 'ads'])
  556. def _decode(self, enc):
  557. dec = ''
  558. e = n = 0
  559. for c in enc:
  560. r = self._BASE64_CHARS.index(c)
  561. cond = n % 4
  562. e = 64 * e + r if cond else r
  563. n += 1
  564. if cond:
  565. dec += chr(255 & e >> (-2 * n & 6))
  566. return dec
  567. def _unmask_url(self, mask_url, vk_id):
  568. if 'audio_api_unavailable' in mask_url:
  569. extra = mask_url.split('?extra=')[1].split('#')
  570. func, base = self._decode(extra[1]).split(chr(11))
  571. mask_url = list(self._decode(extra[0]))
  572. url_len = len(mask_url)
  573. indexes = [None] * url_len
  574. index = int(base) ^ vk_id
  575. for n in range(url_len - 1, -1, -1):
  576. index = (url_len * (n + 1) ^ index + n) % url_len
  577. indexes[n] = index
  578. for n in range(1, url_len):
  579. c = mask_url[n]
  580. index = indexes[url_len - 1 - n]
  581. mask_url[n] = mask_url[index]
  582. mask_url[index] = c
  583. mask_url = ''.join(mask_url)
  584. return mask_url
  585. def _real_extract(self, url):
  586. post_id = self._match_id(url)
  587. webpage = self._download_payload('wkview', post_id, {
  588. 'act': 'show',
  589. 'w': 'wall' + post_id,
  590. })[1]
  591. description = clean_html(get_element_by_class('wall_post_text', webpage))
  592. uploader = clean_html(get_element_by_class('author', webpage))
  593. entries = []
  594. for audio in re.findall(r'data-audio="([^"]+)', webpage):
  595. audio = self._parse_json(unescapeHTML(audio), post_id)
  596. a = self._AUDIO._make(audio[:16])
  597. if not a.url:
  598. continue
  599. title = unescapeHTML(a.title)
  600. performer = unescapeHTML(a.performer)
  601. entries.append({
  602. 'id': '%s_%s' % (a.owner_id, a.id),
  603. 'url': self._unmask_url(a.url, a.ads['vk_id']),
  604. 'title': '%s - %s' % (performer, title) if performer else title,
  605. 'thumbnails': [{'url': c_url} for c_url in a.cover_url.split(',')] if a.cover_url else None,
  606. 'duration': int_or_none(a.duration),
  607. 'uploader': uploader,
  608. 'artist': performer,
  609. 'track': title,
  610. 'ext': 'mp4',
  611. 'protocol': 'm3u8',
  612. })
  613. for video in re.finditer(
  614. r'<a[^>]+href=(["\'])(?P<url>/video(?:-?[\d_]+).*?)\1', webpage):
  615. entries.append(self.url_result(
  616. compat_urlparse.urljoin(url, video.group('url')), VKIE.ie_key()))
  617. title = 'Wall post %s' % post_id
  618. return self.playlist_result(
  619. orderedSet(entries), post_id,
  620. '%s - %s' % (uploader, title) if uploader else title,
  621. description)