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.

630 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. ERROR_COPYRIGHT = 'Video %s has been removed from public access due to rightholder complaint.'
  302. ERRORS = {
  303. r'>Видеозапись .*? была изъята из публичного доступа в связи с обращением правообладателя.<':
  304. ERROR_COPYRIGHT,
  305. r'>The video .*? was removed from public access by request of the copyright holder.<':
  306. ERROR_COPYRIGHT,
  307. r'<!>Please log in or <':
  308. 'Video %s is only available for registered users, '
  309. 'use --username and --password options to provide account credentials.',
  310. r'<!>Unknown error':
  311. 'Video %s does not exist.',
  312. r'<!>Видео временно недоступно':
  313. 'Video %s is temporarily unavailable.',
  314. r'<!>Access denied':
  315. 'Access denied to video %s.',
  316. r'<!>Видеозапись недоступна, так как её автор был заблокирован.':
  317. 'Video %s is no longer available, because its author has been blocked.',
  318. r'<!>This video is no longer available, because its author has been blocked.':
  319. 'Video %s is no longer available, because its author has been blocked.',
  320. }
  321. for error_re, error_msg in ERRORS.items():
  322. if re.search(error_re, info_page):
  323. raise ExtractorError(error_msg % video_id, expected=True)
  324. youtube_url = YoutubeIE._extract_url(info_page)
  325. if youtube_url:
  326. return self.url_result(youtube_url, ie=YoutubeIE.ie_key())
  327. vimeo_url = VimeoIE._extract_url(url, info_page)
  328. if vimeo_url is not None:
  329. return self.url_result(vimeo_url)
  330. pladform_url = PladformIE._extract_url(info_page)
  331. if pladform_url:
  332. return self.url_result(pladform_url)
  333. m_rutube = re.search(
  334. r'\ssrc="((?:https?:)?//rutube\.ru\\?/(?:video|play)\\?/embed(?:.*?))\\?"', info_page)
  335. if m_rutube is not None:
  336. rutube_url = self._proto_relative_url(
  337. m_rutube.group(1).replace('\\', ''))
  338. return self.url_result(rutube_url)
  339. dailymotion_urls = DailymotionIE._extract_urls(info_page)
  340. if dailymotion_urls:
  341. return self.url_result(dailymotion_urls[0], DailymotionIE.ie_key())
  342. m_opts = re.search(r'(?s)var\s+opts\s*=\s*({.+?});', info_page)
  343. if m_opts:
  344. m_opts_url = re.search(r"url\s*:\s*'((?!/\b)[^']+)", m_opts.group(1))
  345. if m_opts_url:
  346. opts_url = m_opts_url.group(1)
  347. if opts_url.startswith('//'):
  348. opts_url = 'http:' + opts_url
  349. return self.url_result(opts_url)
  350. # vars does not look to be served anymore since 24.10.2016
  351. data = self._parse_json(
  352. self._search_regex(
  353. r'var\s+vars\s*=\s*({.+?});', info_page, 'vars', default='{}'),
  354. video_id, fatal=False)
  355. # <!json> is served instead
  356. if not data:
  357. data = self._parse_json(
  358. self._search_regex(
  359. r'<!json>\s*({.+?})\s*<!>', info_page, 'json', default='{}'),
  360. video_id)
  361. if data:
  362. data = data['player']['params'][0]
  363. if not data:
  364. data = self._parse_json(
  365. self._search_regex(
  366. r'var\s+playerParams\s*=\s*({.+?})\s*;\s*\n', info_page,
  367. 'player params'),
  368. video_id)['params'][0]
  369. title = unescapeHTML(data['md_title'])
  370. # 2 = live
  371. # 3 = post live (finished live)
  372. is_live = data.get('live') == 2
  373. if is_live:
  374. title = self._live_title(title)
  375. timestamp = unified_timestamp(self._html_search_regex(
  376. r'class=["\']mv_info_date[^>]+>([^<]+)(?:<|from)', info_page,
  377. 'upload date', fatal=False))
  378. view_count = str_to_int(self._search_regex(
  379. r'class=["\']mv_views_count[^>]+>\s*([\d,.]+)',
  380. info_page, 'view count', default=None))
  381. formats = []
  382. for format_id, format_url in data.items():
  383. if not isinstance(format_url, compat_str) or not format_url.startswith(('http', '//', 'rtmp')):
  384. continue
  385. if (format_id.startswith(('url', 'cache')) or
  386. format_id in ('extra_data', 'live_mp4', 'postlive_mp4')):
  387. height = int_or_none(self._search_regex(
  388. r'^(?:url|cache)(\d+)', format_id, 'height', default=None))
  389. formats.append({
  390. 'format_id': format_id,
  391. 'url': format_url,
  392. 'height': height,
  393. })
  394. elif format_id == 'hls':
  395. formats.extend(self._extract_m3u8_formats(
  396. format_url, video_id, 'mp4', 'm3u8_native',
  397. m3u8_id=format_id, fatal=False, live=is_live))
  398. elif format_id == 'rtmp':
  399. formats.append({
  400. 'format_id': format_id,
  401. 'url': format_url,
  402. 'ext': 'flv',
  403. })
  404. self._sort_formats(formats)
  405. return {
  406. 'id': compat_str(data.get('vid') or video_id),
  407. 'formats': formats,
  408. 'title': title,
  409. 'thumbnail': data.get('jpg'),
  410. 'uploader': data.get('md_author'),
  411. 'duration': data.get('duration'),
  412. 'timestamp': timestamp,
  413. 'view_count': view_count,
  414. 'is_live': is_live,
  415. }
  416. class VKUserVideosIE(VKBaseIE):
  417. IE_NAME = 'vk:uservideos'
  418. IE_DESC = "VK - User's Videos"
  419. _VALID_URL = r'https?://(?:(?:m|new)\.)?vk\.com/videos(?P<id>-?[0-9]+)(?!\?.*\bz=video)(?:[/?#&]|$)'
  420. _TEMPLATE_URL = 'https://vk.com/videos'
  421. _TESTS = [{
  422. 'url': 'http://vk.com/videos205387401',
  423. 'info_dict': {
  424. 'id': '205387401',
  425. 'title': "Tom Cruise's Videos",
  426. },
  427. 'playlist_mincount': 4,
  428. }, {
  429. 'url': 'http://vk.com/videos-77521',
  430. 'only_matching': True,
  431. }, {
  432. 'url': 'http://vk.com/videos-97664626?section=all',
  433. 'only_matching': True,
  434. }, {
  435. 'url': 'http://m.vk.com/videos205387401',
  436. 'only_matching': True,
  437. }, {
  438. 'url': 'http://new.vk.com/videos205387401',
  439. 'only_matching': True,
  440. }]
  441. def _real_extract(self, url):
  442. page_id = self._match_id(url)
  443. webpage = self._download_webpage(url, page_id)
  444. entries = [
  445. self.url_result(
  446. 'http://vk.com/video' + video_id, 'VK', video_id=video_id)
  447. for video_id in orderedSet(re.findall(r'href="/video(-?[0-9_]+)"', webpage))]
  448. title = unescapeHTML(self._search_regex(
  449. r'<title>\s*([^<]+?)\s+\|\s+\d+\s+videos',
  450. webpage, 'title', default=page_id))
  451. return self.playlist_result(entries, page_id, title)
  452. class VKWallPostIE(VKBaseIE):
  453. IE_NAME = 'vk:wallpost'
  454. _VALID_URL = r'https?://(?:(?:(?:(?:m|new)\.)?vk\.com/(?:[^?]+\?.*\bw=)?wall(?P<id>-?\d+_\d+)))'
  455. _TESTS = [{
  456. # public page URL, audio playlist
  457. 'url': 'https://vk.com/bs.official?w=wall-23538238_35',
  458. 'info_dict': {
  459. 'id': '23538238_35',
  460. 'title': 'Black Shadow - Wall post 23538238_35',
  461. 'description': 'md5:3f84b9c4f9ef499731cf1ced9998cc0c',
  462. },
  463. 'playlist': [{
  464. 'md5': '5ba93864ec5b85f7ce19a9af4af080f6',
  465. 'info_dict': {
  466. 'id': '135220665_111806521',
  467. 'ext': 'mp3',
  468. 'title': 'Black Shadow - Слепое Верование',
  469. 'duration': 370,
  470. 'uploader': 'Black Shadow',
  471. 'artist': 'Black Shadow',
  472. 'track': 'Слепое Верование',
  473. },
  474. }, {
  475. 'md5': '4cc7e804579122b17ea95af7834c9233',
  476. 'info_dict': {
  477. 'id': '135220665_111802303',
  478. 'ext': 'mp3',
  479. 'title': 'Black Shadow - Война - Негасимое Бездны Пламя!',
  480. 'duration': 423,
  481. 'uploader': 'Black Shadow',
  482. 'artist': 'Black Shadow',
  483. 'track': 'Война - Негасимое Бездны Пламя!',
  484. },
  485. 'params': {
  486. 'skip_download': True,
  487. },
  488. }],
  489. 'params': {
  490. 'usenetrc': True,
  491. },
  492. 'skip': 'Requires vk account credentials',
  493. }, {
  494. # single YouTube embed, no leading -
  495. 'url': 'https://vk.com/wall85155021_6319',
  496. 'info_dict': {
  497. 'id': '85155021_6319',
  498. 'title': 'Sergey Gorbunov - Wall post 85155021_6319',
  499. },
  500. 'playlist_count': 1,
  501. 'params': {
  502. 'usenetrc': True,
  503. },
  504. 'skip': 'Requires vk account credentials',
  505. }, {
  506. # wall page URL
  507. 'url': 'https://vk.com/wall-23538238_35',
  508. 'only_matching': True,
  509. }, {
  510. # mobile wall page URL
  511. 'url': 'https://m.vk.com/wall-23538238_35',
  512. 'only_matching': True,
  513. }]
  514. def _real_extract(self, url):
  515. post_id = self._match_id(url)
  516. wall_url = 'https://vk.com/wall%s' % post_id
  517. post_id = remove_start(post_id, '-')
  518. webpage = self._download_webpage(wall_url, post_id)
  519. error = self._html_search_regex(
  520. r'>Error</div>\s*<div[^>]+class=["\']body["\'][^>]*>([^<]+)',
  521. webpage, 'error', default=None)
  522. if error:
  523. raise ExtractorError('VK said: %s' % error, expected=True)
  524. description = clean_html(get_element_by_class('wall_post_text', webpage))
  525. uploader = clean_html(get_element_by_class('author', webpage))
  526. thumbnail = self._og_search_thumbnail(webpage)
  527. entries = []
  528. audio_ids = re.findall(r'data-full-id=["\'](\d+_\d+)', webpage)
  529. if audio_ids:
  530. al_audio = self._download_webpage(
  531. 'https://vk.com/al_audio.php', post_id,
  532. note='Downloading audio info', fatal=False,
  533. data=urlencode_postdata({
  534. 'act': 'reload_audio',
  535. 'al': '1',
  536. 'ids': ','.join(audio_ids)
  537. }))
  538. if al_audio:
  539. Audio = collections.namedtuple(
  540. 'Audio', ['id', 'user_id', 'url', 'track', 'artist', 'duration'])
  541. audios = self._parse_json(
  542. self._search_regex(
  543. r'<!json>(.+?)<!>', al_audio, 'audios', default='[]'),
  544. post_id, fatal=False, transform_source=unescapeHTML)
  545. if isinstance(audios, list):
  546. for audio in audios:
  547. a = Audio._make(audio[:6])
  548. entries.append({
  549. 'id': '%s_%s' % (a.user_id, a.id),
  550. 'url': a.url,
  551. 'title': '%s - %s' % (a.artist, a.track) if a.artist and a.track else a.id,
  552. 'thumbnail': thumbnail,
  553. 'duration': a.duration,
  554. 'uploader': uploader,
  555. 'artist': a.artist,
  556. 'track': a.track,
  557. })
  558. for video in re.finditer(
  559. r'<a[^>]+href=(["\'])(?P<url>/video(?:-?[\d_]+).*?)\1', webpage):
  560. entries.append(self.url_result(
  561. compat_urlparse.urljoin(url, video.group('url')), VKIE.ie_key()))
  562. title = 'Wall post %s' % post_id
  563. return self.playlist_result(
  564. orderedSet(entries), post_id,
  565. '%s - %s' % (uploader, title) if uploader else title,
  566. description)