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.

526 lines
19 KiB

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