You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

538 lines
20 KiB

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