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.

625 lines
23 KiB

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