Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support TIFF image previews https://github.com/siyuan-note/siyuan/issues/20764

Daniele2008a95d3e6
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
index 2a0a4315eb..23164965fa 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
@@ -6,7 +6,7 @@
"id": "20200924100744-br924ar",
"title": "Assets",
"type": "doc",
- "updated": "20261018221152"
+ "updated": "20261021003402"
},
"Children": [
{
@@ -132,7 +132,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20201210194734-v2rmiaq",
- "updated": "20261016013311"
+ "updated": "20261021003402"
},
"Children": [
{
@@ -496,6 +496,49 @@
}
]
},
+ {
+ "ID": "20261021003402-19jkwn2",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261021003402-19jkwn2",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "TIFF images"
+ }
+ ],
+ "HeadingLevel": 3
+ },
+ {
+ "ID": "20261021003402-g6tlloh",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021003402-g6tlloh",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "TIFF images (.tif/.tiff) inserted as assets display the first frame. The original file is preserved for download; switching frames is not currently supported. Preview brightness for 16-bit grayscale images follows a valid ImageJ display range, or the actual grayscale range of the first frame when no display range is available."
+ }
+ ]
+ },
+ {
+ "ID": "20261021003402-up66rhq",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021003402-up66rhq",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Previews accept files up to 64 MiB and frames up to 50 million pixels on desktop or 12.5 million pixels on mobile. BigTIFF, floating-point, CMYK, and JPEG-compressed TIFF images are not supported. Unsupported files remain available for download and can be opened in an external application."
+ }
+ ]
+ },
{
"ID": "20261018221152-70wtkp3",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
index 7570985bb1..ba4368b55f 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
@@ -6,7 +6,7 @@
"id": "20200915214115-42b8zma",
"title": "资源文件",
"type": "doc",
- "updated": "20261018221152"
+ "updated": "20261021003402"
},
"Children": [
{
@@ -132,7 +132,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20201210194734-lr6v0s2",
- "updated": "20261016013311"
+ "updated": "20261021003402"
},
"Children": [
{
@@ -496,6 +496,49 @@
}
]
},
+ {
+ "ID": "20261021003402-yv0wj4m",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261021003402-yv0wj4m",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "TIFF 图片"
+ }
+ ],
+ "HeadingLevel": 3
+ },
+ {
+ "ID": "20261021003402-jm550cy",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021003402-jm550cy",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "作为资源文件插入的 TIFF 图片(.tif/.tiff)显示第一帧,下载时仍保留原文件,暂不支持切换帧。16 位灰度图片的预览亮度优先采用有效的 ImageJ 显示范围,未提供显示范围时按第一帧的实际灰度范围调整。"
+ }
+ ]
+ },
+ {
+ "ID": "20261021003402-g9phpj1",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021003402-g9phpj1",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "预览支持不超过 64 MiB 的文件,单帧上限为桌面端 5000 万像素、移动端 1250 万像素。暂不支持 BigTIFF、浮点、CMYK 和 JPEG 压缩的 TIFF 图片。不支持预览的文件仍可下载并使用外部应用打开。"
+ }
+ ]
+ },
{
"ID": "20261018221152-tpxbk0c",
"Type": "NodeHeading",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
index 97898f5c1b..913b1aefc3 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
@@ -6,7 +6,7 @@
"id": "20211226123038-4umgpxy",
"title": "資料文件",
"type": "doc",
- "updated": "20261018221152"
+ "updated": "20261021003402"
},
"Children": [
{
@@ -128,7 +128,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20211226123051-ddr3yub",
- "updated": "20261016013311"
+ "updated": "20261021003402"
},
"Children": [
{
@@ -492,6 +492,49 @@
}
]
},
+ {
+ "ID": "20261021003402-8jtd6hy",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261021003402-8jtd6hy",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "TIFF 圖片"
+ }
+ ],
+ "HeadingLevel": 3
+ },
+ {
+ "ID": "20261021003402-pq0fz6d",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021003402-pq0fz6d",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "作為資源檔案插入的 TIFF 圖片(.tif/.tiff)顯示第一幀,下載時仍保留原始檔案,暫不支援切換幀。16 位元灰階圖片的預覽亮度優先採用有效的 ImageJ 顯示範圍,未提供顯示範圍時依第一幀的實際灰階範圍調整。"
+ }
+ ]
+ },
+ {
+ "ID": "20261021003402-aalgaoz",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021003402-aalgaoz",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "預覽支援不超過 64 MiB 的檔案,單幀上限為桌面端 5000 萬像素、行動端 1250 萬像素。暫不支援 BigTIFF、浮點、CMYK 和 JPEG 壓縮的 TIFF 圖片。不支援預覽的檔案仍可下載並使用外部應用程式開啟。"
+ }
+ ]
+ },
{
"ID": "20261018221152-vfohlz8",
"Type": "NodeHeading",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
index 6d7edb6097..2192836a9c 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-1m5un7l",
"title": "アセット",
"type": "doc",
- "updated": "20261018221152"
+ "updated": "20261021003402"
},
"Children": [
{
@@ -132,7 +132,7 @@
"Properties": {
"ID": "20240530101000-o6et1uc",
"id": "20240530101000-m11xu1w",
- "updated": "20261016202856"
+ "updated": "20261021003402"
},
"Children": [
{
@@ -495,6 +495,49 @@
}
]
},
+ {
+ "ID": "20261021003402-btwcz9x",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20261021003402-btwcz9x",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "TIFF 画像"
+ }
+ ],
+ "HeadingLevel": 3
+ },
+ {
+ "ID": "20261021003402-shhaheh",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021003402-shhaheh",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "アセットとして挿入した TIFF 画像(.tif/.tiff)は最初のフレームを表示します。元のファイルはそのままダウンロードでき、フレームの切り替えには現在対応していません。16 ビットのグレースケール画像は、有効な ImageJ 表示範囲を優先してプレビューの明るさを調整します。表示範囲がない場合は、最初のフレームの実際の階調範囲を使用します。"
+ }
+ ]
+ },
+ {
+ "ID": "20261021003402-ot30fxh",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261021003402-ot30fxh",
+ "updated": "20261021003402"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "プレビューできるファイルは 64 MiB 以下で、1 フレームの上限はデスクトップで 5,000 万画素、モバイルで 1,250 万画素です。BigTIFF、浮動小数点、CMYK、JPEG 圧縮の TIFF 画像には対応していません。プレビューできないファイルもダウンロードして外部アプリで開けます。"
+ }
+ ]
+ },
{
"ID": "20261018221152-s6uge4s",
"Type": "NodeHeading",
diff --git a/app/src/util/image.test.ts b/app/src/util/image.test.ts
index 842700959b..f7c013782a 100644
--- a/app/src/util/image.test.ts
+++ b/app/src/util/image.test.ts
@@ -17,6 +17,8 @@ describe("getCompressURL", () => {
assert.equal(getCompressURL("assets/image.JPG"), "assets/image.JPG?style=thumb");
assert.equal(getCompressURL("assets/image.HeIc"), "assets/image.HeIc?style=thumb");
assert.equal(getCompressURL("assets/image.HEIF"), "assets/image.HEIF?style=thumb");
+ assert.equal(getCompressURL("assets/image.TIF"), "assets/image.TIF?style=thumb");
+ assert.equal(getCompressURL("assets/image.tiff?box=test#preview"), "assets/image.tiff?box=test&style=thumb#preview");
});
it("preserves existing queries and fragments", () => {
@@ -55,6 +57,7 @@ describe("removeCompressURL", () => {
"assets/image.jpg?box=20260816000000-test#preview",
);
assert.equal(removeCompressURL("assets/image.heif?style=thumb#preview"), "assets/image.heif#preview");
+ assert.equal(removeCompressURL("assets/image.tiff?style=thumb&box=test#preview"), "assets/image.tiff?box=test#preview");
});
it("does not change URLs without a thumbnail style", () => {
@@ -84,6 +87,22 @@ describe("HEIF paths", () => {
});
describe("isBrowserRenderableImagePath", () => {
+ it("renders TIFF previews through the internal converter and keeps raw or external TIFFs as links", () => {
+ for (const extension of ["tif", "TIFF"]) {
+ for (const prefix of ["assets/", "/assets/", "./assets/", `${TEST_ORIGIN}/assets/`]) {
+ assert.equal(isBrowserRenderableImagePath(`${prefix}image.${extension}?box=test`, TEST_ORIGIN), true);
+ }
+ for (const url of [
+ `https://example.com/assets/image.${extension}`,
+ `file:///tmp/image.${extension}`,
+ `C:\\notes\\image.${extension}`,
+ `assets/image.${extension}?download=TRUE`,
+ `assets/image.${extension}?%64ownload=true`,
+ ]) {
+ assert.equal(isBrowserRenderableImagePath(url, TEST_ORIGIN), false);
+ }
+ }
+ });
it("renders regular images and same-origin HEIF assets", () => {
assert.equal(isBrowserRenderableImagePath("https://example.com/image.jpg", TEST_ORIGIN), true);
assert.equal(isBrowserRenderableImagePath("assets/image.heic", TEST_ORIGIN), true);
diff --git a/app/src/util/imageURL.ts b/app/src/util/imageURL.ts
index 1b9dcab2c6..909faf199a 100644
--- a/app/src/util/imageURL.ts
+++ b/app/src/util/imageURL.ts
@@ -1,4 +1,4 @@
-const THUMBNAIL_EXTENSIONS = [".png", ".jpg", ".jpeg", ".heic", ".heif"];
+const THUMBNAIL_EXTENSIONS = [".png", ".jpg", ".jpeg", ".heic", ".heif", ".tif", ".tiff"];
const HEIF_EXTENSIONS = [".heic", ".heif"];
const FALLBACK_ORIGIN = "http://siyuan.invalid";
@@ -76,12 +76,20 @@ export const isInternalHEIFPath = (url: string, origin?: string) => {
};
export const isBrowserRenderableImagePath = (url: string, origin?: string) => {
- if (!isHEIFPath(url)) {
+ const path = getDecodedPath(url);
+ if (!isHEIFPath(url) && !path.endsWith(".tif") && !path.endsWith(".tiff")) {
return true;
}
const resolvedURL = resolveHTTPURL(url, origin);
- return isInternalHEIFPath(url, origin) &&
- !resolvedURL?.searchParams.getAll("download").some(value => value.toLowerCase() === "true");
+ if (!resolvedURL) {
+ return false;
+ }
+ try {
+ return decodeURIComponent(resolvedURL.pathname).startsWith("/assets/") &&
+ !resolvedURL.searchParams.getAll("download").some(value => value.toLowerCase() === "true");
+ } catch {
+ return false;
+ }
};
export const getDownloadURL = (url: string) => {
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 7a6c9c5ae2..4d66634432 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -51,6 +51,7 @@ import (
mcpclient "github.com/siyuan-note/siyuan/kernel/mcp/client"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/server/proxy"
+ "github.com/siyuan-note/siyuan/kernel/tiffpreview"
"github.com/siyuan-note/siyuan/kernel/util"
"github.com/soheilhy/cmux"
@@ -1190,17 +1191,25 @@ func serveAssets(ginServer *gin.Engine) {
return
}
+ if shouldTranscodeTIFF(context, p) {
+ if !acquireImagePreviewSlot(context) {
+ return
+ }
+ defer releaseImagePreviewSlot()
+ serveTIFFPreview(context, p)
+ return
+ }
if heif.IsPath(p) {
addHEIFVaryAccept(context)
if shouldTranscodeHEIF(context) {
- if !acquireHEIFPreviewSlot(context) {
+ if !acquireImagePreviewSlot(context) {
return
}
- defer releaseHEIFPreviewSlot()
+ defer releaseImagePreviewSlot()
serveHEIFPreview(context, p)
return
}
- } else {
+ } else if !tiffpreview.IsPath(p) {
if serveThumbnail(context, p, requestPath) || serveSVG(context, p) {
return
}
@@ -1236,19 +1245,24 @@ func serveAssets(ginServer *gin.Engine) {
return
}
transcodeHEIF := heif.IsPath(p) && shouldTranscodeHEIF(context)
+ transcodeTIFF := shouldTranscodeTIFF(context, p)
if heif.IsPath(p) {
addHEIFVaryAccept(context)
}
- if transcodeHEIF {
- if !acquireHEIFPreviewSlot(context) {
+ if transcodeHEIF || transcodeTIFF {
+ if !acquireImagePreviewSlot(context) {
return
}
- defer releaseHEIFPreviewSlot()
+ defer releaseImagePreviewSlot()
}
// 加密笔记本的历史是密文(.sy/assets/AV),需先解密再输出
if serveEncryptedHistory(context, p) {
return
}
+ if transcodeTIFF {
+ servePlainTIFFPreview(context, p, false)
+ return
+ }
if transcodeHEIF {
servePlainHEIFPreview(context, p, "", false)
return
@@ -1258,13 +1272,13 @@ func serveAssets(ginServer *gin.Engine) {
})
}
-var heifPreviewSlots = make(chan struct{}, 1)
+var imagePreviewSlots = make(chan struct{}, 1)
-func acquireHEIFPreviewSlot(c *gin.Context) bool {
+func acquireImagePreviewSlot(c *gin.Context) bool {
timer := time.NewTimer(30 * time.Second)
defer timer.Stop()
select {
- case heifPreviewSlots <- struct{}{}:
+ case imagePreviewSlots <- struct{}{}:
return true
case <-c.Request.Context().Done():
return false
@@ -1274,8 +1288,8 @@ func acquireHEIFPreviewSlot(c *gin.Context) bool {
}
}
-func releaseHEIFPreviewSlot() {
- <-heifPreviewSlots
+func releaseImagePreviewSlot() {
+ <-imagePreviewSlots
}
func setEncryptedAssetCacheHeaders(c *gin.Context) {
@@ -1611,18 +1625,21 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
defer model.ReleaseBoxReadLock(boxID)
heifRequest := heif.IsPath(absPath) && !strings.EqualFold(context.Query("download"), "true")
transcodeHEIF := heif.IsPath(absPath) && shouldTranscodeHEIF(context)
+ transcodeTIFF := shouldTranscodeTIFF(context, absPath)
if heifRequest && rejectOversizedHEIF(context, absPath, true) {
return true
}
var ciphertext []byte
var readErr error
- if heifRequest {
+ if transcodeTIFF {
+ ciphertext, readErr = tiffpreview.ReadFileLimited(absPath, int64(tiffpreview.MaxInputBytes)+2*1024*1024)
+ } else if heifRequest {
ciphertext, readErr = heif.ReadFileLimited(absPath, int64(heif.MaxInputBytes)+2*1024*1024)
} else {
ciphertext, readErr = os.ReadFile(absPath)
}
if readErr != nil {
- if errors.Is(readErr, heif.ErrInputTooLarge) {
+ if errors.Is(readErr, heif.ErrInputTooLarge) || errors.Is(readErr, tiffpreview.ErrInputTooLarge) {
context.Status(http.StatusRequestEntityTooLarge)
} else {
context.Status(http.StatusNotFound)
@@ -1655,6 +1672,10 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
return true
}
defer clear(plain)
+ if transcodeTIFF {
+ writeTIFFPreview(context, plain, true)
+ return true
+ }
if heifRequest && len(plain) > heif.MaxInputBytes {
context.Status(http.StatusRequestEntityTooLarge)
return true
@@ -1727,14 +1748,15 @@ func serveRepoDiff(ginServer *gin.Engine) {
return
}
transcodeHEIF := heif.IsPath(requestPath) && shouldTranscodeHEIF(context)
+ transcodeTIFF := shouldTranscodeTIFF(context, requestPath)
if heif.IsPath(requestPath) {
addHEIFVaryAccept(context)
}
- if transcodeHEIF {
- if !acquireHEIFPreviewSlot(context) {
+ if transcodeHEIF || transcodeTIFF {
+ if !acquireImagePreviewSlot(context) {
return
}
- defer releaseHEIFPreviewSlot()
+ defer releaseImagePreviewSlot()
}
// 从路径提取 boxID,加密笔记本已锁定时拒绝访问(锁定后 repo 预览解密文件仍存在磁盘上)
parts := strings.SplitN(strings.TrimPrefix(requestPath, "/"), "/", 2)
@@ -1761,6 +1783,10 @@ func serveRepoDiff(ginServer *gin.Engine) {
context.Status(http.StatusUnauthorized)
return
}
+ if transcodeTIFF {
+ servePlainTIFFPreview(context, p, encryptedBoxID != "")
+ return
+ }
if transcodeHEIF {
servePlainHEIFPreview(context, p, encryptedBoxID, encryptedBoxID != "")
return
diff --git a/kernel/server/serve_tiff.go b/kernel/server/serve_tiff.go
new file mode 100644
index 0000000000..77c9268317
--- /dev/null
+++ b/kernel/server/serve_tiff.go
@@ -0,0 +1,122 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package server
+
+import (
+ "errors"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/tiffpreview"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func shouldTranscodeTIFF(c *gin.Context, path string) bool {
+ return tiffpreview.IsPath(path) && !strings.EqualFold(c.Query("download"), "true")
+}
+
+// serveTIFFPreview 在资源鉴权后读取首帧,加密笔记本持有操作租约和读锁直至输出结束。
+func serveTIFFPreview(c *gin.Context, path string) {
+ boxID := model.ExtractBoxIDFromAssetsPath(path)
+ encrypted := boxID != "" && model.IsEncryptedBox(boxID)
+ var dek []byte
+ if encrypted {
+ setEncryptedAssetCacheHeaders(c)
+ if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {
+ c.Status(http.StatusForbidden)
+ return
+ }
+ defer model.ReleaseEncryptedBoxOperation(boxID)
+ model.HoldBoxReadLock(boxID)
+ defer model.ReleaseBoxReadLock(boxID)
+ var err error
+ dek, err = model.GetDEKIfUnlocked(boxID)
+ if err != nil {
+ c.Status(http.StatusForbidden)
+ return
+ }
+ defer clear(dek)
+ }
+ limit := int64(tiffpreview.MaxInputBytes)
+ if encrypted {
+ limit += 2 * 1024 * 1024
+ }
+ source, err := tiffpreview.ReadFileLimited(path, limit)
+ if err != nil {
+ tiffPreviewError(c, err)
+ return
+ }
+ if encrypted {
+ decrypted, decErr := model.DecryptAsset(boxID, filepath.Base(path), dek, source)
+ clear(source)
+ if decErr != nil {
+ c.Status(http.StatusInternalServerError)
+ return
+ }
+ source = decrypted
+ defer clear(source)
+ }
+ writeTIFFPreview(c, source, encrypted)
+}
+
+// servePlainTIFFPreview 处理普通历史文件或已解密的快照预览;加密来源不写入预览缓存。
+func servePlainTIFFPreview(c *gin.Context, path string, encrypted bool) {
+ source, err := tiffpreview.ReadFileLimited(path, tiffpreview.MaxInputBytes)
+ if err != nil {
+ tiffPreviewError(c, err)
+ return
+ }
+ if encrypted {
+ defer clear(source)
+ }
+ writeTIFFPreview(c, source, encrypted)
+}
+
+func writeTIFFPreview(c *gin.Context, source []byte, encrypted bool) {
+ result, err := tiffpreview.GetOrCreate(c.Request.Context(), source,
+ filepath.Join(util.TempDir, "assets-cache", "tiff"), c.Query("style") == "thumb", encrypted)
+ if err != nil {
+ tiffPreviewError(c, err)
+ return
+ }
+ c.Header("X-Content-Type-Options", "nosniff")
+ c.Header("Content-Type", "image/png")
+ if encrypted {
+ setEncryptedAssetCacheHeaders(c)
+ defer clear(result.Data)
+ } else {
+ c.Header("ETag", result.ETag)
+ if c.GetHeader("If-None-Match") == result.ETag {
+ c.Status(http.StatusNotModified)
+ return
+ }
+ }
+ if result.Path != "" {
+ http.ServeFile(c.Writer, c.Request, result.Path)
+ return
+ }
+ c.Data(http.StatusOK, "image/png", result.Data)
+}
+
+func tiffPreviewError(c *gin.Context, err error) {
+ if errors.Is(err, c.Request.Context().Err()) {
+ return
+ }
+ status := http.StatusUnprocessableEntity
+ if errors.Is(err, tiffpreview.ErrInputTooLarge) || errors.Is(err, tiffpreview.ErrImageTooLarge) {
+ status = http.StatusRequestEntityTooLarge
+ } else if os.IsNotExist(err) {
+ status = http.StatusNotFound
+ }
+ c.Status(status)
+}
diff --git a/kernel/server/serve_tiff_encrypted_test.go b/kernel/server/serve_tiff_encrypted_test.go
new file mode 100644
index 0000000000..6356680686
--- /dev/null
+++ b/kernel/server/serve_tiff_encrypted_test.go
@@ -0,0 +1,176 @@
+//go:build (sqlcipher || libsqlcipher) && cgo
+
+package server
+
+import (
+ "bytes"
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type tiffBlockedWriter struct {
+ *httptest.ResponseRecorder
+ ready, release chan struct{}
+ once sync.Once
+}
+
+func (w *tiffBlockedWriter) Write(data []byte) (int, error) {
+ w.once.Do(func() { close(w.ready) })
+ <-w.release
+ return w.ResponseRecorder.Write(data)
+}
+
+func TestServeTIFFEncryptedLifecycle(t *testing.T) {
+ const helper = "SIYUAN_TEST_TIFF_ENCRYPTED"
+ if os.Getenv(helper) != "1" {
+ // 独立进程隔离数据库和密钥状态,不访问运行中的工作空间。
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+ command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestServeTIFFEncryptedLifecycle$", "-test.v")
+ command.Env = append(os.Environ(), helper+"=1")
+ if output, err := command.CombinedOutput(); err != nil {
+ t.Fatalf("encrypted TIFF subprocess: %v\n%s", err, output)
+ }
+ return
+ }
+ root := t.TempDir()
+ util.WorkspaceDir = root
+ util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir = filepath.Join(root, "data"), filepath.Join(root, "temp"), filepath.Join(root, "conf"), filepath.Join(root, "history")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath, util.HistoryDBPath = filepath.Join(util.TempDir, util.DBName), filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(util.TempDir, "asset_content.db"), filepath.Join(util.TempDir, "blocktree.db")
+ for _, directory := range []string{util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir} {
+ if err := os.MkdirAll(directory, 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ model.Conf = model.NewAppConf()
+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ model.Conf.FileTree.Store(conf.NewFileTree())
+ model.Conf.Sync.Store(conf.NewSync())
+ model.Conf.System.Store(conf.NewSystem())
+ model.Conf.Editor.Store(conf.NewEditor())
+ model.Conf.Search.Store(conf.NewSearch())
+ model.Conf.Export.Store(conf.NewExport())
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ defer sql.CloseDatabase()
+ const password = "TIFF preview regression"
+ if err := model.EnableEncryptedNotebook(password); err != nil {
+ t.Fatal(err)
+ }
+ boxID, err := model.CreateEncryptedBox("TIFF previews", password)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dek, err := model.GetDEK(boxID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ source := tiffSource(t)
+ ciphertext, err := model.EncryptAsset(boxID, "preview.tif", "original.tif", dek, source)
+ clear(dek)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assetPath := filepath.Join(util.DataDir, boxID, "assets", "preview.tif")
+ historyPath := filepath.Join(util.HistoryDir, "2026-10-21-120000-update", boxID, "assets", "preview.tif")
+ writeTIFFTestFile(t, assetPath, ciphertext)
+ writeTIFFTestFile(t, historyPath, ciphertext)
+ writeTIFFTestFile(t, filepath.Join(util.TempDir, "repo", "diff", boxID, "assets", "preview.tif"), source)
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator); c.Next() })
+ serveAssets(engine)
+ serveRepoDiff(engine)
+ urls := []string{
+ "/assets/preview.tif?box=" + boxID,
+ "/history/2026-10-21-120000-update/" + boxID + "/assets/preview.tif?box=" + boxID,
+ "/repo/diff/" + boxID + "/assets/preview.tif?box=" + boxID,
+ }
+ for _, url := range urls {
+ for _, query := range []string{"", "&style=thumb", "&download=true"} {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, url+query, nil))
+ if query == "&download=true" {
+ if recorder.Code != http.StatusOK || !bytes.Equal(recorder.Body.Bytes(), source) {
+ t.Fatalf("encrypted original download %s = %d", url, recorder.Code)
+ }
+ } else {
+ assertTIFFPreview(t, recorder)
+ }
+ if recorder.Header().Get("Cache-Control") != "private, no-store" || recorder.Header().Get("ETag") != "" {
+ t.Fatalf("encrypted response may be cached: %v", recorder.Header())
+ }
+ }
+ }
+ if _, err := os.Stat(filepath.Join(util.TempDir, "assets-cache", "tiff")); !os.IsNotExist(err) {
+ t.Fatal("encrypted TIFF preview leaked to disk cache")
+ }
+ for _, path := range []string{assetPath, historyPath} {
+ before, _ := os.ReadFile(path)
+ if !bytes.Equal(before, ciphertext) {
+ t.Fatal("preview modified ciphertext")
+ }
+ corrupt := bytes.Clone(ciphertext)
+ corrupt[len(corrupt)-1] ^= 1
+ writeTIFFTestFile(t, path, corrupt)
+ }
+ for _, url := range urls[:2] {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, url, nil))
+ if recorder.Code != http.StatusInternalServerError {
+ t.Fatalf("authentication failure %s = %d", url, recorder.Code)
+ }
+ }
+ writeTIFFTestFile(t, assetPath, ciphertext)
+ writeTIFFTestFile(t, historyPath, ciphertext)
+ writer := &tiffBlockedWriter{ResponseRecorder: httptest.NewRecorder(), ready: make(chan struct{}), release: make(chan struct{})}
+ var release sync.Once
+ defer release.Do(func() { close(writer.release) })
+ done := make(chan struct{})
+ go func() { engine.ServeHTTP(writer, httptest.NewRequest(http.MethodGet, urls[0], nil)); close(done) }()
+ select {
+ case <-writer.ready:
+ case <-time.After(10 * time.Second):
+ t.Fatal("preview never reached response writer")
+ }
+ locked := make(chan struct{})
+ go func() { model.LockBox(boxID); close(locked) }()
+ early := false
+ select {
+ case <-locked:
+ early = true
+ case <-time.After(300 * time.Millisecond):
+ }
+ release.Do(func() { close(writer.release) })
+ <-done
+ select {
+ case <-locked:
+ case <-time.After(10 * time.Second):
+ t.Fatal("notebook lock did not drain preview request")
+ }
+ if early {
+ t.Fatal("preview lease ended before response serialization")
+ }
+ for _, url := range urls {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, url, nil))
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("locked encrypted preview %s = %d", url, recorder.Code)
+ }
+ }
+}
diff --git a/kernel/server/serve_tiff_test.go b/kernel/server/serve_tiff_test.go
new file mode 100644
index 0000000000..734353dda2
--- /dev/null
+++ b/kernel/server/serve_tiff_test.go
@@ -0,0 +1,177 @@
+package server
+
+import (
+ "bytes"
+ "image"
+ "image/color"
+ "image/png"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/tiffpreview"
+ "github.com/siyuan-note/siyuan/kernel/util"
+ "golang.org/x/image/tiff"
+)
+
+func tiffSource(t *testing.T) []byte {
+ t.Helper()
+ img := image.NewGray16(image.Rect(0, 0, 3, 1))
+ for x, value := range []uint16{120, 1960, 3800} {
+ img.SetGray16(x, 0, color.Gray16{Y: value})
+ }
+ var buffer bytes.Buffer
+ if err := tiff.Encode(&buffer, img, &tiff.Options{Compression: tiff.Deflate}); err != nil {
+ t.Fatal(err)
+ }
+ return buffer.Bytes()
+}
+
+func tiffTestEngine(t *testing.T) *gin.Engine {
+ t.Helper()
+ originalData, originalTemp, originalHistory, originalConf := util.DataDir, util.TempDir, util.HistoryDir, model.Conf
+ originalWorkspace := util.WorkspaceDir
+ root := t.TempDir()
+ util.WorkspaceDir = root
+ util.DataDir, util.TempDir, util.HistoryDir = filepath.Join(root, "data"), filepath.Join(root, "temp"), filepath.Join(root, "history")
+ model.Conf = model.NewAppConf()
+ t.Cleanup(func() {
+ util.DataDir, util.TempDir, util.HistoryDir, model.Conf = originalData, originalTemp, originalHistory, originalConf
+ util.WorkspaceDir = originalWorkspace
+ })
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) {
+ c.Set(model.RoleContextKey, model.RoleAdministrator)
+ c.Next()
+ })
+ serveAssets(engine)
+ serveRepoDiff(engine)
+ return engine
+}
+
+func writeTIFFTestFile(t *testing.T, path string, data []byte) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, data, 0600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func assertTIFFPreview(t *testing.T, recorder *httptest.ResponseRecorder) {
+ t.Helper()
+ if recorder.Code != http.StatusOK || recorder.Header().Get("Content-Type") != "image/png" {
+ t.Fatalf("preview returned %d, %s", recorder.Code, recorder.Header().Get("Content-Type"))
+ }
+ img, err := png.Decode(bytes.NewReader(recorder.Body.Bytes()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if img.Bounds() != image.Rect(0, 0, 3, 1) {
+ t.Fatalf("preview bounds = %v", img.Bounds())
+ }
+ if got := color.GrayModel.Convert(img.At(2, 0)).(color.Gray).Y; got != 255 {
+ t.Fatalf("16-bit preview remains dark: brightest pixel = %d", got)
+ }
+}
+
+func TestServeTIFFRoutesPreviewAndOriginalDownload(t *testing.T) {
+ engine := tiffTestEngine(t)
+ // 超过通用缩略图阈值,验证 download 与 style=thumb 同时出现时仍下载原件。
+ source := append(tiffSource(t), make([]byte, 1024*1024)...)
+ for _, test := range []struct{ url, path string }{
+ {"/assets/image.TIF", filepath.Join(util.DataDir, "assets", "image.TIF")},
+ {"/history/2026-10-21-120000-update/assets/image.tiff", filepath.Join(util.HistoryDir, "2026-10-21-120000-update", "assets", "image.tiff")},
+ {"/repo/diff/assets/image.tif", filepath.Join(util.TempDir, "repo", "diff", "assets", "image.tif")},
+ } {
+ t.Run(test.url, func(t *testing.T) {
+ writeTIFFTestFile(t, test.path, source)
+ var etag string
+ for _, query := range []string{"", "?style=thumb"} {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.url+query, nil))
+ assertTIFFPreview(t, recorder)
+ if recorder.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatal("missing nosniff header")
+ }
+ if query == "" {
+ etag = recorder.Header().Get("ETag")
+ }
+ }
+ if etag == "" {
+ t.Fatal("missing preview ETag")
+ }
+ request := httptest.NewRequest(http.MethodGet, test.url, nil)
+ request.Header.Set("If-None-Match", etag)
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request)
+ if recorder.Code != http.StatusNotModified {
+ t.Fatalf("cached preview = %d", recorder.Code)
+ }
+ for _, query := range []string{"?download=true", "?style=thumb&download=TRUE"} {
+ recorder = httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.url+query, nil))
+ if recorder.Code != http.StatusOK || !bytes.Equal(recorder.Body.Bytes(), source) {
+ t.Fatalf("original download changed: status %d", recorder.Code)
+ }
+ }
+ preserved, err := os.ReadFile(test.path)
+ if err != nil || !bytes.Equal(preserved, source) {
+ t.Fatal("preview rewrote the source TIFF")
+ }
+ })
+ }
+}
+
+func TestServeTIFFRejectsCorruptAndOversizedSources(t *testing.T) {
+ engine := tiffTestEngine(t)
+ path := filepath.Join(util.DataDir, "assets", "bad.tif")
+ writeTIFFTestFile(t, path, []byte("corrupt TIFF"))
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/assets/bad.tif", nil))
+ if recorder.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("corrupt preview = %d", recorder.Code)
+ }
+ file, err := os.OpenFile(path, os.O_WRONLY, 0600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = file.Truncate(tiffpreview.MaxInputBytes + 1)
+ file.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ recorder = httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/assets/bad.tif", nil))
+ if recorder.Code != http.StatusRequestEntityTooLarge {
+ t.Fatalf("oversized preview = %d", recorder.Code)
+ }
+}
+
+func TestServeTIFFLockedNotebook(t *testing.T) {
+ engine := tiffTestEngine(t)
+ const boxID = "20261021000000-tifflck"
+ writeTIFFTestFile(t, filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json"), []byte(`{"encrypted":true}`))
+ writeTIFFTestFile(t, filepath.Join(util.DataDir, boxID, "assets", "image.tif"), []byte("SYAE"))
+ writeTIFFTestFile(t, filepath.Join(util.HistoryDir, "2026-10-21-120000-update", boxID, "assets", "image.tif"), []byte("SYAE"))
+ writeTIFFTestFile(t, filepath.Join(util.TempDir, "repo", "diff", boxID, "assets", "image.tif"), tiffSource(t))
+ for _, url := range []string{
+ "/assets/image.tif?box=" + boxID,
+ "/history/2026-10-21-120000-update/" + boxID + "/assets/image.tif",
+ "/repo/diff/" + boxID + "/assets/image.tif",
+ } {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, url, nil))
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("locked notebook GET %s = %d", url, recorder.Code)
+ }
+ }
+ if _, err := os.Stat(filepath.Join(util.TempDir, "assets-cache", "tiff")); !os.IsNotExist(err) {
+ t.Fatal("locked notebook created a preview cache")
+ }
+}
diff --git a/kernel/tiffpreview/cache.go b/kernel/tiffpreview/cache.go
new file mode 100644
index 0000000000..e1341d60a5
--- /dev/null
+++ b/kernel/tiffpreview/cache.go
@@ -0,0 +1,117 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package tiffpreview
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "sync"
+ "time"
+)
+
+type Result struct {
+ Data []byte
+ Path string
+ ETag string
+}
+
+var cacheLock sync.Mutex
+
+// GetOrCreate 用内容摘要隔离预览及缩略图缓存;加密资源只返回请求内存中的 PNG。
+func GetOrCreate(ctx context.Context, source []byte, directory string, thumbnail, encrypted bool) (Result, error) {
+ if encrypted {
+ data, err := Convert(ctx, source, thumbnail)
+ return Result{Data: data}, err
+ }
+ if len(source) > MaxInputBytes {
+ return Result{}, ErrInputTooLarge
+ }
+ if err := ctx.Err(); err != nil {
+ return Result{}, err
+ }
+ hash := sha256.New()
+ hash.Write([]byte("tiff-first-frame-png-v1"))
+ if thumbnail {
+ hash.Write([]byte{1})
+ }
+ hash.Write(source)
+ digest := hex.EncodeToString(hash.Sum(nil))
+ result := Result{ETag: `"tiff-` + digest + `"`}
+ cachePath := filepath.Join(directory, digest+".png")
+ cacheLock.Lock()
+ defer cacheLock.Unlock()
+ if err := ctx.Err(); err != nil {
+ return Result{}, err
+ }
+ if info, err := os.Stat(cachePath); err == nil && info.Mode().IsRegular() && info.Size() > 0 {
+ _ = os.Chtimes(cachePath, time.Now(), time.Now())
+ result.Path = cachePath
+ return result, nil
+ }
+ data, err := Convert(ctx, source, thumbnail)
+ if err != nil {
+ return Result{}, err
+ }
+ result.Data = data
+ if err = os.MkdirAll(directory, 0700); err != nil {
+ return result, nil
+ }
+ file, err := os.CreateTemp(directory, ".tiff-*.tmp")
+ if err != nil {
+ return result, nil
+ }
+ defer os.Remove(file.Name())
+ _, writeErr := file.Write(data)
+ closeErr := file.Close()
+ if writeErr != nil || closeErr != nil || ctx.Err() != nil {
+ return result, ctx.Err()
+ }
+ if err = os.Rename(file.Name(), cachePath); err != nil {
+ return result, nil
+ }
+ pruneCache(directory, cachePath)
+ result.Data, result.Path = nil, cachePath
+ return result, nil
+}
+
+func pruneCache(directory, keep string) {
+ const maxBytes = 512 * 1024 * 1024
+ type entry struct {
+ path string
+ info fs.FileInfo
+ }
+ var entries []entry
+ var total int64
+ files, _ := os.ReadDir(directory)
+ for _, file := range files {
+ if filepath.Ext(file.Name()) != ".png" {
+ continue
+ }
+ info, err := file.Info()
+ if err != nil || !info.Mode().IsRegular() {
+ continue
+ }
+ total += info.Size()
+ entries = append(entries, entry{filepath.Join(directory, file.Name()), info})
+ }
+ sort.Slice(entries, func(i, j int) bool { return entries[i].info.ModTime().Before(entries[j].info.ModTime()) })
+ for _, file := range entries {
+ if total <= maxBytes {
+ break
+ }
+ if file.path != keep && os.Remove(file.path) == nil {
+ total -= file.info.Size()
+ }
+ }
+}
diff --git a/kernel/tiffpreview/cache_test.go b/kernel/tiffpreview/cache_test.go
new file mode 100644
index 0000000000..95a89db68a
--- /dev/null
+++ b/kernel/tiffpreview/cache_test.go
@@ -0,0 +1,68 @@
+package tiffpreview
+
+import (
+ "bytes"
+ "context"
+ "image"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "golang.org/x/image/tiff"
+)
+
+func TestCacheSeparatesContentAndThumbnail(t *testing.T) {
+ root := t.TempDir()
+ source := encodeTIFF(t, image.NewGray(image.Rect(0, 0, 1040, 520)), tiff.Deflate)
+ first, err := GetOrCreate(context.Background(), source, root, false, false)
+ if err != nil || first.Path == "" || first.ETag == "" {
+ t.Fatalf("create cache = %+v, %v", first, err)
+ }
+ again, err := GetOrCreate(context.Background(), source, root, false, false)
+ if err != nil || again.Path != first.Path || again.ETag != first.ETag {
+ t.Fatalf("repeat cache = %+v, %v", again, err)
+ }
+ thumb, err := GetOrCreate(context.Background(), source, root, true, false)
+ if err != nil || thumb.Path == first.Path || thumb.ETag == first.ETag {
+ t.Fatalf("thumbnail cache = %+v, %v", thumb, err)
+ }
+ changed := bytes.Clone(source)
+ changed = append(changed, 0)
+ updated, err := GetOrCreate(context.Background(), changed, root, false, false)
+ if err != nil || updated.Path == first.Path || updated.ETag == first.ETag {
+ t.Fatalf("updated content cache = %+v, %v", updated, err)
+ }
+}
+
+func TestEncryptedPreviewNeverReadsOrWritesDiskCache(t *testing.T) {
+ root := t.TempDir()
+ source := encodeTIFF(t, image.NewGray(image.Rect(0, 0, 3, 2)), tiff.Deflate)
+ ordinary, err := GetOrCreate(context.Background(), source, root, false, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(ordinary.Path, []byte("poisoned disk cache"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ for _, directory := range []string{root, filepath.Join(root, "encrypted-only")} {
+ result, err := GetOrCreate(context.Background(), source, directory, false, true)
+ if err != nil || result.Path != "" || result.ETag != "" || !bytes.HasPrefix(result.Data, []byte("\x89PNG")) {
+ t.Fatalf("encrypted preview = %+v, %v", result, err)
+ }
+ }
+ if _, err := os.Stat(filepath.Join(root, "encrypted-only")); !os.IsNotExist(err) {
+ t.Fatal("encrypted preview created a disk cache")
+ }
+}
+
+func TestCacheWriteFailureStillReturnsPreview(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "file")
+ if err := os.WriteFile(path, []byte("file"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ source := encodeTIFF(t, image.NewGray(image.Rect(0, 0, 1, 1)), tiff.Uncompressed)
+ result, err := GetOrCreate(context.Background(), source, path, false, false)
+ if err != nil || len(result.Data) == 0 || result.Path != "" {
+ t.Fatalf("uncacheable preview = %+v, %v", result, err)
+ }
+}
diff --git a/kernel/tiffpreview/convert.go b/kernel/tiffpreview/convert.go
new file mode 100644
index 0000000000..3122d0964f
--- /dev/null
+++ b/kernel/tiffpreview/convert.go
@@ -0,0 +1,283 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package tiffpreview
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "image"
+ "image/png"
+ "io"
+ "math"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+
+ "github.com/disintegration/imaging"
+ "golang.org/x/image/tiff"
+)
+
+const MaxInputBytes = 64 * 1024 * 1024
+
+var (
+ ErrInputTooLarge = errors.New("TIFF image exceeds the input size limit")
+ ErrImageTooLarge = errors.New("TIFF image exceeds the dimension limit")
+)
+
+func IsPath(path string) bool {
+ path = strings.SplitN(strings.SplitN(path, "?", 2)[0], "#", 2)[0]
+ ext := strings.ToLower(filepath.Ext(path))
+ return ext == ".tif" || ext == ".tiff"
+}
+
+func ReadFileLimited(path string, limit int64) ([]byte, error) {
+ file, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ data, err := io.ReadAll(io.LimitReader(file, limit+1))
+ if err == nil && int64(len(data)) > limit {
+ clear(data)
+ return nil, ErrInputTooLarge
+ }
+ return data, err
+}
+
+type contextReader struct {
+ *bytes.Reader
+ ctx context.Context
+}
+
+func (r contextReader) ReadAt(p []byte, offset int64) (int, error) {
+ if err := r.ctx.Err(); err != nil {
+ return 0, err
+ }
+ return r.Reader.ReadAt(p, offset)
+}
+
+func (r contextReader) Read(p []byte) (int, error) {
+ if err := r.ctx.Err(); err != nil {
+ return 0, err
+ }
+ return r.Reader.Read(p)
+}
+
+type contextWriter struct {
+ *bytes.Buffer
+ ctx context.Context
+}
+
+func (w contextWriter) Write(p []byte) (int, error) {
+ if err := w.ctx.Err(); err != nil {
+ return 0, err
+ }
+ return w.Buffer.Write(p)
+}
+
+// Convert 仅解码首个 IFD,生成浏览器可显示的 PNG;原件及后续帧保持不变。
+// 16 位灰度优先采用 ImageJ 显示范围,否则按首帧的实际灰度范围拉伸。
+func Convert(ctx context.Context, source []byte, thumbnail bool) (output []byte, err error) {
+ if len(source) > MaxInputBytes {
+ return nil, ErrInputTooLarge
+ }
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
+ defer func() {
+ if recovered := recover(); recovered != nil {
+ output = nil
+ err = fmt.Errorf("decode TIFF preview: %v", recovered)
+ }
+ }()
+ reader := contextReader{bytes.NewReader(source), ctx}
+ config, err := tiff.DecodeConfig(reader)
+ if err != nil {
+ return nil, err
+ }
+ maxPixels := 50_000_000
+ if runtime.GOOS == "android" || runtime.GOOS == "ios" {
+ maxPixels = 12_500_000
+ }
+ if config.Width < 1 || config.Height < 1 || config.Width > 65535 || config.Height > 65535 ||
+ config.Width > maxPixels/config.Height {
+ return nil, ErrImageTooLarge
+ }
+ reader.Seek(0, io.SeekStart)
+ img, err := tiff.Decode(reader)
+ if err != nil {
+ return nil, err
+ }
+ defer clearPixels(img)
+ metadata := readMetadata(source)
+ if gray, ok := img.(*image.Gray16); ok {
+ img, err = displayGray(ctx, gray, metadata)
+ if err != nil {
+ return nil, err
+ }
+ defer clearPixels(img)
+ }
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
+ switch metadata.orientation {
+ case 2:
+ img = imaging.FlipH(img)
+ case 3:
+ img = imaging.Rotate180(img)
+ case 4:
+ img = imaging.FlipV(img)
+ case 5:
+ img = imaging.Transpose(img)
+ case 6:
+ img = imaging.Rotate270(img)
+ case 7:
+ img = imaging.Transverse(img)
+ case 8:
+ img = imaging.Rotate90(img)
+ }
+ defer clearPixels(img)
+ if thumbnail && img.Bounds().Dx() > 520 {
+ img = imaging.Resize(img, 520, 0, imaging.Lanczos)
+ defer clearPixels(img)
+ }
+ var buffer bytes.Buffer
+ if err = png.Encode(contextWriter{&buffer, ctx}, img); err != nil {
+ clear(buffer.Bytes())
+ return nil, err
+ }
+ return buffer.Bytes(), nil
+}
+
+func clearPixels(img image.Image) {
+ switch value := img.(type) {
+ case *image.Gray:
+ clear(value.Pix)
+ case *image.Gray16:
+ clear(value.Pix)
+ case *image.RGBA:
+ clear(value.Pix)
+ case *image.RGBA64:
+ clear(value.Pix)
+ case *image.NRGBA:
+ clear(value.Pix)
+ case *image.NRGBA64:
+ clear(value.Pix)
+ case *image.Paletted:
+ clear(value.Pix)
+ }
+}
+
+type metadata struct {
+ orientation int
+ min, max float64
+ hasRange bool
+}
+
+// readMetadata 只读取首个经典 TIFF IFD 中有界的方向和 ImageJ 显示范围,不遍历图像栈。
+func readMetadata(source []byte) (result metadata) {
+ if len(source) < 8 {
+ return
+ }
+ var order binary.ByteOrder = binary.LittleEndian
+ if string(source[:2]) == "MM" {
+ order = binary.BigEndian
+ }
+ offset := uint64(order.Uint32(source[4:8]))
+ if offset+2 > uint64(len(source)) {
+ return
+ }
+ count := uint64(order.Uint16(source[offset : offset+2]))
+ whiteIsZero := false
+ for i := uint64(0); i < count; i++ {
+ position := offset + 2 + 12*i
+ if position+12 > uint64(len(source)) {
+ return
+ }
+ entry := source[position : position+12]
+ tag, kind, size := order.Uint16(entry), order.Uint16(entry[2:]), uint64(order.Uint32(entry[4:]))
+ if tag == 262 && kind == 3 && size == 1 {
+ whiteIsZero = order.Uint16(entry[8:]) == 0
+ }
+ if tag == 274 && kind == 3 && size == 1 {
+ result.orientation = int(order.Uint16(entry[8:]))
+ }
+ if tag != 270 || kind != 2 || size < 5 || size > 64*1024 {
+ continue
+ }
+ start := uint64(order.Uint32(entry[8:]))
+ if start+size > uint64(len(source)) {
+ continue
+ }
+ description := strings.TrimRight(string(source[start:start+size]), "\x00")
+ if !strings.HasPrefix(description, "ImageJ=") {
+ continue
+ }
+ low, high := math.NaN(), math.NaN()
+ for _, line := range strings.Split(description, "\n") {
+ key, value, found := strings.Cut(strings.TrimSpace(line), "=")
+ if !found {
+ continue
+ }
+ switch key {
+ case "min":
+ if number, err := strconv.ParseFloat(value, 64); err == nil {
+ low = number
+ }
+ case "max":
+ if number, err := strconv.ParseFloat(value, 64); err == nil {
+ high = number
+ }
+ }
+ }
+ if !math.IsNaN(low) && !math.IsNaN(high) && low >= 0 && high <= 65535 && high > low {
+ result.min, result.max, result.hasRange = low, high, true
+ }
+ }
+ if result.hasRange && whiteIsZero {
+ result.min, result.max = 65535-result.max, 65535-result.min
+ }
+ return
+}
+
+func displayGray(ctx context.Context, source *image.Gray16, info metadata) (*image.Gray, error) {
+ low, high := info.min, info.max
+ if !info.hasRange {
+ low, high = 65535, 0
+ for y := source.Rect.Min.Y; y < source.Rect.Max.Y; y++ {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ for x := source.Rect.Min.X; x < source.Rect.Max.X; x++ {
+ value := float64(source.Gray16At(x, y).Y)
+ low, high = min(low, value), max(high, value)
+ }
+ }
+ }
+ if high <= low {
+ low, high = 0, 65535
+ }
+ result := image.NewGray(source.Rect)
+ for y := source.Rect.Min.Y; y < source.Rect.Max.Y; y++ {
+ if err := ctx.Err(); err != nil {
+ clear(result.Pix)
+ return nil, err
+ }
+ for x := source.Rect.Min.X; x < source.Rect.Max.X; x++ {
+ value := (float64(source.Gray16At(x, y).Y) - low) * 255 / (high - low)
+ result.Pix[result.PixOffset(x, y)] = uint8(min(255, max(0, math.Round(value))))
+ }
+ }
+ return result, nil
+}
diff --git a/kernel/tiffpreview/convert_test.go b/kernel/tiffpreview/convert_test.go
new file mode 100644
index 0000000000..4eec2b4790
--- /dev/null
+++ b/kernel/tiffpreview/convert_test.go
@@ -0,0 +1,223 @@
+package tiffpreview
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "errors"
+ "image"
+ "image/color"
+ "image/png"
+ "sort"
+ "testing"
+
+ "golang.org/x/image/tiff"
+)
+
+func encodeTIFF(t *testing.T, img image.Image, compression tiff.CompressionType) []byte {
+ t.Helper()
+ var buffer bytes.Buffer
+ if err := tiff.Encode(&buffer, img, &tiff.Options{Compression: compression}); err != nil {
+ t.Fatal(err)
+ }
+ return buffer.Bytes()
+}
+
+// withMetadata 保留像素和偏移,追加测试所需的首个 IFD 及可选后续页。
+func withMetadata(data []byte, description string, orientation uint16, multiPage bool) []byte {
+ data = bytes.Clone(data)
+ order := binary.LittleEndian
+ offset := int(order.Uint32(data[4:8]))
+ count := int(order.Uint16(data[offset:]))
+ entries := make([][]byte, 0, count+2)
+ for i := 0; i < count; i++ {
+ entries = append(entries, bytes.Clone(data[offset+2+i*12:offset+2+(i+1)*12]))
+ }
+ addEntry := func(tag, kind uint16, count, value uint32) {
+ entry := make([]byte, 12)
+ order.PutUint16(entry, tag)
+ order.PutUint16(entry[2:], kind)
+ order.PutUint32(entry[4:], count)
+ order.PutUint32(entry[8:], value)
+ entries = append(entries, entry)
+ }
+ if description != "" {
+ start := len(data)
+ data = append(data, []byte(description+"\x00")...)
+ addEntry(270, 2, uint32(len(description)+1), uint32(start))
+ }
+ if orientation != 0 {
+ addEntry(274, 3, 1, uint32(orientation))
+ }
+ sort.Slice(entries, func(i, j int) bool { return order.Uint16(entries[i]) < order.Uint16(entries[j]) })
+ if len(data)%2 != 0 {
+ data = append(data, 0)
+ }
+ first := len(data)
+ order.PutUint32(data[4:], uint32(first))
+ ifd := make([]byte, 2+len(entries)*12+4)
+ order.PutUint16(ifd, uint16(len(entries)))
+ for i, entry := range entries {
+ copy(ifd[2+i*12:], entry)
+ }
+ if multiPage {
+ order.PutUint32(ifd[len(ifd)-4:], uint32(first+len(ifd)))
+ }
+ data = append(data, ifd...)
+ if multiPage {
+ second := bytes.Clone(ifd)
+ // 后续页故意不可解码,用来验证首帧预览不读取下一页。
+ order.PutUint32(second[len(second)-4:], 0)
+ for i, entry := range entries {
+ if order.Uint16(entry) == 259 {
+ order.PutUint32(second[2+i*12+8:], 65535)
+ }
+ }
+ data = append(data, second...)
+ }
+ return data
+}
+
+func decodePreview(t *testing.T, source []byte, thumb bool) image.Image {
+ t.Helper()
+ data, err := Convert(context.Background(), source, thumb)
+ if err != nil {
+ t.Fatal(err)
+ }
+ img, err := png.Decode(bytes.NewReader(data))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return img
+}
+
+func TestConvertGrayDisplay(t *testing.T) {
+ gray := image.NewGray16(image.Rect(0, 0, 3, 1))
+ for x, value := range []uint16{120, 1960, 3800} {
+ gray.SetGray16(x, 0, color.Gray16{Y: value})
+ }
+ for _, test := range []struct {
+ name, description string
+ multiPage bool
+ want []uint8
+ }{
+ {"actual range", "", false, []uint8{0, 128, 255}},
+ {"multi IFD first frame", "", true, []uint8{0, 128, 255}},
+ {"ImageJ single IFD stack", "ImageJ=1.11a\nimages=12\nframes=12\nmin=0\nmax=4095\n", false, []uint8{7, 122, 237}},
+ {"invalid ImageJ range", "ImageJ=1.54\nmin=invalid\nmax=4095\n", false, []uint8{0, 128, 255}},
+ {"infinite ImageJ range", "ImageJ=1.54\nmin=0\nmax=Inf\n", false, []uint8{0, 128, 255}},
+ {"non ImageJ description", "min=0\nmax=4095\n", false, []uint8{0, 128, 255}},
+ {"clamped display range", "ImageJ=1.54\nmin=500\nmax=2000\n", false, []uint8{0, 248, 255}},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ source := withMetadata(encodeTIFF(t, gray, tiff.Deflate), test.description, 0, test.multiPage)
+ before := bytes.Clone(source)
+ img := decodePreview(t, source, false)
+ for x, want := range test.want {
+ got := color.GrayModel.Convert(img.At(x, 0)).(color.Gray).Y
+ if got != want {
+ t.Fatalf("pixel %d = %d, want %d", x, got, want)
+ }
+ }
+ if !bytes.Equal(source, before) {
+ t.Fatal("preview modified the original TIFF")
+ }
+ })
+ }
+ flat := image.NewGray16(image.Rect(0, 0, 1, 1))
+ flat.SetGray16(0, 0, color.Gray16{Y: 32768})
+ img := decodePreview(t, encodeTIFF(t, flat, tiff.Uncompressed), false)
+ if got := color.GrayModel.Convert(img.At(0, 0)).(color.Gray).Y; got != 128 {
+ t.Fatalf("uniform image = %d, want 128", got)
+ }
+ inverted := withMetadata(encodeTIFF(t, gray, tiff.Uncompressed), "ImageJ=1.54\nmin=0\nmax=4095\n", 0, false)
+ offset := int(binary.LittleEndian.Uint32(inverted[4:]))
+ for i := 0; i < int(binary.LittleEndian.Uint16(inverted[offset:])); i++ {
+ entry := inverted[offset+2+i*12:]
+ if binary.LittleEndian.Uint16(entry) == 262 {
+ binary.LittleEndian.PutUint16(entry[8:], 0)
+ }
+ }
+ img = decodePreview(t, inverted, false)
+ for x, want := range []uint8{248, 133, 18} {
+ if got := color.GrayModel.Convert(img.At(x, 0)).(color.Gray).Y; got != want {
+ t.Fatalf("white-is-zero pixel %d = %d, want %d", x, got, want)
+ }
+ }
+}
+
+func TestConvertPreserves8BitAndAlpha(t *testing.T) {
+ gray := image.NewGray(image.Rect(0, 0, 2, 1))
+ gray.Pix = []byte{7, 253}
+ img := decodePreview(t, encodeTIFF(t, gray, tiff.Deflate), false)
+ for x, want := range gray.Pix {
+ if got := color.GrayModel.Convert(img.At(x, 0)).(color.Gray).Y; got != want {
+ t.Fatalf("8-bit pixel %d = %d, want %d", x, got, want)
+ }
+ }
+ rgba := image.NewNRGBA(image.Rect(0, 0, 1, 1))
+ rgba.SetNRGBA(0, 0, color.NRGBA{R: 200, G: 50, B: 20, A: 128})
+ img = decodePreview(t, encodeTIFF(t, rgba, tiff.Deflate), false)
+ if got := color.NRGBAModel.Convert(img.At(0, 0)).(color.NRGBA); got != rgba.NRGBAAt(0, 0) {
+ t.Fatalf("RGBA = %v, want %v", got, rgba.NRGBAAt(0, 0))
+ }
+}
+
+func TestConvertOrientationAndThumbnail(t *testing.T) {
+ gray := image.NewGray(image.Rect(0, 0, 2, 1))
+ gray.Pix = []byte{7, 253}
+ for orientation := uint16(1); orientation <= 8; orientation++ {
+ img := decodePreview(t, withMetadata(encodeTIFF(t, gray, tiff.Uncompressed), "", orientation, false), false)
+ want := image.Rect(0, 0, 2, 1)
+ if orientation >= 5 {
+ want = image.Rect(0, 0, 1, 2)
+ }
+ if img.Bounds() != want {
+ t.Fatalf("orientation %d bounds = %v, want %v", orientation, img.Bounds(), want)
+ }
+ first := uint8(7)
+ if orientation == 2 || orientation == 3 || orientation == 7 || orientation == 8 {
+ first = 253
+ }
+ if got := color.GrayModel.Convert(img.At(0, 0)).(color.Gray).Y; got != first {
+ t.Fatalf("orientation %d first pixel = %d, want %d", orientation, got, first)
+ }
+ }
+ large := image.NewGray(image.Rect(0, 0, 1040, 520))
+ source := encodeTIFF(t, large, tiff.Deflate)
+ if got := decodePreview(t, source, true).Bounds(); got != image.Rect(0, 0, 520, 260) {
+ t.Fatalf("thumbnail bounds = %v", got)
+ }
+ if got := decodePreview(t, source, false).Bounds(); got != large.Bounds() {
+ t.Fatalf("full preview bounds = %v", got)
+ }
+}
+
+func TestConvertRejectsInvalidAndOversizedInputs(t *testing.T) {
+ for _, source := range [][]byte{nil, []byte("not a TIFF"), {'I', 'I', 43, 0, 8, 0, 0, 0}} {
+ if _, err := Convert(context.Background(), source, false); err == nil {
+ t.Fatal("invalid or unsupported TIFF was accepted")
+ }
+ }
+ source := encodeTIFF(t, image.NewGray(image.Rect(0, 0, 1, 1)), tiff.Uncompressed)
+ order := binary.LittleEndian
+ offset := int(order.Uint32(source[4:]))
+ for i := 0; i < int(order.Uint16(source[offset:])); i++ {
+ entry := source[offset+2+i*12:]
+ if order.Uint16(entry) == 256 {
+ order.PutUint16(entry[2:], 4)
+ order.PutUint32(entry[8:], 65536)
+ }
+ }
+ if _, err := Convert(context.Background(), source, false); !errors.Is(err, ErrImageTooLarge) {
+ t.Fatalf("oversized dimensions = %v", err)
+ }
+ if _, err := Convert(context.Background(), make([]byte, MaxInputBytes+1), false); !errors.Is(err, ErrInputTooLarge) {
+ t.Fatalf("oversized input = %v", err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if _, err := Convert(ctx, source, false); !errors.Is(err, context.Canceled) {
+ t.Fatalf("canceled conversion = %v", err)
+ }
+}