package com.android.trisolarisserver.controller import com.android.trisolarisserver.component.PropertyAccess import com.android.trisolarisserver.db.repo.InboundEmailRepo import com.android.trisolarisserver.models.property.Role import com.android.trisolarisserver.security.MyPrincipal import org.springframework.core.io.FileSystemResource import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.security.core.annotation.AuthenticationPrincipal import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.server.ResponseStatusException import java.nio.file.Files import java.nio.file.Paths import java.util.UUID @RestController @RequestMapping("/properties/{propertyId}/inbound-emails") class InboundEmails( private val propertyAccess: PropertyAccess, private val inboundEmailRepo: InboundEmailRepo ) { @GetMapping("/{emailId}/file") fun downloadEmailPdf( @PathVariable propertyId: UUID, @PathVariable emailId: UUID, @AuthenticationPrincipal principal: MyPrincipal? ): ResponseEntity { requirePrincipal(principal) propertyAccess.requireMember(propertyId, principal!!.userId) propertyAccess.requireAnyRole(propertyId, principal.userId, Role.ADMIN, Role.MANAGER) val email = inboundEmailRepo.findByIdAndPropertyId(emailId, propertyId) ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Email not found") val path = email.rawPdfPath ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Email PDF missing") val file = Paths.get(path) if (!Files.exists(file)) { throw ResponseStatusException(HttpStatus.NOT_FOUND, "Email PDF missing") } val resource = FileSystemResource(file) return ResponseEntity.ok() .contentType(MediaType.APPLICATION_PDF) .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"email-${emailId}.pdf\"") .contentLength(resource.contentLength()) .body(resource) } private fun requirePrincipal(principal: MyPrincipal?) { if (principal == null) { throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing principal") } } }