vk.py 25 KB

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