This commit is contained in:
2026-11-20 22:48:28 +03:00
parent 276dbdad8a
commit 8e1f96b70b
46 changed files with 2345 additions and 49 deletions
@@ -0,0 +1,93 @@
package ru.mtusi.messenger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import static ru.mtusi.messenger.Models.*;
@Service
public class AttachmentService {
public static final long MAX_BYTES = 10_485_760L;
public static final long MAX_PIXELS = 40_000_000L;
private final JdbcTemplate jdbc;
private final MessengerStore store;
private final S3Storage s3;
private final TransactionTemplate transaction;
public AttachmentService(JdbcTemplate jdbc, MessengerStore store, S3Storage s3,
org.springframework.transaction.PlatformTransactionManager manager) {
this.jdbc = jdbc; this.store = store; this.s3 = s3; this.transaction = new TransactionTemplate(manager);
}
public Attachment upload(UUID actor, UUID chatId, String filename, String contentType, InputStream input) throws IOException {
store.chat(actor, chatId); validateFilename(filename);
String normalizedType = contentType == null ? "" : contentType.split(";", 2)[0].trim().toLowerCase();
if (!normalizedType.equals("image/png") && !normalizedType.equals("image/jpeg")) throw new ApiException(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG");
Path temp = Files.createTempFile("messenger-upload-", ".bin"); UUID id = UUID.randomUUID(); String stagingKey = "staging/" + id; boolean uploaded = false;
try {
long size = copyWithLimit(input, temp, MAX_BYTES); String actualType = detectType(temp);
if (!normalizedType.equals(actualType)) throw new ApiException(415, "unsupported_media_type", "MIME не совпадает с содержимым");
validateImage(temp); String sha256 = sha256(temp);
try (InputStream file = Files.newInputStream(temp)) { s3.put(stagingKey, file, size, actualType); uploaded = true; }
Instant now = Instant.now(); UUID jobId = UUID.randomUUID();
try {
transaction.executeWithoutResult(status -> {
jdbc.update("""
INSERT INTO attachments(id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, staging_key, status, error_code, pipeline_version, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL, 1, ?, ?)
""", id, chatId, actor, filename, actualType, size, sha256, "original/" + id, stagingKey, Timestamp.from(now), Timestamp.from(now));
jdbc.update("""
INSERT INTO attachment_jobs(job_id, attachment_id, pipeline_version, attempt, status, next_attempt_at, lease_until, error_code, published_at, created_at, updated_at)
VALUES (?, ?, 1, 0, 'queued', ?, NULL, NULL, NULL, ?, ?)
""", jobId, id, Timestamp.from(now), Timestamp.from(now), Timestamp.from(now));
});
} catch (RuntimeException exception) { if (uploaded) s3.delete(stagingKey); throw exception; }
return get(actor, id);
} finally { Files.deleteIfExists(temp); }
}
public Attachment get(UUID actor, UUID id) {
try {
return jdbc.queryForObject("""
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=? AND m.user_id=?
""", (rs, row) -> new Attachment(rs.getObject("id", UUID.class), rs.getObject("chat_id", UUID.class), rs.getObject("owner_id", UUID.class), rs.getString("filename"), rs.getString("content_type"), rs.getLong("size_bytes"), rs.getString("sha256"), rs.getString("status"), loadVariants(rs.getObject("id", UUID.class)), rs.getString("error_code"), rs.getTimestamp("created_at").toInstant(), rs.getTimestamp("updated_at").toInstant()), id, actor);
} catch (EmptyResultDataAccessException exception) { throw ApiException.notFound(); }
}
public Download download(UUID actor, UUID id, String variant) {
if (!List.of("original", "thumbnail", "crop", "optimized").contains(variant)) throw ApiException.notFound();
Attachment metadata = get(actor, id);
if (metadata.status().equals("queued") || metadata.status().equals("processing")) throw new ApiException(409, "conflict", "Вложение ещё обрабатывается");
if (metadata.status().equals("failed")) throw new ApiException(409, "conflict", "Обработка вложения завершилась ошибкой");
try {
String key; String type;
if (variant.equals("original")) { key = jdbc.queryForObject("SELECT object_key FROM attachments WHERE id=?", String.class, id); type = metadata.contentType(); }
else { Variant v = metadata.variants().stream().filter(x -> x.name().equals(variant)).findFirst().orElseThrow(ApiException::notFound); key = jdbc.queryForObject("SELECT object_key FROM attachment_variants WHERE attachment_id=? AND name=?", String.class, id, variant); type = v.contentType(); }
return new Download(s3.get(key), type);
} catch (EmptyResultDataAccessException exception) { throw ApiException.notFound(); }
}
private List<Variant> loadVariants(UUID id) { return jdbc.query("SELECT name, content_type, size_bytes, width, height, sha256 FROM attachment_variants WHERE attachment_id=? ORDER BY name", (rs, row) -> new Variant(rs.getString("name"), rs.getString("content_type"), rs.getLong("size_bytes"), rs.getInt("width"), rs.getInt("height"), rs.getString("sha256")), id); }
private static long copyWithLimit(InputStream input, Path target, long max) throws IOException { long total = 0; byte[] buffer = new byte[8192]; try (var output = Files.newOutputStream(target)) { int read; while ((read = input.read(buffer)) != -1) { total += read; if (total > max) throw new ApiException(413, "payload_too_large", "Файл слишком большой"); output.write(buffer, 0, read); } } if (total == 0) throw new ApiException(400, "invalid_request", "Пустой файл"); return total; }
private static String detectType(Path path) throws IOException { byte[] h = new byte[12]; int n; try (InputStream in = Files.newInputStream(path)) { n = in.read(h); } if (n >= 8 && (h[0] & 255) == 0x89 && h[1] == 0x50 && h[2] == 0x4e && h[3] == 0x47 && h[4] == 0x0d && h[5] == 0x0a && h[6] == 0x1a && h[7] == 0x0a) return "image/png"; if (n >= 3 && (h[0] & 255) == 0xff && (h[1] & 255) == 0xd8 && (h[2] & 255) == 0xff) return "image/jpeg"; throw new ApiException(415, "unsupported_media_type", "Файл не является PNG или JPEG"); }
static Dimensions validateImage(Path path) throws IOException { try (ImageInputStream stream = ImageIO.createImageInputStream(path.toFile())) { Iterator<ImageReader> readers = ImageIO.getImageReaders(stream); if (!readers.hasNext()) throw new ApiException(415, "unsupported_media_type", "Повреждённое изображение"); ImageReader reader = readers.next(); try { reader.setInput(stream, true, true); int width = reader.getWidth(0), height = reader.getHeight(0); if ((long) width * height > MAX_PIXELS) throw new ApiException(413, "payload_too_large", "Слишком много пикселей"); if (ImageIO.read(path.toFile()) == null) throw new ApiException(415, "unsupported_media_type", "Повреждённое изображение"); return new Dimensions(width, height); } finally { reader.dispose(); } } }
static String sha256(Path path) throws IOException { try (InputStream input = Files.newInputStream(path)) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] buffer = new byte[8192]; int n; while ((n = input.read(buffer)) != -1) digest.update(buffer, 0, n); StringBuilder result = new StringBuilder(); for (byte value : digest.digest()) result.append(String.format("%02x", value)); return result.toString(); } catch (java.security.NoSuchAlgorithmException exception) { throw new IllegalStateException(exception); } } }
private static void validateFilename(String value) { if (value == null || value.isEmpty() || value.codePointCount(0, value.length()) > 255 || value.indexOf('/') >= 0 || value.indexOf('\\') >= 0 || value.indexOf('\0') >= 0 || value.codePoints().anyMatch(cp -> cp < 32 || cp == 127)) throw ApiException.invalid("Некорректное имя файла"); }
record Dimensions(int width, int height) {}
public record Download(InputStream stream, String contentType) {}
}