vk.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 compat_str
  8. from ..utils import (
  9. ExtractorError,
  10. int_or_none,
  11. orderedSet,
  12. sanitized_Request,
  13. str_to_int,
  14. unescapeHTML,
  15. unified_strdate,
  16. urlencode_postdata,
  17. )
  18. from .vimeo import VimeoIE
  19. from .pladform import PladformIE
  20. class VKIE(InfoExtractor):
  21. IE_NAME = 'vk'
  22. IE_DESC = 'VK'
  23. _VALID_URL = r'''(?x)
  24. https?://
  25. (?:
  26. (?:
  27. (?:m\.)?vk\.com/video_|
  28. (?:www\.)?daxab.com/
  29. )
  30. ext\.php\?(?P<embed_query>.*?\boid=(?P<oid>-?\d+).*?\bid=(?P<id>\d+).*)|
  31. (?:
  32. (?:m\.)?vk\.com/(?:.+?\?.*?z=)?video|
  33. (?:www\.)?daxab.com/embed/
  34. )
  35. (?P<videoid>-?\d+_\d+)(?:.*\blist=(?P<list_id>[\da-f]+))?
  36. )
  37. '''
  38. _NETRC_MACHINE = 'vk'
  39. _TESTS = [
  40. {
  41. 'url': 'http://vk.com/videos-77521?z=video-77521_162222515%2Fclub77521',
  42. 'md5': '0deae91935c54e00003c2a00646315f0',
  43. 'info_dict': {
  44. 'id': '162222515',
  45. 'ext': 'flv',
  46. 'title': 'ProtivoGunz - Хуёвая песня',
  47. 'uploader': 're:(?:Noize MC|Alexander Ilyashenko).*',
  48. 'duration': 195,
  49. 'upload_date': '20120212',
  50. 'view_count': int,
  51. },
  52. },
  53. {
  54. 'url': 'http://vk.com/video205387401_165548505',
  55. 'md5': '6c0aeb2e90396ba97035b9cbde548700',
  56. 'info_dict': {
  57. 'id': '165548505',
  58. 'ext': 'mp4',
  59. 'uploader': 'Tom Cruise',
  60. 'title': 'No name',
  61. 'duration': 9,
  62. 'upload_date': '20130721',
  63. 'view_count': int,
  64. }
  65. },
  66. {
  67. 'note': 'Embedded video',
  68. 'url': 'http://vk.com/video_ext.php?oid=32194266&id=162925554&hash=7d8c2e0d5e05aeaa&hd=1',
  69. 'md5': 'c7ce8f1f87bec05b3de07fdeafe21a0a',
  70. 'info_dict': {
  71. 'id': '162925554',
  72. 'ext': 'mp4',
  73. 'uploader': 'Vladimir Gavrin',
  74. 'title': 'Lin Dan',
  75. 'duration': 101,
  76. 'upload_date': '20120730',
  77. 'view_count': int,
  78. },
  79. 'skip': 'This video has been removed from public access.',
  80. },
  81. {
  82. # VIDEO NOW REMOVED
  83. # please update if you find a video whose URL follows the same pattern
  84. 'url': 'http://vk.com/video-8871596_164049491',
  85. 'md5': 'a590bcaf3d543576c9bd162812387666',
  86. 'note': 'Only available for registered users',
  87. 'info_dict': {
  88. 'id': '164049491',
  89. 'ext': 'mp4',
  90. 'uploader': 'Триллеры',
  91. 'title': '► Бойцовский клуб / Fight Club 1999 [HD 720]',
  92. 'duration': 8352,
  93. 'upload_date': '20121218',
  94. 'view_count': int,
  95. },
  96. 'skip': 'Requires vk account credentials',
  97. },
  98. {
  99. 'url': 'http://vk.com/hd_kino_mania?z=video-43215063_168067957%2F15c66b9b533119788d',
  100. 'md5': '4d7a5ef8cf114dfa09577e57b2993202',
  101. 'info_dict': {
  102. 'id': '168067957',
  103. 'ext': 'mp4',
  104. 'uploader': 'Киномания - лучшее из мира кино',
  105. 'title': ' ',
  106. 'duration': 7291,
  107. 'upload_date': '20140328',
  108. },
  109. 'skip': 'Requires vk account credentials',
  110. },
  111. {
  112. 'url': 'http://m.vk.com/video-43215063_169084319?list=125c627d1aa1cebb83&from=wall-43215063_2566540',
  113. 'md5': '0c45586baa71b7cb1d0784ee3f4e00a6',
  114. 'note': 'ivi.ru embed',
  115. 'info_dict': {
  116. 'id': '60690',
  117. 'ext': 'mp4',
  118. 'title': 'Книга Илая',
  119. 'duration': 6771,
  120. 'upload_date': '20140626',
  121. 'view_count': int,
  122. },
  123. 'skip': 'Only works from Russia',
  124. },
  125. {
  126. # video (removed?) only available with list id
  127. 'url': 'https://vk.com/video30481095_171201961?list=8764ae2d21f14088d4',
  128. 'md5': '091287af5402239a1051c37ec7b92913',
  129. 'info_dict': {
  130. 'id': '171201961',
  131. 'ext': 'mp4',
  132. 'title': 'ТюменцевВВ_09.07.2015',
  133. 'uploader': 'Anton Ivanov',
  134. 'duration': 109,
  135. 'upload_date': '20150709',
  136. 'view_count': int,
  137. },
  138. },
  139. {
  140. # youtube embed
  141. 'url': 'https://vk.com/video276849682_170681728',
  142. 'info_dict': {
  143. 'id': 'V3K4mi0SYkc',
  144. 'ext': 'webm',
  145. 'title': "DSWD Awards 'Children's Joy Foundation, Inc.' Certificate of Registration and License to Operate",
  146. 'description': 'md5:d9903938abdc74c738af77f527ca0596',
  147. 'duration': 178,
  148. 'upload_date': '20130116',
  149. 'uploader': "Children's Joy Foundation",
  150. 'uploader_id': 'thecjf',
  151. 'view_count': int,
  152. },
  153. },
  154. {
  155. # video key is extra_data not url\d+
  156. 'url': 'http://vk.com/video-110305615_171782105',
  157. 'md5': 'e13fcda136f99764872e739d13fac1d1',
  158. 'info_dict': {
  159. 'id': '171782105',
  160. 'ext': 'mp4',
  161. 'title': 'S-Dance, репетиции к The way show',
  162. 'uploader': 'THE WAY SHOW | 17 апреля',
  163. 'upload_date': '20160207',
  164. 'view_count': int,
  165. },
  166. },
  167. {
  168. # removed video, just testing that we match the pattern
  169. 'url': 'http://vk.com/feed?z=video-43215063_166094326%2Fbb50cacd3177146d7a',
  170. 'only_matching': True,
  171. },
  172. {
  173. # age restricted video, requires vk account credentials
  174. 'url': 'https://vk.com/video205387401_164765225',
  175. 'only_matching': True,
  176. },
  177. {
  178. # pladform embed
  179. 'url': 'https://vk.com/video-76116461_171554880',
  180. 'only_matching': True,
  181. }
  182. ]
  183. def _login(self):
  184. (username, password) = self._get_login_info()
  185. if username is None:
  186. return
  187. login_page, url_handle = self._download_webpage_handle(
  188. 'https://vk.com', None, 'Downloading login page')
  189. login_form = self._hidden_inputs(login_page)
  190. login_form.update({
  191. 'email': username.encode('cp1251'),
  192. 'pass': password.encode('cp1251'),
  193. })
  194. # https://new.vk.com/ serves two same remixlhk cookies in Set-Cookie header
  195. # and expects the first one to be set rather than second (see
  196. # https://github.com/rg3/youtube-dl/issues/9841#issuecomment-227871201).
  197. # As of RFC6265 the newer one cookie should be set into cookie store
  198. # what actually happens.
  199. # We will workaround this VK issue by resetting the remixlhk cookie to
  200. # the first one manually.
  201. cookies = url_handle.headers.get('Set-Cookie')
  202. if sys.version_info[0] >= 3:
  203. cookies = cookies.encode('iso-8859-1')
  204. cookies = cookies.decode('utf-8')
  205. remixlhk = re.search(r'remixlhk=(.+?);.*?\bdomain=(.+?)(?:[,;]|$)', cookies)
  206. if remixlhk:
  207. value, domain = remixlhk.groups()
  208. self._set_cookie(domain, 'remixlhk', value)
  209. request = sanitized_Request(
  210. 'https://login.vk.com/?act=login',
  211. urlencode_postdata(login_form))
  212. login_page = self._download_webpage(
  213. request, None, note='Logging in as %s' % username)
  214. if re.search(r'onLoginFailed', login_page):
  215. raise ExtractorError(
  216. 'Unable to login, incorrect username and/or password', expected=True)
  217. def _real_initialize(self):
  218. self._login()
  219. def _real_extract(self, url):
  220. mobj = re.match(self._VALID_URL, url)
  221. video_id = mobj.group('videoid')
  222. if video_id:
  223. info_url = 'https://vk.com/al_video.php?act=show&al=1&module=video&video=%s' % video_id
  224. # Some videos (removed?) can only be downloaded with list id specified
  225. list_id = mobj.group('list_id')
  226. if list_id:
  227. info_url += '&list=%s' % list_id
  228. else:
  229. info_url = 'http://vk.com/video_ext.php?' + mobj.group('embed_query')
  230. video_id = '%s_%s' % (mobj.group('oid'), mobj.group('id'))
  231. info_page = self._download_webpage(info_url, video_id)
  232. error_message = self._html_search_regex(
  233. [r'(?s)<!><div[^>]+class="video_layer_message"[^>]*>(.+?)</div>',
  234. r'(?s)<div[^>]+id="video_ext_msg"[^>]*>(.+?)</div>'],
  235. info_page, 'error message', default=None)
  236. if error_message:
  237. raise ExtractorError(error_message, expected=True)
  238. if re.search(r'<!>/login\.php\?.*\bact=security_check', info_page):
  239. raise ExtractorError(
  240. 'You are trying to log in from an unusual location. You should confirm ownership at vk.com to log in with this IP.',
  241. expected=True)
  242. ERRORS = {
  243. r'>Видеозапись .*? была изъята из публичного доступа в связи с обращением правообладателя.<':
  244. 'Video %s has been removed from public access due to rightholder complaint.',
  245. r'<!>Please log in or <':
  246. 'Video %s is only available for registered users, '
  247. 'use --username and --password options to provide account credentials.',
  248. r'<!>Unknown error':
  249. 'Video %s does not exist.',
  250. r'<!>Видео временно недоступно':
  251. 'Video %s is temporarily unavailable.',
  252. r'<!>Access denied':
  253. 'Access denied to video %s.',
  254. }
  255. for error_re, error_msg in ERRORS.items():
  256. if re.search(error_re, info_page):
  257. raise ExtractorError(error_msg % video_id, expected=True)
  258. youtube_url = self._search_regex(
  259. r'<iframe[^>]+src="((?:https?:)?//www.youtube.com/embed/[^"]+)"',
  260. info_page, 'youtube iframe', default=None)
  261. if youtube_url:
  262. return self.url_result(youtube_url, 'Youtube')
  263. vimeo_url = VimeoIE._extract_vimeo_url(url, info_page)
  264. if vimeo_url is not None:
  265. return self.url_result(vimeo_url)
  266. pladform_url = PladformIE._extract_url(info_page)
  267. if pladform_url:
  268. return self.url_result(pladform_url)
  269. m_rutube = re.search(
  270. r'\ssrc="((?:https?:)?//rutube\.ru\\?/(?:video|play)\\?/embed(?:.*?))\\?"', info_page)
  271. if m_rutube is not None:
  272. rutube_url = self._proto_relative_url(
  273. m_rutube.group(1).replace('\\', ''))
  274. return self.url_result(rutube_url)
  275. m_opts = re.search(r'(?s)var\s+opts\s*=\s*({.+?});', info_page)
  276. if m_opts:
  277. m_opts_url = re.search(r"url\s*:\s*'((?!/\b)[^']+)", m_opts.group(1))
  278. if m_opts_url:
  279. opts_url = m_opts_url.group(1)
  280. if opts_url.startswith('//'):
  281. opts_url = 'http:' + opts_url
  282. return self.url_result(opts_url)
  283. data_json = self._search_regex(r'var\s+vars\s*=\s*({.+?});', info_page, 'vars')
  284. data = json.loads(data_json)
  285. # Extract upload date
  286. upload_date = None
  287. mobj = re.search(r'id="mv_date(?:_views)?_wrap"[^>]*>([a-zA-Z]+ [0-9]+), ([0-9]+) at', info_page)
  288. if mobj is not None:
  289. mobj.group(1) + ' ' + mobj.group(2)
  290. upload_date = unified_strdate(mobj.group(1) + ' ' + mobj.group(2))
  291. view_count = None
  292. views = self._html_search_regex(
  293. r'"mv_views_count_number"[^>]*>(.+?\bviews?)<',
  294. info_page, 'view count', default=None)
  295. if views:
  296. view_count = str_to_int(self._search_regex(
  297. r'([\d,.]+)', views, 'view count', fatal=False))
  298. formats = []
  299. for k, v in data.items():
  300. if not k.startswith('url') and not k.startswith('cache') and k != 'extra_data' or not v:
  301. continue
  302. height = int_or_none(self._search_regex(
  303. r'^(?:url|cache)(\d+)', k, 'height', default=None))
  304. formats.append({
  305. 'format_id': k,
  306. 'url': v,
  307. 'height': height,
  308. })
  309. self._sort_formats(formats)
  310. return {
  311. 'id': compat_str(data['vid']),
  312. 'formats': formats,
  313. 'title': unescapeHTML(data['md_title']),
  314. 'thumbnail': data.get('jpg'),
  315. 'uploader': data.get('md_author'),
  316. 'duration': data.get('duration'),
  317. 'upload_date': upload_date,
  318. 'view_count': view_count,
  319. }
  320. class VKUserVideosIE(InfoExtractor):
  321. IE_NAME = 'vk:uservideos'
  322. IE_DESC = "VK - User's Videos"
  323. _VALID_URL = r'https?://vk\.com/videos(?P<id>-?[0-9]+)(?!\?.*\bz=video)(?:[/?#&]|$)'
  324. _TEMPLATE_URL = 'https://vk.com/videos'
  325. _TESTS = [{
  326. 'url': 'http://vk.com/videos205387401',
  327. 'info_dict': {
  328. 'id': '205387401',
  329. 'title': "Tom Cruise's Videos",
  330. },
  331. 'playlist_mincount': 4,
  332. }, {
  333. 'url': 'http://vk.com/videos-77521',
  334. 'only_matching': True,
  335. }, {
  336. 'url': 'http://vk.com/videos-97664626?section=all',
  337. 'only_matching': True,
  338. }]
  339. def _real_extract(self, url):
  340. page_id = self._match_id(url)
  341. webpage = self._download_webpage(url, page_id)
  342. entries = [
  343. self.url_result(
  344. 'http://vk.com/video' + video_id, 'VK', video_id=video_id)
  345. for video_id in orderedSet(re.findall(r'href="/video(-?[0-9_]+)"', webpage))]
  346. title = unescapeHTML(self._search_regex(
  347. r'<title>\s*([^<]+?)\s+\|\s+\d+\s+videos',
  348. webpage, 'title', default=page_id))
  349. return self.playlist_result(entries, page_id, title)