Skip to content

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

:zap: Skip HEIF transcoding for capable clients https://github.com/siyuan-note/siyuan/issues/18760

Danielfe0f3e449c7c
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index a9f4f17b20..a641225e92 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -152,7 +152,9 @@ func Serve(fastMode bool, cookieKey string) {
model.Activity, // 记录用户活动时间,用于 AutoFixIndex 的空闲判断
corsMiddleware(), // 后端服务支持 CORS 预检请求验证 https://github.com/siyuan-note/siyuan/pull/5593
jwtMiddleware, // 解析 JWT https://github.com/siyuan-note/siyuan/issues/11364
- gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedExtensions([]string{".pdf", ".mp3", ".wav", ".ogg", ".mov", ".weba", ".mkv", ".mp4", ".webm", ".flac"})),
+ gzip.Gzip(gzip.DefaultCompression,
+ gzip.WithExcludedExtensions([]string{".pdf", ".mp3", ".wav", ".ogg", ".mov", ".weba", ".mkv", ".mp4", ".webm", ".flac"}),
+ gzip.WithExcludedPathsRegexs([]string{`(?i)\.hei[cf]$`})),
)
sessionStore = cookie.NewStore([]byte(cookieKey))
@@ -980,8 +982,8 @@ func serveAssets(ginServer *gin.Engine) {
}
if heif.IsPath(p) {
- // 下载始终返回原文件;预览请求统一转成浏览器可显示的 JPEG。
- if !strings.EqualFold(context.Query("download"), "true") {
+ addHEIFVaryAccept(context)
+ if shouldTranscodeHEIF(context) {
if !acquireHEIFPreviewSlot(context) {
return
}
@@ -1024,7 +1026,11 @@ func serveAssets(ginServer *gin.Engine) {
context.Status(http.StatusForbidden)
return
}
- if heif.IsPath(p) && !strings.EqualFold(context.Query("download"), "true") {
+ transcodeHEIF := heif.IsPath(p) && shouldTranscodeHEIF(context)
+ if heif.IsPath(p) {
+ addHEIFVaryAccept(context)
+ }
+ if transcodeHEIF {
if !acquireHEIFPreviewSlot(context) {
return
}
@@ -1034,7 +1040,7 @@ func serveAssets(ginServer *gin.Engine) {
if serveEncryptedHistory(context, p) {
return
}
- if heif.IsPath(p) && !strings.EqualFold(context.Query("download"), "true") {
+ if transcodeHEIF {
servePlainHEIFPreview(context, p, "", false)
return
}
@@ -1311,13 +1317,18 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {
defer model.ReleaseBoxReadLock(boxID)
var ciphertext []byte
var readErr error
- if heif.IsPath(absPath) && !strings.EqualFold(context.Query("download"), "true") {
+ heifRequest := heif.IsPath(absPath) && !strings.EqualFold(context.Query("download"), "true")
+ if heifRequest {
ciphertext, readErr = heif.ReadFileLimited(absPath, int64(heif.MaxInputBytes)+2*1024*1024)
} else {
ciphertext, readErr = os.ReadFile(absPath)
}
if readErr != nil {
- context.Status(http.StatusNotFound)
+ if errors.Is(readErr, heif.ErrInputTooLarge) {
+ context.Status(http.StatusRequestEntityTooLarge)
+ } else {
+ context.Status(http.StatusNotFound)
+ }
return true
}
diskName := filepath.Base(absPath)
@@ -1328,6 +1339,10 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {
return true
}
defer clear(plain)
+ if heifRequest && len(plain) > heif.MaxInputBytes {
+ context.Status(http.StatusRequestEntityTooLarge)
+ return true
+ }
// 下载时用原始文件名(查加密映射),查不到则退回磁盘名
dispositionName := absPath
if originalName := model.LookupAssetOriginalNameLocked(boxID, diskName); originalName != "" {
@@ -1385,14 +1400,14 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
}
defer clear(dek)
defer model.ReleaseBoxReadLock(boxID)
- if heif.IsPath(absPath) && !strings.EqualFold(context.Query("download"), "true") &&
- rejectOversizedHEIF(context, absPath, true) {
+ heifRequest := heif.IsPath(absPath) && !strings.EqualFold(context.Query("download"), "true")
+ transcodeHEIF := heif.IsPath(absPath) && shouldTranscodeHEIF(context)
+ if heifRequest && rejectOversizedHEIF(context, absPath, true) {
return true
}
- heifPreview := heif.IsPath(absPath) && !strings.EqualFold(context.Query("download"), "true")
var ciphertext []byte
var readErr error
- if heifPreview {
+ if heifRequest {
ciphertext, readErr = heif.ReadFileLimited(absPath, int64(heif.MaxInputBytes)+2*1024*1024)
} else {
ciphertext, readErr = os.ReadFile(absPath)
@@ -1431,11 +1446,11 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
return true
}
defer clear(plain)
- if heifPreview && len(plain) > heif.MaxInputBytes {
+ if heifRequest && len(plain) > heif.MaxInputBytes {
context.Status(http.StatusRequestEntityTooLarge)
return true
}
- if heifPreview {
+ if transcodeHEIF {
writeHEIFPreview(context, absPath, plain, boxID, true)
return true
}
@@ -1502,8 +1517,11 @@ func serveRepoDiff(ginServer *gin.Engine) {
context.Status(http.StatusForbidden)
return
}
- heifPreview := heif.IsPath(requestPath) && !strings.EqualFold(context.Query("download"), "true")
- if heifPreview {
+ transcodeHEIF := heif.IsPath(requestPath) && shouldTranscodeHEIF(context)
+ if heif.IsPath(requestPath) {
+ addHEIFVaryAccept(context)
+ }
+ if transcodeHEIF {
if !acquireHEIFPreviewSlot(context) {
return
}
@@ -1534,7 +1552,7 @@ func serveRepoDiff(ginServer *gin.Engine) {
context.Status(http.StatusUnauthorized)
return
}
- if heifPreview {
+ if transcodeHEIF {
servePlainHEIFPreview(context, p, encryptedBoxID, encryptedBoxID != "")
return
}
diff --git a/kernel/server/serve_heif_accept.go b/kernel/server/serve_heif_accept.go
new file mode 100644
index 0000000000..a49a1444a6
--- /dev/null
+++ b/kernel/server/serve_heif_accept.go
@@ -0,0 +1,159 @@
+// 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 (
+ "mime"
+ "net/http"
+ "strings"
+
+ "github.com/gin-gonic/gin"
+)
+
+// requestAcceptsHEIF 只接受客户端显式声明且质量值大于 0 的 HEIC/HEIF 媒体类型。
+func requestAcceptsHEIF(request *http.Request) bool {
+ for _, accept := range request.Header.Values("Accept") {
+ values, valid := splitAcceptHeader(accept)
+ if !valid {
+ continue
+ }
+ for _, value := range values {
+ mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(value))
+ if err != nil || (mediaType != "image/heic" && mediaType != "image/heif") {
+ continue
+ }
+ if !acceptQualityPositive(value) {
+ continue
+ }
+ return true
+ }
+ }
+ return false
+}
+
+// splitAcceptHeader 仅在引号外拆分 Accept 条目,避免把媒体类型参数中的逗号当成分隔符。
+func splitAcceptHeader(value string) ([]string, bool) {
+ return splitHeaderValue(value, ',')
+}
+
+func splitHeaderValue(value string, separator rune) ([]string, bool) {
+ var ret []string
+ start := 0
+ quoted := false
+ escaped := false
+ for index, char := range value {
+ if escaped {
+ escaped = false
+ continue
+ }
+ if quoted && char == '\\' {
+ escaped = true
+ continue
+ }
+ if char == '"' {
+ quoted = !quoted
+ continue
+ }
+ if char == separator && !quoted {
+ ret = append(ret, value[start:index])
+ start = index + 1
+ }
+ }
+ if quoted {
+ return nil, false
+ }
+ return append(ret, value[start:]), true
+}
+
+// acceptQualityPositive 拒绝扩展、重复或非正数的 q 参数,未声明 q 时使用默认质量值 1。
+func acceptQualityPositive(value string) bool {
+ parameters, valid := splitHeaderValue(value, ';')
+ if !valid {
+ return false
+ }
+ foundQuality := false
+ for _, parameter := range parameters[1:] {
+ name, quality, found := strings.Cut(parameter, "=")
+ if !found {
+ continue
+ }
+ name = strings.ToLower(strings.TrimSpace(name))
+ if strings.HasPrefix(name, "q*") || (name == "q" && foundQuality) {
+ return false
+ }
+ if name != "q" {
+ continue
+ }
+ foundQuality = true
+ if !positiveQValue(strings.TrimSpace(quality)) {
+ return false
+ }
+ }
+ return true
+}
+
+// positiveQValue 按 HTTP qvalue 语法接受最多三位小数,且只返回大于 0 的质量值。
+func positiveQValue(value string) bool {
+ if value == "1" {
+ return true
+ }
+ if strings.HasPrefix(value, "1.") {
+ digits := value[2:]
+ if 3 < len(digits) {
+ return false
+ }
+ for _, digit := range digits {
+ if digit != '0' {
+ return false
+ }
+ }
+ return true
+ }
+ if !strings.HasPrefix(value, "0.") {
+ return false
+ }
+ digits := value[2:]
+ if 3 < len(digits) {
+ return false
+ }
+ positive := false
+ for _, digit := range digits {
+ if digit < '0' || '9' < digit {
+ return false
+ }
+ positive = positive || digit != '0'
+ }
+ return positive
+}
+
+// shouldTranscodeHEIF 保持下载原件和 JPEG 缩略图语义,全图按客户端能力协商。
+func shouldTranscodeHEIF(context *gin.Context) bool {
+ if strings.EqualFold(context.Query("download"), "true") {
+ return false
+ }
+ if context.Query("style") == "thumb" {
+ return true
+ }
+ return !requestAcceptsHEIF(context.Request)
+}
+
+// addHEIFVaryAccept 标记全图响应会随 Accept 请求头变化,并保留其他缓存协商字段。
+func addHEIFVaryAccept(context *gin.Context) {
+ if strings.EqualFold(context.Query("download"), "true") || context.Query("style") == "thumb" {
+ return
+ }
+ for _, vary := range context.Writer.Header().Values("Vary") {
+ for _, value := range strings.Split(vary, ",") {
+ if strings.EqualFold(strings.TrimSpace(value), "Accept") || strings.TrimSpace(value) == "*" {
+ return
+ }
+ }
+ }
+ context.Writer.Header().Add("Vary", "Accept")
+}
diff --git a/kernel/server/serve_heif_accept_test.go b/kernel/server/serve_heif_accept_test.go
new file mode 100644
index 0000000000..d2e09de799
--- /dev/null
+++ b/kernel/server/serve_heif_accept_test.go
@@ -0,0 +1,170 @@
+// 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 (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+)
+
+func TestRequestAcceptsHEIF(t *testing.T) {
+ tests := []struct {
+ name string
+ accept []string
+ want bool
+ }{
+ {name: "HEIC", accept: []string{"image/heic"}, want: true},
+ {name: "HEIF", accept: []string{"image/heif"}, want: true},
+ {name: "case insensitive", accept: []string{"IMAGE/HEIC"}, want: true},
+ {name: "positive quality", accept: []string{"image/avif, image/heif; q=0.5, image/webp"}, want: true},
+ {name: "minimum positive quality", accept: []string{"image/heic;q=0.001"}, want: true},
+ {name: "maximum quality", accept: []string{"image/heif;q=1.000"}, want: true},
+ {name: "parameters", accept: []string{"image/heic; q=1; version=1"}, want: true},
+ {name: "quoted comma parameter", accept: []string{`image/heic; profile="alpha,beta"; q=0.7`}, want: true},
+ {name: "HEIC inside quoted parameter", accept: []string{`application/example; profile=",image/heic,"`}, want: false},
+ {name: "unclosed quoted parameter", accept: []string{`image/heic; profile="alpha,beta`}, want: false},
+ {name: "multiple header lines", accept: []string{"image/avif", "image/heif; q=0.8"}, want: true},
+ {name: "zero quality HEIC", accept: []string{"image/heic;q=0"}, want: false},
+ {name: "zero quality HEIF", accept: []string{"image/png, image/heif; q=0"}, want: false},
+ {name: "extended quality cannot override zero", accept: []string{`image/heic;q=0;q*=utf-8''1`}, want: false},
+ {name: "continued quality is invalid", accept: []string{`image/heif;q*0*=utf-8''0.;q*1=8`}, want: false},
+ {name: "NaN quality", accept: []string{"image/heic;q=NaN"}, want: false},
+ {name: "infinite quality", accept: []string{"image/heif;q=Inf"}, want: false},
+ {name: "quality above one", accept: []string{"image/heic;q=1.1"}, want: false},
+ {name: "quality without leading zero", accept: []string{"image/heic;q=.5"}, want: false},
+ {name: "exponential quality", accept: []string{"image/heic;q=1e-1"}, want: false},
+ {name: "quality with leading zero", accept: []string{"image/heic;q=01"}, want: false},
+ {name: "quality with four decimal places", accept: []string{"image/heic;q=0.5000"}, want: false},
+ {name: "quoted quality", accept: []string{`image/heic;q="0.5"`}, want: false},
+ {name: "invalid quality", accept: []string{"image/heic;q=invalid"}, want: false},
+ {name: "image wildcard", accept: []string{"image/*"}, want: false},
+ {name: "any wildcard", accept: []string{"*/*"}, want: false},
+ {name: "missing", want: false},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ request := httptest.NewRequest(http.MethodGet, "/assets/image.heic", nil)
+ for _, accept := range test.accept {
+ request.Header.Add("Accept", accept)
+ }
+ if got := requestAcceptsHEIF(request); got != test.want {
+ t.Fatalf("requestAcceptsHEIF() = %v, want %v for Accept %q", got, test.want, test.accept)
+ }
+ })
+ }
+}
+
+func TestShouldTranscodeHEIF(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ tests := []struct {
+ name string
+ requestURL string
+ accept string
+ want bool
+ }{
+ {name: "native full preview", requestURL: "/assets/image.heic", accept: "image/heic", want: false},
+ {name: "fallback full preview", requestURL: "/assets/image.heic", accept: "image/webp", want: true},
+ {name: "missing capability", requestURL: "/assets/image.heic", want: true},
+ {name: "thumbnail with native support", requestURL: "/assets/image.heic?style=thumb", accept: "image/heic", want: true},
+ {name: "thumbnail without native support", requestURL: "/assets/image.heic?style=thumb", want: true},
+ {name: "download without native support", requestURL: "/assets/image.heic?download=true", want: false},
+ {name: "case insensitive download", requestURL: "/assets/image.heic?download=TRUE", want: false},
+ {name: "download overrides thumbnail", requestURL: "/assets/image.heic?download=true&style=thumb", want: false},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ context, _ := gin.CreateTestContext(httptest.NewRecorder())
+ context.Request = httptest.NewRequest(http.MethodGet, test.requestURL, nil)
+ if test.accept != "" {
+ context.Request.Header.Set("Accept", test.accept)
+ }
+ if got := shouldTranscodeHEIF(context); got != test.want {
+ t.Fatalf("shouldTranscodeHEIF() = %v, want %v for %q with Accept %q",
+ got, test.want, test.requestURL, test.accept)
+ }
+ })
+ }
+}
+
+func TestAddHEIFVaryAccept(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ tests := []struct {
+ name string
+ requestURL string
+ initialVary string
+ wantAccept bool
+ wantOrigin bool
+ wantAcceptOnce bool
+ }{
+ {name: "full preview", requestURL: "/assets/image.heic", wantAccept: true, wantAcceptOnce: true},
+ {
+ name: "preserves existing value",
+ requestURL: "/assets/image.heic",
+ initialVary: "Origin",
+ wantAccept: true,
+ wantOrigin: true,
+ wantAcceptOnce: true,
+ },
+ {
+ name: "does not duplicate value",
+ requestURL: "/assets/image.heic",
+ initialVary: "Origin, accept",
+ wantAccept: true,
+ wantOrigin: true,
+ wantAcceptOnce: true,
+ },
+ {name: "wildcard already varies", requestURL: "/assets/image.heic", initialVary: "*"},
+ {name: "thumbnail", requestURL: "/assets/image.heic?style=thumb"},
+ {name: "download", requestURL: "/assets/image.heic?download=true"},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ context, _ := gin.CreateTestContext(recorder)
+ context.Request = httptest.NewRequest(http.MethodGet, test.requestURL, nil)
+ if test.initialVary != "" {
+ context.Header("Vary", test.initialVary)
+ }
+
+ addHEIFVaryAccept(context)
+
+ acceptCount := 0
+ originFound := false
+ for _, value := range recorder.Header().Values("Vary") {
+ for _, field := range strings.Split(value, ",") {
+ switch {
+ case strings.EqualFold(strings.TrimSpace(field), "Accept"):
+ acceptCount++
+ case strings.EqualFold(strings.TrimSpace(field), "Origin"):
+ originFound = true
+ }
+ }
+ }
+ if got := acceptCount > 0; got != test.wantAccept {
+ t.Fatalf("Vary Accept presence = %v, want %v; header is %q", got, test.wantAccept,
+ recorder.Header().Values("Vary"))
+ }
+ if originFound != test.wantOrigin {
+ t.Fatalf("Vary Origin presence = %v, want %v; header is %q", originFound, test.wantOrigin,
+ recorder.Header().Values("Vary"))
+ }
+ if test.wantAcceptOnce && acceptCount != 1 {
+ t.Fatalf("Vary Accept count = %d, want 1; header is %q", acceptCount,
+ recorder.Header().Values("Vary"))
+ }
+ })
+ }
+}