package ru.mtuci.messenger.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.InvalidMediaTypeException; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionTemplate; import ru.mtuci.messenger.api.model.Attachment; import ru.mtuci.messenger.domain.AttachmentEntity; import ru.mtuci.messenger.exception.InvalidRequestException; import ru.mtuci.messenger.exception.NotFoundException; import ru.mtuci.messenger.exception.PayloadTooLargeException; import ru.mtuci.messenger.exception.UnsupportedMediaException; import ru.mtuci.messenger.repository.AttachmentRepository; import ru.mtuci.messenger.repository.ChatMemberRepository; import ru.mtuci.messenger.storage.ObjectStorage; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HexFormat; import java.util.UUID; @Service public class AttachmentService { private final AttachmentRepository attachments; private final ChatMemberRepository members; private final ObjectStorage storage; private final TransactionTemplate transactions; private final int maxBytes; private final long maxPixels; public AttachmentService(AttachmentRepository attachments, ChatMemberRepository members, ObjectStorage storage, PlatformTransactionManager transactionManager, @Value("${app.upload.max-bytes:10485760}") int maxBytes, @Value("${app.upload.max-pixels:40000000}") long maxPixels) { this.attachments = attachments; this.members = members; this.storage = storage; this.transactions = new TransactionTemplate(transactionManager); this.maxBytes = maxBytes; this.maxPixels = maxPixels; } public Attachment upload(UUID actorId, UUID chatId, String filename, String contentType, long contentLength, InputStream body) { requireMember(chatId, actorId); String displayName = filename(filename); String declared = declaredType(contentType); if (contentLength > maxBytes) { throw new PayloadTooLargeException(); } byte[] bytes; try { bytes = ImageFiles.readLimited(body, maxBytes); } catch (PayloadTooLargeException tooLarge) { throw tooLarge; } catch (java.io.IOException exception) { throw new ru.mtuci.messenger.exception.UnavailableException("Хранилище временно недоступно"); } ImageFiles.Image image = ImageFiles.inspect(bytes, declared, maxPixels); UUID id = UUID.randomUUID(); String key = "originals/" + id; storage.ensureBucket(); storage.put(key, bytes, image.contentType()); try { AttachmentEntity saved = transactions.execute(status -> attachments.saveAndFlush(new AttachmentEntity( id, chatId, actorId, displayName, image.contentType(), bytes.length, sha256(bytes), key))); return toModel(saved); } catch (RuntimeException exception) { storage.deleteQuietly(key); throw exception; } } @Transactional(readOnly = true) public Attachment get(UUID actorId, UUID attachmentId) { return toModel(visible(actorId, attachmentId)); } @Transactional(readOnly = true) public AttachmentEntity content(UUID actorId, UUID attachmentId, String variant) { if (variant != null && !"original".equals(variant)) { throw new InvalidRequestException("Некорректный запрос"); } return visible(actorId, attachmentId); } public InputStream open(AttachmentEntity attachment) { return storage.get(attachment.getObjectKey()); } private AttachmentEntity visible(UUID actorId, UUID attachmentId) { AttachmentEntity attachment = attachments.findById(attachmentId).orElseThrow(NotFoundException::new); if (!members.existsByChatIdAndUserId(attachment.getChatId(), actorId)) { throw new NotFoundException(); } return attachment; } private void requireMember(UUID chatId, UUID actorId) { if (!members.existsByChatIdAndUserId(chatId, actorId)) { throw new NotFoundException(); } } private static String filename(String value) { if (value == null) { throw new InvalidRequestException("Некорректный запрос"); } int codePoints = value.codePointCount(0, value.length()); if (codePoints < 1 || codePoints > 255) { throw new InvalidRequestException("Некорректный запрос"); } int offset = 0; while (offset < value.length()) { int codePoint = value.codePointAt(offset); if (codePoint == '/' || codePoint == '\\' || Character.isISOControl(codePoint)) { throw new InvalidRequestException("Некорректный запрос"); } offset += Character.charCount(codePoint); } return value; } private static String declaredType(String header) { if (header == null || header.isBlank()) { throw new UnsupportedMediaException(); } MediaType media; try { media = MediaType.parseMediaType(header); } catch (InvalidMediaTypeException exception) { throw new UnsupportedMediaException(); } if (media.equalsTypeAndSubtype(MediaType.IMAGE_PNG)) { return "image/png"; } if (media.equalsTypeAndSubtype(MediaType.parseMediaType("image/jpeg"))) { return "image/jpeg"; } throw new UnsupportedMediaException(); } private static String sha256(byte[] bytes) { try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } catch (NoSuchAlgorithmException exception) { throw new IllegalStateException(exception); } } private static Attachment toModel(AttachmentEntity entity) { Attachment model = new Attachment(); model.setId(entity.getId()); model.setChatId(entity.getChatId()); model.setOwnerId(entity.getOwnerId()); model.setFilename(entity.getFilename()); model.setContentType(Attachment.ContentTypeEnum.fromValue(entity.getContentType())); model.setSizeBytes((int) entity.getSizeBytes()); model.setSha256(entity.getSha256()); model.setStatus(Attachment.StatusEnum.READY); model.setVariants(new ArrayList<>()); model.setErrorCode(null); model.setCreatedAt(entity.getCreatedAt().atOffset(java.time.ZoneOffset.UTC)); model.setUpdatedAt(entity.getUpdatedAt().atOffset(java.time.ZoneOffset.UTC)); return model; } }