diff --git a/docs/api-integration.md b/docs/api-integration.md index 90af6df..2400b50 100644 --- a/docs/api-integration.md +++ b/docs/api-integration.md @@ -205,6 +205,15 @@ Accept-Language: zh-CN 具体哪些接口属于二进制响应,以 OpenAPI 中定义的响应 `Content-Type` 为准。 +#### 缩略图预览 + +`GET /system/file/preview/{path}` 仅支持图片和视频,其他类型返回 `400`。图片和视频统一返回缩略图: + +- `size`:缩略图最大边长(像素),范围 `32-512`,默认 `256` +- `v`:缓存版本号,建议传文件列表返回的 `etag`;传入后响应使用一年强缓存,不传时缓存一天 +- 响应 `Content-Type` 为 `image/jpeg` 或 `image/png`;PNG/GIF 源图使用 PNG,其余使用 JPEG +- 支持 `If-None-Match` 条件请求,`ETag` 已包含缩略图尺寸和算法版本 + ### 3.2 SSE 部分长任务接口使用 `text/event-stream`,不经过 `TimiResponse`。事件类型如下: diff --git a/src/main/java/com/imyeyu/api/modules/system/bean/ServerFile.java b/src/main/java/com/imyeyu/api/modules/system/bean/ServerFile.java index 6430aab..ec83bd9 100644 --- a/src/main/java/com/imyeyu/api/modules/system/bean/ServerFile.java +++ b/src/main/java/com/imyeyu/api/modules/system/bean/ServerFile.java @@ -1,5 +1,6 @@ package com.imyeyu.api.modules.system.bean; +import com.imyeyu.api.modules.system.util.FilePreview; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.tika.Tika; @@ -103,12 +104,7 @@ public class ServerFile implements Serializable { this.mimeType = TIKA.detect(this.name); this.category = FileCategory.of(this.mimeType, this.extension, false); this.etag = String.format("\"%x-%x\"", this.size, this.modifiedAt); - this.canPreview = switch (this.mimeType) { - case "image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp", - "video/mp4", "video/quicktime", "video/webm", - "application/pdf", "text/plain" -> true; - default -> false; - }; + this.canPreview = FilePreview.supports(this.mimeType); } else { this.size = 0L; this.modifiedAt = absolute.toFile().lastModified(); diff --git a/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java b/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java index 06d3fb4..3a7925f 100644 --- a/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java +++ b/src/main/java/com/imyeyu/api/modules/system/controller/FileContentController.java @@ -15,6 +15,7 @@ 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.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** @@ -55,14 +56,18 @@ public class FileContentController { FileBinaryResponder.serve(resp, () -> contentService.serve(req, resp, path, true)); } - @Operation(summary = "预览文件", description = "图片和视频返回 PNG 缩略图,PDF 与文本返回原始内容。") + @Operation(summary = "预览文件", description = "图片和视频返回缩略图,其他类型不支持。") @RequireCorePermission(CorePermissionCode.FILE_READ) @IgnoreGlobalReturn @GetMapping("/preview/{*path}") public void preview( HttpServletRequest req, HttpServletResponse resp, @Parameter(description = "文件虚拟路径,以 / 开头", required = true) - @PathVariable("path") String path) { - FileBinaryResponder.serve(resp, () -> contentService.preview(req, resp, path)); + @PathVariable("path") String path, + @Parameter(description = "缩略图最大边长(像素),范围 32-512,默认 256", example = "256") + @RequestParam(value = "size", required = false, defaultValue = "256") int size, + @Parameter(description = "缓存版本号,建议传文件列表返回的 etag;传入后使用长期强缓存") + @RequestParam(value = "v", required = false) String version) { + FileBinaryResponder.serve(resp, () -> contentService.preview(req, resp, path, size, version)); } } diff --git a/src/main/java/com/imyeyu/api/modules/system/service/FileContentService.java b/src/main/java/com/imyeyu/api/modules/system/service/FileContentService.java index 3edcdb4..1f7578a 100644 --- a/src/main/java/com/imyeyu/api/modules/system/service/FileContentService.java +++ b/src/main/java/com/imyeyu/api/modules/system/service/FileContentService.java @@ -1,5 +1,6 @@ package com.imyeyu.api.modules.system.service; +import com.imyeyu.api.modules.system.util.FilePreview; import com.imyeyu.api.modules.system.util.ResourceHandler; import com.imyeyu.java.bean.timi.TimiCode; import com.imyeyu.java.bean.timi.TimiException; @@ -28,6 +29,8 @@ public class FileContentService { "text/html", "application/xhtml+xml", "image/svg+xml", "application/javascript", "text/javascript", "application/x-javascript" ); + private static final String PREVIEW_CACHE_CONTROL = "private, max-age=86400"; + private static final String PREVIEW_IMMUTABLE_CACHE_CONTROL = "private, max-age=31536000, immutable"; private final FileStorageService storage; private final ThumbnailService thumbnailService; @@ -56,7 +59,7 @@ public class FileContentService { resp.setHeader("ETag", info.etag()); resp.setDateHeader("Last-Modified", info.modifiedAt()); resp.setHeader("Cache-Control", "private, max-age=0, must-revalidate"); - if (notModified(req, info)) { + if (notModified(req, info.etag())) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } @@ -80,50 +83,48 @@ public class FileContentService { } } - /// 输出预览图。图片/视频走缩略图缓存,PDF/文本直接内联。 - public void preview(HttpServletRequest req, HttpServletResponse resp, String virtualPath) { + /// 输出预览图。仅图片和视频支持,按请求尺寸生成缩略图。 + /// + /// @param size 缩略图最大边长 + /// @param version 缓存版本号,建议传文件列表返回的 etag;传入后使用长期强缓存 + public void preview(HttpServletRequest req, HttpServletResponse resp, String virtualPath, int size, String version) { + ThumbnailService.requireValidSize(size); ContentInfo info = info(virtualPath); - if (info.attachment()) { + if (info.attachment() || !FilePreview.supports(info.mimeType())) { throw new TimiException(TimiCode.ARG_BAD, "该文件类型不支持在线预览"); } - resp.setHeader("ETag", info.etag()); + String etag = previewEtag(info, size); + resp.setHeader("ETag", etag); resp.setDateHeader("Last-Modified", info.modifiedAt()); - if (notModified(req, info)) { + resp.setHeader("Cache-Control", version == null || version.isBlank() + ? PREVIEW_CACHE_CONTROL : PREVIEW_IMMUTABLE_CACHE_CONTROL); + if (notModified(req, etag)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } - if (info.mimeType().startsWith("image/") || info.mimeType().startsWith("video/")) { - Path thumbnail = thumbnailService.thumbnail(info.path(), info.mimeType()); - try { - resp.setContentType("image/png"); - resp.setHeader("X-Content-Type-Options", "nosniff"); - resp.setHeader("Cache-Control", "private, max-age=86400"); - resp.setContentLengthLong(Files.size(thumbnail)); - Files.copy(thumbnail, resp.getOutputStream()); - } catch (IOException e) { - throw new TimiException(TimiCode.ERROR, "生成预览失败"); - } - return; - } - if ("application/pdf".equals(info.mimeType()) || "text/plain".equals(info.mimeType())) { - resp.setContentType(info.mimeType()); + Path thumbnail = thumbnailService.thumbnail(info.path(), info.mimeType(), size); + try { + resp.setContentType(contentType(thumbnail)); resp.setHeader("X-Content-Type-Options", "nosniff"); - resp.setHeader("Content-Disposition", "inline; filename*=UTF-8''" + - java.net.URLEncoder.encode(info.path().getFileName().toString(), java.nio.charset.StandardCharsets.UTF_8).replace("+", "%20")); - resp.setContentLengthLong(info.size()); - try { - Files.copy(info.path(), resp.getOutputStream()); - } catch (IOException e) { - throw new TimiException(TimiCode.ERROR, "读取文件失败"); - } - return; + resp.setContentLengthLong(Files.size(thumbnail)); + Files.copy(thumbnail, resp.getOutputStream()); + } catch (IOException e) { + throw new TimiException(TimiCode.ERROR, "生成预览失败"); } - throw new TimiException(TimiCode.ARG_BAD, "该文件类型不支持预览"); } - private boolean notModified(HttpServletRequest req, ContentInfo info) { + private String previewEtag(ContentInfo info, int size) { + return "\"%s-%s-%d\"".formatted( + ThumbnailService.ALGORITHM_VERSION, info.etag().replace("\"", ""), size); + } + + private String contentType(Path thumbnail) { + return thumbnail.getFileName().toString().endsWith(".png") ? "image/png" : "image/jpeg"; + } + + private boolean notModified(HttpServletRequest req, String etag) { String ifNoneMatch = req.getHeader("If-None-Match"); - return ifNoneMatch != null && ifNoneMatch.contains(info.etag()); + return ifNoneMatch != null && ifNoneMatch.contains(etag); } public record ContentInfo(Path path, String mimeType, long size, long modifiedAt, String etag, diff --git a/src/main/java/com/imyeyu/api/modules/system/service/ThumbnailService.java b/src/main/java/com/imyeyu/api/modules/system/service/ThumbnailService.java index c03e38b..dd74ae2 100644 --- a/src/main/java/com/imyeyu/api/modules/system/service/ThumbnailService.java +++ b/src/main/java/com/imyeyu/api/modules/system/service/ThumbnailService.java @@ -16,44 +16,60 @@ import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Iterator; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutionException; /// 缩略图缓存服务。 @Service @RequiredArgsConstructor public class ThumbnailService { - private static final int SIZE = 256; + /// 缩略图算法版本,算法或输出格式变化时递增,使旧缓存和浏览器缓存失效 + public static final String ALGORITHM_VERSION = "v2"; + + /// 允许的缩略图最小边长 + public static final int MIN_SIZE = 32; + + /// 允许的缩略图最大边长 + public static final int MAX_SIZE = 512; + + private static final double JPEG_QUALITY = 0.82; private static final long MAX_PIXELS = 50_000_000L; private final FileStorageService storage; - public Path thumbnail(Path source, String mimeType) { + /// 同一缩略图的并发生成任务,避免平铺列表同时请求同一文件时重复解码 + private final ConcurrentMap> generating = new ConcurrentHashMap<>(); + + /// 校验缩略图尺寸是否在允许范围内。 + public static void requireValidSize(int size) { + if (size < MIN_SIZE || MAX_SIZE < size) { + throw new TimiException(TimiCode.ARG_BAD, "缩略图尺寸必须在 " + MIN_SIZE + "-" + MAX_SIZE + " 之间"); + } + } + + /// 获取缩略图缓存路径,缓存不存在时生成。 + /// + /// @param source 源文件 + /// @param mimeType 源文件 MIME 类型 + /// @param size 缩略图最大边长 + /// @return 缩略图文件 + public Path thumbnail(Path source, String mimeType, int size) { + requireValidSize(size); + String format = outputFormat(mimeType); try { - long modifiedAt = Files.getLastModifiedTime(source).toMillis(); - long size = Files.size(source); - String key = sha256(source.toAbsolutePath() + "|" + modifiedAt + "|" + size + "|" + SIZE); - Path target = storage.thumbnailPath().resolve(key + ".png"); + String key = cacheKey(source, size, format); + Path target = storage.thumbnailPath().resolve(key + "." + format); if (Files.isRegularFile(target)) { return target; } - Files.createDirectories(target.getParent()); - if (mimeType.startsWith("video/")) { - Picture picture; - try { - picture = FrameGrab.getFrameAtSec(source.toFile(), 0); - } catch (Exception e) { - picture = FrameGrab.getFrameAtSec(source.toFile(), 1); - } - BufferedImage image = AWTUtil.toBufferedImage(picture); - ImageIO.write(image, "png", target.toFile()); - } else { - validatePixelCount(source); - Thumbnails.of(source.toFile()).size(SIZE, SIZE).outputFormat("png").toFile(target.toFile()); - } - return target; + return generateOnce(key, target, source, mimeType, size, format); } catch (TimiException e) { throw e; } catch (Exception e) { @@ -61,8 +77,137 @@ public class ThumbnailService { } } - /// 在完整解码前检查图片像素数,避免超大图片耗尽内存。 - private void validatePixelCount(Path source) throws IOException { + private Path generateOnce(String key, Path target, Path source, String mimeType, int size, String format) { + CompletableFuture future = new CompletableFuture<>(); + CompletableFuture running = generating.putIfAbsent(key, future); + if (running != null) { + return await(running); + } + try { + if (Files.isRegularFile(target)) { + future.complete(target); + return target; + } + Path result = generate(source, mimeType, size, format, target); + future.complete(result); + return result; + } catch (Throwable e) { + future.completeExceptionally(e); + if (e instanceof TimiException te) { + throw te; + } + if (e instanceof RuntimeException re) { + throw re; + } + if (e instanceof Error error) { + throw error; + } + throw new TimiException(TimiCode.ERROR, "生成缩略图失败"); + } finally { + generating.remove(key, future); + } + } + + private Path await(CompletableFuture future) { + try { + return future.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TimiException(TimiCode.ERROR, "生成缩略图失败"); + } catch (ExecutionException e) { + Throwable cause = e.getCause(); + if (cause instanceof TimiException te) { + throw te; + } + if (cause instanceof RuntimeException re) { + throw re; + } + if (cause instanceof Error error) { + throw error; + } + throw new TimiException(TimiCode.ERROR, "生成缩略图失败"); + } + } + + private Path generate(Path source, String mimeType, int size, String format, Path target) throws IOException { + Files.createDirectories(target.getParent()); + Path temp = Files.createTempFile(target.getParent(), "thumb-", "." + format); + try { + if (mimeType.startsWith("video/")) { + BufferedImage frame = videoFrame(source); + write(Thumbnails.of(frame), boundedSize(frame.getWidth(), frame.getHeight(), size), format, temp); + } else { + int[] dimensions = imageDimensions(source); + write(Thumbnails.of(source.toFile()).useExifOrientation(true), + boundedSize(dimensions[0], dimensions[1], size), format, temp); + } + move(temp, target); + return target; + } catch (TimiException e) { + throw e; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOException("生成缩略图失败", e); + } finally { + Files.deleteIfExists(temp); + } + } + + /// 小图不放大,避免生成模糊且更大的缩略图。 + private int boundedSize(int width, int height, int size) { + return Math.min(size, Math.max(width, height)); + } + + private void write(Thumbnails.Builder builder, int size, String format, Path target) throws IOException { + builder.size(size, size).outputFormat(format); + if ("jpg".equals(format)) { + builder.outputQuality(JPEG_QUALITY); + } + builder.toFile(target.toFile()); + } + + private BufferedImage videoFrame(Path source) throws Exception { + Picture picture; + try { + picture = FrameGrab.getFrameAtSec(source.toFile(), 0); + } catch (Exception e) { + picture = FrameGrab.getFrameAtSec(source.toFile(), 1); + } + if (picture == null) { + throw new IOException("无法读取视频帧"); + } + return AWTUtil.toBufferedImage(picture); + } + + /// 使用原子移动避免其他请求读到写了一半的缩略图。 + private void move(Path temp, Path target) throws IOException { + try { + Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException e) { + if (Files.isRegularFile(target)) { + return; + } + Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); + } + } + + /// PNG/GIF 源图输出 PNG,其余输出 JPEG(视频帧也使用 JPEG)。 + private String outputFormat(String mimeType) { + return switch (mimeType) { + case "image/png", "image/gif" -> "png"; + default -> "jpg"; + }; + } + + private String cacheKey(Path source, int size, String format) throws IOException { + long modifiedAt = Files.getLastModifiedTime(source).toMillis(); + long fileSize = Files.size(source); + return sha256(ALGORITHM_VERSION + "|" + source.toAbsolutePath() + "|" + modifiedAt + "|" + fileSize + "|" + size + "|" + format); + } + + /// 在完整解码前检查图片像素数,避免超大图片耗尽内存,并返回原始尺寸。 + private int[] imageDimensions(Path source) throws IOException { try (ImageInputStream input = ImageIO.createImageInputStream(source.toFile())) { if (input == null) { throw new IOException("无法读取图片"); @@ -74,10 +219,12 @@ public class ThumbnailService { ImageReader reader = readers.next(); try { reader.setInput(input, true, true); - long pixels = (long) reader.getWidth(0) * reader.getHeight(0); - if (MAX_PIXELS < pixels) { + int width = reader.getWidth(0); + int height = reader.getHeight(0); + if (MAX_PIXELS < (long) width * height) { throw new TimiException(TimiCode.ARG_BAD, "图片像素过大"); } + return new int[]{width, height}; } finally { reader.dispose(); } diff --git a/src/main/java/com/imyeyu/api/modules/system/util/FilePreview.java b/src/main/java/com/imyeyu/api/modules/system/util/FilePreview.java new file mode 100644 index 0000000..0ab4d17 --- /dev/null +++ b/src/main/java/com/imyeyu/api/modules/system/util/FilePreview.java @@ -0,0 +1,25 @@ +package com.imyeyu.api.modules.system.util; + +import java.util.Set; + +/// 文件缩略图预览类型判定。 +/// +/// 只包含当前缩略图生成链路实际支持的图片和视频类型,避免列表把不可预览的文件标记为可预览。 +/// +/// @author 夜雨 +/// @since 2026-11-25 +public final class FilePreview { + + private static final Set MIME_TYPES = Set.of( + "image/png", "image/jpeg", "image/gif", "image/bmp", + "video/mp4", "video/quicktime", "video/webm" + ); + + private FilePreview() { + } + + /// 是否为支持缩略图预览的类型。 + public static boolean supports(String mimeType) { + return MIME_TYPES.contains(mimeType); + } +} diff --git a/src/test/java/com/imyeyu/api/modules/system/service/FileContentServiceTest.java b/src/test/java/com/imyeyu/api/modules/system/service/FileContentServiceTest.java index 25348b0..de48e30 100644 --- a/src/test/java/com/imyeyu/api/modules/system/service/FileContentServiceTest.java +++ b/src/test/java/com/imyeyu/api/modules/system/service/FileContentServiceTest.java @@ -8,6 +8,8 @@ import org.junit.jupiter.api.io.TempDir; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -19,8 +21,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /// 文件内容服务测试。 class FileContentServiceTest { @@ -58,7 +63,36 @@ class FileContentServiceTest { Files.writeString(temp.resolve("a.html"), "", StandardCharsets.UTF_8); assertThrows(TimiException.class, () -> service.preview(new MockHttpServletRequest(), - new MockHttpServletResponse(), "/a.html")); + new MockHttpServletResponse(), "/a.html", 256, null)); + } + + @Test + void rejectsPdfPreview() throws IOException { + Files.writeString(temp.resolve("a.pdf"), "%PDF-1.4", StandardCharsets.UTF_8); + + assertThrows(TimiException.class, () -> service.preview(new MockHttpServletRequest(), + new MockHttpServletResponse(), "/a.pdf", 256, null)); + } + + @Test + void previewsImageWithRequestedSize() throws Exception { + Path source = temp.resolve("a.png"); + ImageIO.write(new BufferedImage(8, 8, BufferedImage.TYPE_INT_RGB), "png", source.toFile()); + Path thumbnail = temp.resolve("thumb.png"); + Files.write(thumbnail, new byte[]{1, 2, 3}); + + ThumbnailService thumbnailService = mock(ThumbnailService.class); + when(thumbnailService.thumbnail(any(), eq("image/png"), eq(128))).thenReturn(thumbnail); + FileContentService service = new FileContentService(FileTestSupport.storage(temp, Map.of()), + thumbnailService, resourceHandler); + MockHttpServletResponse resp = new MockHttpServletResponse(); + + service.preview(new MockHttpServletRequest(), resp, "/a.png", 128, "etag"); + + assertEquals("image/png", resp.getContentType()); + assertEquals(3, resp.getContentAsByteArray().length); + assertTrue(resp.getHeader("ETag").contains("-128")); + assertTrue(resp.getHeader("Cache-Control").contains("immutable")); } @Test diff --git a/src/test/java/com/imyeyu/api/modules/system/service/ThumbnailServiceTest.java b/src/test/java/com/imyeyu/api/modules/system/service/ThumbnailServiceTest.java new file mode 100644 index 0000000..fb8d573 --- /dev/null +++ b/src/test/java/com/imyeyu/api/modules/system/service/ThumbnailServiceTest.java @@ -0,0 +1,97 @@ +package com.imyeyu.api.modules.system.service; + +import com.imyeyu.java.bean.timi.TimiException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// 缩略图缓存服务测试。 +class ThumbnailServiceTest { + + @TempDir + Path temp; + + private ThumbnailService service; + + @BeforeEach + void setUp() throws Exception { + service = new ThumbnailService(FileTestSupport.storage(temp, Map.of())); + } + + @Test + void generatesPngForPngSource() throws Exception { + Path source = temp.resolve("a.png"); + ImageIO.write(new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB), "png", source.toFile()); + + Path thumbnail = service.thumbnail(source, "image/png", 32); + + assertTrue(Files.isRegularFile(thumbnail)); + assertTrue(thumbnail.getFileName().toString().endsWith(".png")); + BufferedImage image = ImageIO.read(thumbnail.toFile()); + assertEquals(32, image.getWidth()); + assertEquals(16, image.getHeight()); + } + + @Test + void generatesJpegForJpegSource() throws Exception { + Path source = temp.resolve("a.jpg"); + ImageIO.write(new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB), "jpg", source.toFile()); + + Path thumbnail = service.thumbnail(source, "image/jpeg", 64); + + assertTrue(Files.isRegularFile(thumbnail)); + assertTrue(thumbnail.getFileName().toString().endsWith(".jpg")); + BufferedImage image = ImageIO.read(thumbnail.toFile()); + assertEquals(64, image.getWidth()); + assertEquals(32, image.getHeight()); + } + + @Test + void reusesCachedThumbnail() throws Exception { + Path source = temp.resolve("a.png"); + ImageIO.write(new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB), "png", source.toFile()); + + Path first = service.thumbnail(source, "image/png", 64); + Path second = service.thumbnail(source, "image/png", 64); + + assertEquals(first, second); + } + + @Test + void cachesEachSizeSeparately() throws Exception { + Path source = temp.resolve("a.png"); + ImageIO.write(new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB), "png", source.toFile()); + + assertNotEquals(service.thumbnail(source, "image/png", 64), + service.thumbnail(source, "image/png", 128)); + } + + @Test + void doesNotUpscaleSmallImage() throws Exception { + Path source = temp.resolve("small.png"); + ImageIO.write(new BufferedImage(20, 10, BufferedImage.TYPE_INT_RGB), "png", source.toFile()); + + Path thumbnail = service.thumbnail(source, "image/png", 256); + + BufferedImage image = ImageIO.read(thumbnail.toFile()); + assertEquals(20, image.getWidth()); + assertEquals(10, image.getHeight()); + } + + @Test + void rejectsInvalidSize() { + assertThrows(TimiException.class, () -> service.thumbnail(temp.resolve("a.png"), "image/png", 8)); + assertThrows(TimiException.class, () -> service.thumbnail(temp.resolve("a.png"), "image/png", 1024)); + } +}