| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2021-2026 Mike Fährmann |
| 4 |
# |
| 5 |
# This program is free software; you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License version 2 as |
| 7 |
# published by the Free Software Foundation. |
| 8 |
|
| 9 |
"""Extractors for https://vk.com/""" |
| 10 |
|
| 11 |
from .common import Extractor, Message |
| 12 |
from .. import text |
| 13 |
|
| 14 |
BASE_PATTERN = r"(?:https://)?(?:www\.|m\.)?vk\.(com|ru)" |
| 15 |
|
| 16 |
|
| 17 |
class VkExtractor(Extractor): |
| 18 |
"""Base class for vk extractors""" |
| 19 |
category = "vk" |
| 20 |
directory_fmt = ("{category}", "{user[name]|user[id]}") |
| 21 |
filename_fmt = "{id}.{extension}" |
| 22 |
archive_fmt = "{user[id]}_{id}" |
| 23 |
root = "https://vk.com" |
| 24 |
request_interval = (0.5, 1.5) |
| 25 |
|
| 26 |
def initialize(self): |
| 27 |
domain = self.config("domain", "auto") |
| 28 |
if domain == "auto": |
| 29 |
domain = "vk." + self.groups[0] |
| 30 |
self.root = "https://" + domain |
| 31 |
self.cookies_domain = "." + domain |
| 32 |
Extractor.initialize(self) |
| 33 |
|
| 34 |
def _init(self): |
| 35 |
self.offset = text.parse_int(self.config("offset")) |
| 36 |
|
| 37 |
def finalize(self, status): |
| 38 |
if status and self.offset: |
| 39 |
self.log.info("Use '-o offset=%s' to continue downloading " |
| 40 |
"from the current position", self.offset) |
| 41 |
|
| 42 |
def skip_files(self, num): |
| 43 |
self.offset += num |
| 44 |
return num |
| 45 |
|
| 46 |
def items(self): |
| 47 |
subn = text.re(r"/imp[fg]/").subn |
| 48 |
sizes = "wzyxrqpo" |
| 49 |
|
| 50 |
data = self.metadata() |
| 51 |
yield Message.Directory, "", data |
| 52 |
|
| 53 |
for photo in self.photos(): |
| 54 |
|
| 55 |
for size in sizes: |
| 56 |
size += "_" |
| 57 |
if size in photo: |
| 58 |
break |
| 59 |
else: |
| 60 |
self.log.warning("no photo URL found (%s)", photo.get("id")) |
| 61 |
continue |
| 62 |
|
| 63 |
try: |
| 64 |
url = photo[size + "src"] |
| 65 |
except KeyError: |
| 66 |
self.log.warning("no photo URL found (%s)", photo.get("id")) |
| 67 |
continue |
| 68 |
|
| 69 |
url_sub, count = subn("/", url.partition("?")[0]) |
| 70 |
if count: |
| 71 |
photo["_fallback"] = (url,) |
| 72 |
photo["url"] = url = url_sub |
| 73 |
else: |
| 74 |
photo["url"] = url |
| 75 |
|
| 76 |
try: |
| 77 |
_, photo["width"], photo["height"] = photo[size] |
| 78 |
except ValueError: |
| 79 |
# photo without width/height entries (#2535) |
| 80 |
photo["width"] = photo["height"] = 0 |
| 81 |
|
| 82 |
photo["id"] = photo["id"].rpartition("_")[2] |
| 83 |
photo["date"] = self.parse_timestamp(text.extr( |
| 84 |
photo["date"], 'data-date="', '"')) |
| 85 |
photo["description"] = text.unescape(text.extr( |
| 86 |
photo.get("desc", ""), ">", "<")) |
| 87 |
photo.update(data) |
| 88 |
|
| 89 |
text.nameext_from_url(url, photo) |
| 90 |
yield Message.Url, url, photo |
| 91 |
|
| 92 |
def _pagination(self, photos_id): |
| 93 |
url = self.root + "/al_photos.php" |
| 94 |
headers = { |
| 95 |
"X-Requested-With": "XMLHttpRequest", |
| 96 |
"Origin" : self.root, |
| 97 |
"Referer" : self.root + "/" + photos_id, |
| 98 |
} |
| 99 |
data = { |
| 100 |
"act" : "show", |
| 101 |
"al" : "1", |
| 102 |
"direction": "1", |
| 103 |
"list" : photos_id, |
| 104 |
"offset" : self.offset, |
| 105 |
} |
| 106 |
|
| 107 |
while True: |
| 108 |
response = self.request( |
| 109 |
url, method="POST", headers=headers, data=data) |
| 110 |
if response.history and "/challenge.html" in response.url: |
| 111 |
raise self.exc.AbortExtraction( |
| 112 |
"HTTP redirect to 'challenge' page:\n" + response.url) |
| 113 |
|
| 114 |
payload = response.json()["payload"][1] |
| 115 |
if len(payload) < 4: |
| 116 |
self.log.debug(payload) |
| 117 |
raise self.exc.AuthorizationError( |
| 118 |
text.unescape(payload[0]) if payload[0] else None) |
| 119 |
|
| 120 |
total = payload[1] |
| 121 |
photos = payload[3] |
| 122 |
|
| 123 |
for i in range(len(photos)): |
| 124 |
photos[i]["num"] = self.offset + i + 1 |
| 125 |
photos[i]["count"] = total |
| 126 |
|
| 127 |
offset_next = self.offset + len(photos) |
| 128 |
if offset_next >= total: |
| 129 |
# the last chunk of photos also contains the first few photos |
| 130 |
# again if 'total' is not a multiple of 10 |
| 131 |
if extra := total - offset_next: |
| 132 |
del photos[extra:] |
| 133 |
|
| 134 |
yield from photos |
| 135 |
self.offset = 0 |
| 136 |
return |
| 137 |
|
| 138 |
yield from photos |
| 139 |
data["offset"] = self.offset = offset_next |
| 140 |
|
| 141 |
|
| 142 |
class VkPhotosExtractor(VkExtractor): |
| 143 |
"""Extractor for photos from a vk user""" |
| 144 |
subcategory = "photos" |
| 145 |
pattern = (BASE_PATTERN + r"/(?:" |
| 146 |
r"(?:albums|photos|id)(-?\d+)" |
| 147 |
r"|(?!(?:album|tag|wall)-?\d+_?)([^/?#]+))") |
| 148 |
example = "https://vk.com/id12345" |
| 149 |
|
| 150 |
def __init__(self, match): |
| 151 |
VkExtractor.__init__(self, match) |
| 152 |
_, self.user_id, self.user_name = match.groups() |
| 153 |
|
| 154 |
def photos(self): |
| 155 |
return self._pagination("photos" + self.user_id) |
| 156 |
|
| 157 |
def metadata(self): |
| 158 |
if self.user_id: |
| 159 |
user_id = self.user_id |
| 160 |
prefix = "public" if user_id[0] == "-" else "id" |
| 161 |
url = f"{self.root}/{prefix}{user_id.lstrip('-')}" |
| 162 |
data = self._extract_profile(url) |
| 163 |
else: |
| 164 |
url = f"{self.root}/{self.user_name}" |
| 165 |
data = self._extract_profile(url) |
| 166 |
self.user_id = data["user"]["id"] |
| 167 |
return data |
| 168 |
|
| 169 |
def _extract_profile(self, url): |
| 170 |
page = self.request(url).text |
| 171 |
extr = text.extract_from(page) |
| 172 |
|
| 173 |
user = { |
| 174 |
"id" : extr('property="og:url" content="https://vk.com/id', '"'), |
| 175 |
"nick": text.unescape(extr( |
| 176 |
"<title>", " | VK</title>")), |
| 177 |
"info": text.unescape(extr( |
| 178 |
',"activity":"', '","')).replace("\\/", "/"), |
| 179 |
"name": extr('href="https://m.vk.com/', '"'), |
| 180 |
} |
| 181 |
|
| 182 |
if user["id"]: |
| 183 |
user["group"] = False |
| 184 |
else: |
| 185 |
user["group"] = True |
| 186 |
user["id"] = extr('data-from-id="', '"') |
| 187 |
|
| 188 |
return {"user": user} |
| 189 |
|
| 190 |
|
| 191 |
class VkAlbumExtractor(VkExtractor): |
| 192 |
"""Extractor for a vk album""" |
| 193 |
subcategory = "album" |
| 194 |
directory_fmt = ("{category}", "{user[id]}", "{album[id]}") |
| 195 |
pattern = BASE_PATTERN + r"/album(-?\d+)_(\d+)$" |
| 196 |
example = "https://vk.com/album12345_00" |
| 197 |
|
| 198 |
def photos(self): |
| 199 |
_, user_id, album_id = self.groups |
| 200 |
return self._pagination(f"album{user_id}_{album_id}") |
| 201 |
|
| 202 |
def metadata(self): |
| 203 |
_, user_id, album_id = self.groups |
| 204 |
|
| 205 |
url = f"{self.root}/album{user_id}_{album_id}" |
| 206 |
page = self.request(url).text |
| 207 |
desc = text.extr(page, 'name="og:description" value="', '"') |
| 208 |
try: |
| 209 |
album_name, user_name, photos = desc.rsplit(" - ", 2) |
| 210 |
except ValueError: |
| 211 |
if msg := text.extr( |
| 212 |
page, '<div class="message_page_title">Error</div>', |
| 213 |
"</div>"): |
| 214 |
msg = f" ('{text.remove_html(msg)[:-5]}')" |
| 215 |
self.log.warning("%s_%s: Failed to extract metadata%s", |
| 216 |
user_id, album_id, msg) |
| 217 |
return {"user": {"id": user_id}, "album": {"id": album_id}} |
| 218 |
|
| 219 |
return { |
| 220 |
"user": { |
| 221 |
"id" : user_id, |
| 222 |
"nick" : text.unescape(user_name), |
| 223 |
"name" : text.unescape(text.extr( |
| 224 |
page, 'class="ui_crumb" href="/', '"')), |
| 225 |
"group": user_id[0] == "-", |
| 226 |
}, |
| 227 |
"album": { |
| 228 |
"id" : album_id, |
| 229 |
"name" : text.unescape(album_name), |
| 230 |
"count": text.parse_int(photos[:-7]) |
| 231 |
}, |
| 232 |
} |
| 233 |
|
| 234 |
|
| 235 |
class VkTaggedExtractor(VkExtractor): |
| 236 |
"""Extractor for a vk tagged photos""" |
| 237 |
subcategory = "tagged" |
| 238 |
directory_fmt = ("{category}", "{user[id]}", "tags") |
| 239 |
pattern = BASE_PATTERN + r"/tag(-?\d+)$" |
| 240 |
example = "https://vk.com/tag12345" |
| 241 |
|
| 242 |
def __init__(self, match): |
| 243 |
VkExtractor.__init__(self, match) |
| 244 |
self.user_id = match[1] |
| 245 |
|
| 246 |
def photos(self): |
| 247 |
return self._pagination("tag" + self.user_id) |
| 248 |
|
| 249 |
def metadata(self): |
| 250 |
return {"user": {"id": self.user_id}} |
| 251 |
|
| 252 |
|
| 253 |
class VkWallPostExtractor(VkExtractor): |
| 254 |
"""Extractor for a vk wall post""" |
| 255 |
subcategory = "wall-post" |
| 256 |
directory_fmt = ("{category}", "{user[id]}", "wall") |
| 257 |
filename_fmt = "{wall[id]}_{num}.{extension}" |
| 258 |
pattern = BASE_PATTERN + r"/wall(-?\d+)_(\d+)" |
| 259 |
example = "https://vk.com/wall12345_123" |
| 260 |
|
| 261 |
def photos(self): |
| 262 |
_, user_id, wall_id = self.groups |
| 263 |
return self._pagination(f"wall{user_id}_{wall_id}") |
| 264 |
|
| 265 |
def metadata(self): |
| 266 |
_, user_id, wall_id = self.groups |
| 267 |
|
| 268 |
url = f"{self.root}/wall{user_id}_{wall_id}" |
| 269 |
page = self.request(url).text |
| 270 |
desc = text.unescape( |
| 271 |
text.extr(page, 'data-testid="post_description">', "</div>") or |
| 272 |
text.extr(page, 'name="description" content="', '"')) |
| 273 |
|
| 274 |
return { |
| 275 |
"user": { |
| 276 |
"id": user_id, |
| 277 |
}, |
| 278 |
"wall": { |
| 279 |
"id": wall_id, |
| 280 |
"description": desc, |
| 281 |
}, |
| 282 |
} |