vk.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import json
  5. import sys
  6. from .common import InfoExtractor
  7. from ..compat import (
  8. compat_str,
  9. compat_urlparse,
  10. )
  11. from ..utils import (
  12. clean_html,
  13. ExtractorError,
  14. get_element_by_class,
  15. int_or_none,
  16. orderedSet,
  17. parse_duration,
  18. remove_start,
  19. str_to_int,
  20. unescapeHTML,
  21. unified_strdate,
  22. urlencode_postdata,
  23. )
  24. from .vimeo import VimeoIE
  25. from .pladform import PladformIE
  26. class VKBaseIE(InfoExtractor):
  27. _NETRC_MACHINE = 'vk'
  28. def _login(self):
  29. (username, password) = self._get_login_info()
  30. if username is None:
  31. return
  32. login_page, url_handle = self._download_webpage_handle(
  33. 'https://vk.com', None, 'Downloading login page')
  34. login_form = self._hidden_inputs(login_page)
  35. login_form.update({
  36. 'email': username.encode('cp1251'),
  37. 'pass': password.encode('cp1251'),
  38. })
  39. # https://new.vk.com/ serves two same remixlhk cookies in Set-Cookie header
  40. # and expects the first one to be set rather than second (see
  41. # https://github.com/rg3/youtube-dl/issues/9841#issuecomment-227871201).
  42. # As of RFC6265 the newer one cookie should be set into cookie store
  43. # what actually happens.
  44. # We will workaround this VK issue by resetting the remixlhk cookie to
  45. # the first one manually.
  46. cookies = url_handle.headers.get('Set-Cookie')
  47. if sys.version_info[0] >= 3:
  48. cookies = cookies.encode('iso-8859-1')
  49. cookies = cookies.decode('utf-8')
  50. remixlhk = re.search(r'remixlhk=(.+?);.*?\bdomain=(.+?)(?:[,;]|$)', cookies)
  51. if remixlhk:
  52. value, domain = remixlhk.groups()
  53. self._set_cookie(domain, 'remixlhk', value)
  54. login_page = self._download_webpage(
  55. 'https://login.vk.com/?act=login', None,
  56. note='Logging in as %s' % username,
  57. data=urlencode_postdata(login_form))
  58. if re.search(r'onLoginFailed', login_page):
  59. raise ExtractorError(
  60. 'Unable to login, incorrect username and/or password', expected=True)
  61. def _real_initialize(self):
  62. self._login()
  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': '0deae91935c54e00003c2a00646315f0',
  85. 'info_dict': {
  86. 'id': '162222515',
  87. 'ext': 'flv',
  88. 'title': 'ProtivoGunz - Хуёвая песня',
  89. 'uploader': 're:(?:Noize MC|Alexander Ilyashenko).*',
  90. 'duration': 195,
  91. 'upload_date': '20120212',
  92. 'view_count': int,
  93. },
  94. },
  95. {
  96. 'url': 'http://vk.com/video205387401_165548505',
  97. 'md5': '6c0aeb2e90396ba97035b9cbde548700',
  98. 'info_dict': {
  99. 'id': '165548505',
  100. 'ext': 'mp4',
  101. 'uploader': 'Tom Cruise',
  102. 'title': 'No name',
  103. 'duration': 9,
  104. 'upload_date': '20130721',
  105. 'view_count': int,
  106. }
  107. },
  108. {
  109. 'note': 'Embedded video',
  110. 'url': 'http://vk.com/video_ext.php?oid=32194266&id=162925554&hash=7d8c2e0d5e05aeaa&hd=1',
  111. 'md5': 'c7ce8f1f87bec05b3de07fdeafe21a0a',
  112. 'info_dict': {
  113. 'id': '162925554',
  114. 'ext': 'mp4',
  115. 'uploader': 'Vladimir Gavrin',
  116. 'title': 'Lin Dan',
  117. 'duration': 101,
  118. 'upload_date': '20120730',
  119. 'view_count': int,
  120. },
  121. 'skip': 'This video has been removed from public access.',
  122. },
  123. {
  124. # VIDEO NOW REMOVED
  125. # please update if you find a video whose URL follows the same pattern
  126. 'url': 'http://vk.com/video-8871596_164049491',
  127. 'md5': 'a590bcaf3d543576c9bd162812387666',
  128. 'note': 'Only available for registered users',
  129. 'info_dict': {
  130. 'id': '164049491',
  131. 'ext': 'mp4',
  132. 'uploader': 'Триллеры',
  133. 'title': '► Бойцовский клуб / Fight Club 1999 [HD 720]',
  134. 'duration': 8352,
  135. 'upload_date': '20121218',
  136. 'view_count': int,
  137. },
  138. 'skip': 'Requires vk account credentials',
  139. },
  140. {
  141. 'url': 'http://vk.com/hd_kino_mania?z=video-43215063_168067957%2F15c66b9b533119788d',
  142. 'md5': '4d7a5ef8cf114dfa09577e57b2993202',
  143. 'info_dict': {
  144. 'id': '168067957',
  145. 'ext': 'mp4',
  146. 'uploader': 'Киномания - лучшее из мира кино',
  147. 'title': ' ',
  148. 'duration': 7291,
  149. 'upload_date': '20140328',
  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': '60690',
  159. 'ext': 'mp4',
  160. 'title': 'Книга Илая',
  161. 'duration': 6771,
  162. 'upload_date': '20140626',
  163. 'view_count': int,
  164. },
  165. 'skip': 'Only works from Russia',
  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': '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. },
  181. {
  182. # youtube embed
  183. 'url': 'https://vk.com/video276849682_170681728',
  184. 'info_dict': {
  185. 'id': 'V3K4mi0SYkc',
  186. 'ext': 'webm',
  187. 'title': "DSWD Awards 'Children's Joy Foundation, Inc.' Certificate of Registration and License to Operate",
  188. 'description': 'md5:d9903938abdc74c738af77f527ca0596',
  189. 'duration': 178,
  190. 'upload_date': '20130116',
  191. 'uploader': "Children's Joy Foundation",
  192. 'uploader_id': 'thecjf',
  193. 'view_count': int,
  194. },
  195. },
  196. {
  197. # video key is extra_data not url\d+
  198. 'url': 'http://vk.com/video-110305615_171782105',
  199. 'md5': 'e13fcda136f99764872e739d13fac1d1',
  200. 'info_dict': {
  201. 'id': '171782105',
  202. 'ext': 'mp4',
  203. 'title': 'S-Dance, репетиции к The way show',
  204. 'uploader': 'THE WAY SHOW | 17 апреля',
  205. 'upload_date': '20160207',
  206. 'view_count': int,
  207. },
  208. },
  209. {
  210. # removed video, just testing that we match the pattern
  211. 'url': 'http://vk.com/feed?z=video-43215063_166094326%2Fbb50cacd3177146d7a',
  212. 'only_matching': True,
  213. },
  214. {
  215. # age restricted video, requires vk account credentials
  216. 'url': 'https://vk.com/video205387401_164765225',
  217. 'only_matching': True,
  218. },
  219. {
  220. # pladform embed
  221. 'url': 'https://vk.com/video-76116461_171554880',
  222. 'only_matching': True,
  223. },
  224. {
  225. 'url': 'http://new.vk.com/video205387401_165548505',
  226. 'only_matching': True,
  227. }
  228. ]
  229. def _real_extract(self, url):
  230. mobj = re.match(self._VALID_URL, url)
  231. video_id = mobj.group('videoid')
  232. if video_id:
  233. info_url = 'https://vk.com/al_video.php?act=show&al=1&module=video&video=%s' % video_id
  234. # Some videos (removed?) can only be downloaded with list id specified
  235. list_id = mobj.group('list_id')
  236. if list_id:
  237. info_url += '&list=%s' % list_id
  238. else:
  239. info_url = 'http://vk.com/video_ext.php?' + mobj.group('embed_query')
  240. video_id = '%s_%s' % (mobj.group('oid'), mobj.group('id'))
  241. info_page = self._download_webpage(info_url, video_id)
  242. error_message = self._html_search_regex(
  243. [r'(?s)<!><div[^>]+class="video_layer_message"[^>]*>(.+?)</div>',
  244. r'(?s)<div[^>]+id="video_ext_msg"[^>]*>(.+?)</div>'],
  245. info_page, 'error message', default=None)
  246. if error_message:
  247. raise ExtractorError(error_message, expected=True)
  248. if re.search(r'<!>/login\.php\?.*\bact=security_check', info_page):
  249. raise ExtractorError(
  250. 'You are trying to log in from an unusual location. You should confirm ownership at vk.com to log in with this IP.',
  251. expected=True)
  252. ERRORS = {
  253. r'>Видеозапись .*? была изъята из публичного доступа в связи с обращением правообладателя.<':
  254. 'Video %s has been removed from public access due to rightholder complaint.',
  255. r'<!>Please log in or <':
  256. 'Video %s is only available for registered users, '
  257. 'use --username and --password options to provide account credentials.',
  258. r'<!>Unknown error':
  259. 'Video %s does not exist.',
  260. r'<!>Видео временно недоступно':
  261. 'Video %s is temporarily unavailable.',
  262. r'<!>Access denied':
  263. 'Access denied to video %s.',
  264. }
  265. for error_re, error_msg in ERRORS.items():
  266. if re.search(error_re, info_page):
  267. raise ExtractorError(error_msg % video_id, expected=True)
  268. youtube_url = self._search_regex(
  269. r'<iframe[^>]+src="((?:https?:)?//www.youtube.com/embed/[^"]+)"',
  270. info_page, 'youtube iframe', default=None)
  271. if youtube_url:
  272. return self.url_result(youtube_url, 'Youtube')
  273. vimeo_url = VimeoIE._extract_vimeo_url(url, info_page)
  274. if vimeo_url is not None:
  275. return self.url_result(vimeo_url)
  276. pladform_url = PladformIE._extract_url(info_page)
  277. if pladform_url:
  278. return self.url_result(pladform_url)
  279. m_rutube = re.search(
  280. r'\ssrc="((?:https?:)?//rutube\.ru\\?/(?:video|play)\\?/embed(?:.*?))\\?"', info_page)
  281. if m_rutube is not None:
  282. rutube_url = self._proto_relative_url(
  283. m_rutube.group(1).replace('\\', ''))
  284. return self.url_result(rutube_url)
  285. m_opts = re.search(r'(?s)var\s+opts\s*=\s*({.+?});', info_page)
  286. if m_opts:
  287. m_opts_url = re.search(r"url\s*:\s*'((?!/\b)[^']+)", m_opts.group(1))
  288. if m_opts_url:
  289. opts_url = m_opts_url.group(1)
  290. if opts_url.startswith('//'):
  291. opts_url = 'http:' + opts_url
  292. return self.url_result(opts_url)
  293. data_json = self._search_regex(r'var\s+vars\s*=\s*({.+?});', info_page, 'vars')
  294. data = json.loads(data_json)
  295. # Extract upload date
  296. upload_date = None
  297. mobj = re.search(r'id="mv_date(?:_views)?_wrap"[^>]*>([a-zA-Z]+ [0-9]+), ([0-9]+) at', info_page)
  298. if mobj is not None:
  299. mobj.group(1) + ' ' + mobj.group(2)
  300. upload_date = unified_strdate(mobj.group(1) + ' ' + mobj.group(2))
  301. view_count = None
  302. views = self._html_search_regex(
  303. r'"mv_views_count_number"[^>]*>(.+?\bviews?)<',
  304. info_page, 'view count', default=None)
  305. if views:
  306. view_count = str_to_int(self._search_regex(
  307. r'([\d,.]+)', views, 'view count', fatal=False))
  308. formats = []
  309. for k, v in data.items():
  310. if not k.startswith('url') and not k.startswith('cache') and k != 'extra_data' or not v:
  311. continue
  312. height = int_or_none(self._search_regex(
  313. r'^(?:url|cache)(\d+)', k, 'height', default=None))
  314. formats.append({
  315. 'format_id': k,
  316. 'url': v,
  317. 'height': height,
  318. })
  319. self._sort_formats(formats)
  320. return {
  321. 'id': compat_str(data['vid']),
  322. 'formats': formats,
  323. 'title': unescapeHTML(data['md_title']),
  324. 'thumbnail': data.get('jpg'),
  325. 'uploader': data.get('md_author'),
  326. 'duration': data.get('duration'),
  327. 'upload_date': upload_date,
  328. 'view_count': view_count,
  329. }
  330. class VKUserVideosIE(VKBaseIE):
  331. IE_NAME = 'vk:uservideos'
  332. IE_DESC = "VK - User's Videos"
  333. _VALID_URL = r'https?://(?:(?:m|new)\.)?vk\.com/videos(?P<id>-?[0-9]+)(?!\?.*\bz=video)(?:[/?#&]|$)'
  334. _TEMPLATE_URL = 'https://vk.com/videos'
  335. _TESTS = [{
  336. 'url': 'http://vk.com/videos205387401',
  337. 'info_dict': {
  338. 'id': '205387401',
  339. 'title': "Tom Cruise's Videos",
  340. },
  341. 'playlist_mincount': 4,
  342. }, {
  343. 'url': 'http://vk.com/videos-77521',
  344. 'only_matching': True,
  345. }, {
  346. 'url': 'http://vk.com/videos-97664626?section=all',
  347. 'only_matching': True,
  348. }, {
  349. 'url': 'http://m.vk.com/videos205387401',
  350. 'only_matching': True,
  351. }, {
  352. 'url': 'http://new.vk.com/videos205387401',
  353. 'only_matching': True,
  354. }]
  355. def _real_extract(self, url):
  356. page_id = self._match_id(url)
  357. webpage = self._download_webpage(url, page_id)
  358. entries = [
  359. self.url_result(
  360. 'http://vk.com/video' + video_id, 'VK', video_id=video_id)
  361. for video_id in orderedSet(re.findall(r'href="/video(-?[0-9_]+)"', webpage))]
  362. title = unescapeHTML(self._search_regex(
  363. r'<title>\s*([^<]+?)\s+\|\s+\d+\s+videos',
  364. webpage, 'title', default=page_id))
  365. return self.playlist_result(entries, page_id, title)
  366. class VKWallPostIE(VKBaseIE):
  367. IE_NAME = 'vk:wallpost'
  368. _VALID_URL = r'https?://(?:(?:(?:(?:m|new)\.)?vk\.com/(?:[^?]+\?.*\bw=)?wall(?P<id>-?\d+_\d+)))'
  369. _TESTS = [{
  370. # public page URL, audio playlist
  371. 'url': 'https://vk.com/bs.official?w=wall-23538238_35',
  372. 'info_dict': {
  373. 'id': '23538238_35',
  374. 'title': 'Black Shadow - Wall post 23538238_35',
  375. 'description': 'md5:3f84b9c4f9ef499731cf1ced9998cc0c',
  376. },
  377. 'playlist': [{
  378. 'md5': '5ba93864ec5b85f7ce19a9af4af080f6',
  379. 'info_dict': {
  380. 'id': '135220665_111806521',
  381. 'ext': 'mp3',
  382. 'title': 'Black Shadow - Слепое Верование',
  383. 'duration': 370,
  384. 'uploader': 'Black Shadow',
  385. 'artist': 'Black Shadow',
  386. 'track': 'Слепое Верование',
  387. },
  388. }, {
  389. 'md5': '4cc7e804579122b17ea95af7834c9233',
  390. 'info_dict': {
  391. 'id': '135220665_111802303',
  392. 'ext': 'mp3',
  393. 'title': 'Black Shadow - Война - Негасимое Бездны Пламя!',
  394. 'duration': 423,
  395. 'uploader': 'Black Shadow',
  396. 'artist': 'Black Shadow',
  397. 'track': 'Война - Негасимое Бездны Пламя!',
  398. },
  399. 'params': {
  400. 'skip_download': True,
  401. },
  402. }],
  403. 'skip': 'Requires vk account credentials',
  404. }, {
  405. # single YouTube embed, no leading -
  406. 'url': 'https://vk.com/wall85155021_6319',
  407. 'info_dict': {
  408. 'id': '85155021_6319',
  409. 'title': 'Sergey Gorbunov - Wall post 85155021_6319',
  410. },
  411. 'playlist_count': 1,
  412. 'skip': 'Requires vk account credentials',
  413. }, {
  414. # wall page URL
  415. 'url': 'https://vk.com/wall-23538238_35',
  416. 'only_matching': True,
  417. }, {
  418. # mobile wall page URL
  419. 'url': 'https://m.vk.com/wall-23538238_35',
  420. 'only_matching': True,
  421. }]
  422. def _real_extract(self, url):
  423. post_id = self._match_id(url)
  424. wall_url = 'https://vk.com/wall%s' % post_id
  425. post_id = remove_start(post_id, '-')
  426. webpage = self._download_webpage(wall_url, post_id)
  427. error = self._html_search_regex(
  428. r'>Error</div>\s*<div[^>]+class=["\']body["\'][^>]*>([^<]+)',
  429. webpage, 'error', default=None)
  430. if error:
  431. raise ExtractorError('VK said: %s' % error, expected=True)
  432. description = clean_html(get_element_by_class('wall_post_text', webpage))
  433. uploader = clean_html(get_element_by_class(
  434. 'fw_post_author', webpage)) or self._og_search_description(webpage)
  435. thumbnail = self._og_search_thumbnail(webpage)
  436. entries = []
  437. for audio in re.finditer(r'''(?sx)
  438. <input[^>]+
  439. id=(?P<q1>["\'])audio_info(?P<id>\d+_\d+).*?(?P=q1)[^>]+
  440. value=(?P<q2>["\'])(?P<url>http.+?)(?P=q2)
  441. .+?
  442. </table>''', webpage):
  443. audio_html = audio.group(0)
  444. audio_id = audio.group('id')
  445. duration = parse_duration(get_element_by_class('duration', audio_html))
  446. track = self._html_search_regex(
  447. r'<span[^>]+id=["\']title%s[^>]*>([^<]+)' % audio_id,
  448. audio_html, 'title', default=None)
  449. artist = self._html_search_regex(
  450. r'>([^<]+)</a></b>\s*&ndash', audio_html,
  451. 'artist', default=None)
  452. entries.append({
  453. 'id': audio_id,
  454. 'url': audio.group('url'),
  455. 'title': '%s - %s' % (artist, track) if artist and track else audio_id,
  456. 'thumbnail': thumbnail,
  457. 'duration': duration,
  458. 'uploader': uploader,
  459. 'artist': artist,
  460. 'track': track,
  461. })
  462. for video in re.finditer(
  463. r'<a[^>]+href=(["\'])(?P<url>/video(?:-?[\d_]+).*?)\1', webpage):
  464. entries.append(self.url_result(
  465. compat_urlparse.urljoin(url, video.group('url')), VKIE.ie_key()))
  466. title = 'Wall post %s' % post_id
  467. return self.playlist_result(
  468. orderedSet(entries), post_id,
  469. '%s - %s' % (uploader, title) if uploader else title,
  470. description)