Skip to content

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

:bug: Preserve asset upload identity and ownership https://github.com/siyuan-note/siyuan/issues/18878

Daniel4e29437bed59
diff --git a/app/src/asset/anno.ts b/app/src/asset/anno.ts
index 831cf7f38a..493e89f9c5 100644
--- a/app/src/asset/anno.ts
+++ b/app/src/asset/anno.ts
@@ -18,6 +18,7 @@ import {
getCaptureCanvasBounds,
getCaptureDisplayWidth,
getLimitedCaptureScale,
+ getPdfAnnotationAssetsDirPath,
PDF_RECT_CAPTURE_PROFILE,
PDF_RECT_CAPTURE_SCALE,
PDF_RECT_DISPLAY_SCALE,
@@ -1055,13 +1056,20 @@ const copyAnno = (idPath: string, fileName: string, pdf: any) => {
confirmDialog(msg ? window.siyuan.languages.upload : "", msg, () => {
const imageName = getRectImageName(content, imageData.rotation, positionHash,
PDF_RECT_CAPTURE_PROFILE);
+ const assetsDirPath = getPdfAnnotationAssetsDirPath(pdf.appConfig.file, location.origin);
+ if (assetsDirPath === null) {
+ return;
+ }
void uploadStandaloneAssetFiles([
new File([imageData.blob], imageName, {type: imageData.blob.type}),
], {
source: "programmatic",
target: "pdf-annotation",
requiredFileCount: 1,
- extraData: {skipIfDuplicated: "true"},
+ extraData: {
+ skipIfDuplicated: "true",
+ ...(assetsDirPath ? {assetsDirPath} : {}),
+ },
}).then(response => {
const path = getAssetUploadSuccesses(response?.data)[0]?.path;
if (path) {
diff --git a/app/src/asset/pdfRectCapture.test.ts b/app/src/asset/pdfRectCapture.test.ts
index bf6f988f93..0ccdfad259 100644
--- a/app/src/asset/pdfRectCapture.test.ts
+++ b/app/src/asset/pdfRectCapture.test.ts
@@ -4,6 +4,7 @@ import {
getCaptureCanvasBounds,
getCaptureDisplayWidth,
getLimitedCaptureScale,
+ getPdfAnnotationAssetsDirPath,
normalizePdfRect,
PDF_RECT_CAPTURE_MAX_EDGE,
PDF_RECT_CAPTURE_MAX_PIXELS,
@@ -67,4 +68,19 @@ describe("PDF rectangle capture", () => {
assert.equal(getCaptureDisplayWidth([10, 20, 130.126, 70]), 120.13);
assert.equal(getCaptureDisplayWidth([10, 20, 10, 70]), 1);
});
+
+ it("derives the encrypted notebook asset directory from the source PDF", () => {
+ const origin = "http://127.0.0.1:6806";
+ assert.equal(
+ getPdfAnnotationAssetsDirPath(`${origin}/assets/document.pdf?box=20260908000000-abcdefg`, origin),
+ "20260908000000-abcdefg/assets/",
+ );
+ assert.equal(getPdfAnnotationAssetsDirPath(`${origin}/assets/document.pdf`, origin), undefined);
+ assert.equal(getPdfAnnotationAssetsDirPath(
+ "https://example.com/assets/document.pdf?box=20260908000000-abcdefg", origin), null);
+ assert.equal(getPdfAnnotationAssetsDirPath(
+ `${origin}/assets/document.pdf?box=invalid`, origin), null);
+ assert.equal(getPdfAnnotationAssetsDirPath(
+ `${origin}/assets/document.pdf?box=20260908000000-abcdefg&box=20260908000001-hijklmn`, origin), null);
+ });
});
diff --git a/app/src/asset/pdfRectCapture.ts b/app/src/asset/pdfRectCapture.ts
index 6aebcb4660..e3cf353b4b 100644
--- a/app/src/asset/pdfRectCapture.ts
+++ b/app/src/asset/pdfRectCapture.ts
@@ -5,6 +5,7 @@ export const PDF_RECT_DISPLAY_SCALE = 2;
export const PDF_RECT_CAPTURE_MAX_EDGE = 8192;
export const PDF_RECT_CAPTURE_MAX_PIXELS = 16 * 1024 * 1024;
export const PDF_RECT_CAPTURE_PROFILE = "capture-v2";
+const BOX_ID_PATTERN = /^\d{14}-[0-9a-z]{7}$/;
interface IRectBounds {
left: number;
@@ -67,3 +68,21 @@ export const getCaptureDisplayWidth = (viewportRect: number[]) => {
const width = normalizePdfRect(viewportRect).width;
return Math.max(1, Math.round(width * 100) / 100);
};
+
+export const getPdfAnnotationAssetsDirPath = (file: string, origin: string) => {
+ try {
+ const baseURL = new URL(origin);
+ const fileURL = new URL(file, `${baseURL.origin}/`);
+ const boxIDs = fileURL.searchParams.getAll("box");
+ if (boxIDs.length === 0) {
+ return;
+ }
+ if (fileURL.origin !== baseURL.origin || !fileURL.pathname.startsWith("/assets/") ||
+ boxIDs.length !== 1 || !BOX_ID_PATTERN.test(boxIDs[0])) {
+ return null;
+ }
+ return `${boxIDs[0]}/assets/`;
+ } catch {
+ return null;
+ }
+};
diff --git a/app/src/protyle/render/av/asset.ts b/app/src/protyle/render/av/asset.ts
index b2bc3d08b0..012e5a5b3f 100644
--- a/app/src/protyle/render/av/asset.ts
+++ b/app/src/protyle/render/av/asset.ts
@@ -30,8 +30,9 @@ import {base64ToURL, showBase64ImageSizeLimit} from "../../upload/base64";
import {isBrowserRenderableImagePath} from "../../../util/imageURL";
import {genNetworkImageAssetValue} from "./assetValue";
import {getAssetUploadSuccesses} from "../../upload/uploadResult";
-import {getAVSelectedCells, type IAVSelectedCell} from "./selectionState";
-import {getAVSelectedTableCells} from "./virtualScroll";
+import {getAVSelectedCells, resolveAVSelectedCell, type IAVSelectedCell} from "./selectionState";
+import {getAVData, getAVSelectedTableCells} from "./virtualScroll";
+import {getAVAssetUploadTargets} from "./assetUploadTarget";
export const bindAssetEvent = (options: {
protyle: IProtyle,
@@ -606,9 +607,7 @@ export const captureAVAssetUploadHandler = (protyle: IProtyle, blockElement: HTM
}
});
}
- if (stableCellCandidates.length > cellElements.length) {
- stableCells = stableCellCandidates;
- }
+ stableCells = stableCellCandidates;
}
const targetCellElements = Array.from(cellElements);
@@ -623,6 +622,7 @@ export const captureAVAssetUploadHandler = (protyle: IProtyle, blockElement: HTM
}
}
}
+ const targets = getAVAssetUploadTargets(stableCells, targetCellElements);
return async (result: Omit<IAssetUploadResult, "requestId" | "input">) => {
if (!document.body.contains(blockElement)) {
@@ -641,24 +641,37 @@ export const captureAVAssetUploadHandler = (protyle: IProtyle, blockElement: HTM
}
return;
}
- if (stableCells.length === 1 || cellElements.length === 1) {
- await updateCellsValue(protyle, blockElement, values, cellElements, undefined, undefined,
- false, false, false, stableCells);
+ if (targets.length === 0) {
return;
}
- if (stableCells.length === 0 && cellElements.length === 0) {
+ const data = targets[0].stableCell ? getAVData(blockElement) : undefined;
+ if (targets.length === 1) {
+ const target = targets[0];
+ const selectedCell = data && target.stableCell ? resolveAVSelectedCell(data, target.stableCell) : undefined;
+ if (selectedCell?.column.type === "mAsset") {
+ await updateCellsValue(protyle, blockElement, values, undefined, undefined, undefined,
+ false, false, false, [selectedCell]);
+ } else if (target.cellElement) {
+ await updateCellsValue(protyle, blockElement, values, [target.cellElement]);
+ }
return;
}
const doOperations: IOperation[] = [];
const undoOperations: IOperation[] = [];
for (let i = 0; i < values.length; i++) {
- const selectedCell = stableCells[i];
- const cellElement = targetCellElements[i];
- if (!selectedCell && !cellElement) {
+ const target = targets[i];
+ if (!target) {
break;
}
+ let selectedCell: IAVSelectedCell | undefined;
+ if (target.stableCell) {
+ selectedCell = data ? resolveAVSelectedCell(data, target.stableCell) : undefined;
+ if (selectedCell?.column.type !== "mAsset") {
+ continue;
+ }
+ }
const operations = await updateCellsValue(protyle, blockElement, [values[i]],
- cellElement ? [cellElement] : undefined, undefined, undefined,
+ target.cellElement ? [target.cellElement] : undefined, undefined, undefined,
true, false, false, selectedCell ? [selectedCell] : undefined);
doOperations.push(...operations.doOperations);
undoOperations.push(...operations.undoOperations);
diff --git a/app/src/protyle/render/av/assetUploadTarget.test.ts b/app/src/protyle/render/av/assetUploadTarget.test.ts
new file mode 100644
index 0000000000..ccacb5fdcd
--- /dev/null
+++ b/app/src/protyle/render/av/assetUploadTarget.test.ts
@@ -0,0 +1,25 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {getAVAssetUploadTargets} from "./assetUploadTarget";
+import type {IAVSelectedCell} from "./selectionState";
+
+describe("database asset upload targets", () => {
+ it("uses the complete logical selection instead of a partial rendered selection", () => {
+ const stableCells = ["row-a", "row-b", "row-c"].map(rowID => ({rowID} as IAVSelectedCell));
+ const renderedCells = [{dataset: {rowId: "row-c"}}] as unknown as HTMLElement[];
+
+ const targets = getAVAssetUploadTargets(stableCells, renderedCells);
+
+ assert.deepEqual(targets.map(target => target.stableCell?.rowID), ["row-a", "row-b", "row-c"]);
+ assert.equal(targets.some(target => target.cellElement), false);
+ });
+
+ it("uses rendered cells when no logical selection is available", () => {
+ const renderedCells = [{dataset: {rowId: "row-a"}}] as unknown as HTMLElement[];
+
+ const targets = getAVAssetUploadTargets([], renderedCells);
+
+ assert.equal(targets[0].cellElement, renderedCells[0]);
+ assert.equal(targets[0].stableCell, undefined);
+ });
+});
diff --git a/app/src/protyle/render/av/assetUploadTarget.ts b/app/src/protyle/render/av/assetUploadTarget.ts
new file mode 100644
index 0000000000..b164580f20
--- /dev/null
+++ b/app/src/protyle/render/av/assetUploadTarget.ts
@@ -0,0 +1,14 @@
+import type {IAVSelectedCell} from "./selectionState";
+
+export interface IAVAssetUploadTarget {
+ stableCell?: IAVSelectedCell;
+ cellElement?: HTMLElement;
+}
+
+export const getAVAssetUploadTargets = (stableCells: IAVSelectedCell[],
+ cellElements: HTMLElement[]): IAVAssetUploadTarget[] => {
+ if (stableCells.length > 0) {
+ return stableCells.map(stableCell => ({stableCell}));
+ }
+ return cellElements.map(cellElement => ({cellElement}));
+};
diff --git a/app/src/protyle/render/av/selectionState.test.ts b/app/src/protyle/render/av/selectionState.test.ts
index 8f931ae8f1..bbfca76251 100644
--- a/app/src/protyle/render/av/selectionState.test.ts
+++ b/app/src/protyle/render/av/selectionState.test.ts
@@ -7,6 +7,7 @@ import {
getAVItemSelection,
getAVSelectionRoot,
reconcileAVSelectedItemIDs,
+ resolveAVSelectedCell,
setAVCellSelection,
setAVItemAnchorState,
setAVItemSelectionState,
@@ -126,4 +127,37 @@ describe("database range selection helpers", () => {
cells: [],
});
});
+
+ it("resolves a captured cell identity against the current database data", () => {
+ const previousCell = {id: "old-cell"} as IAVCell;
+ const currentCell = {id: "current-cell"} as IAVCell;
+ const column = {id: "asset-column", type: "mAsset", hidden: false} as IAVColumn;
+ const capturedCell = {
+ groupID: "",
+ rowID: "row-1",
+ colID: "asset-column",
+ rowIndex: 0,
+ colIndex: 0,
+ cell: previousCell,
+ column,
+ };
+ const data = {
+ view: {
+ id: "view",
+ groups: [],
+ columns: [column],
+ rows: [{id: "row-1", cells: [currentCell]}],
+ },
+ } as unknown as IAV;
+
+ const resolved = resolveAVSelectedCell(data, capturedCell);
+
+ assert.equal(resolved?.cell, currentCell);
+ assert.notEqual(resolved?.cell, previousCell);
+ assert.equal(resolveAVSelectedCell(data, {
+ groupID: "",
+ rowID: "missing-row",
+ colID: "asset-column",
+ }), undefined);
+ });
});
diff --git a/app/src/protyle/render/av/selectionState.ts b/app/src/protyle/render/av/selectionState.ts
index 77bafc2f85..22a1ac3354 100644
--- a/app/src/protyle/render/av/selectionState.ts
+++ b/app/src/protyle/render/av/selectionState.ts
@@ -134,50 +134,49 @@ export const clearAVItemSelectionState = (blockElement: HTMLElement) => {
}
};
-export const refreshAVCellSelection = (blockElement: HTMLElement, data: IAV) => {
- const selection = getAVCellSelection(blockElement);
- if (!selection) {
- return true;
+const findAVSelectionView = (view: IAVView, groupID: string): IAVView | undefined => {
+ if ((!groupID && !view.groups?.length) || view.id === groupID) {
+ return view;
}
- const findView = (view: IAVView): IAVView | undefined => {
- if ((!selection.anchor.groupID && !view.groups?.length) || view.id === selection.anchor.groupID) {
- return view;
- }
- for (const group of view.groups || []) {
- const result = findView(group);
- if (result) {
- return result;
- }
+ for (const group of view.groups || []) {
+ const result = findAVSelectionView(group, groupID);
+ if (result) {
+ return result;
}
- };
- const view = findView(data.view) as IAVTable;
+ }
+};
+
+export const resolveAVSelectedCell = (data: IAV, point: IAVCellPoint): IAVSelectedCell | undefined => {
+ const view = findAVSelectionView(data.view, point.groupID) as IAVTable;
if (!view?.rows || !view.columns) {
- clearAVCellSelectionState(blockElement);
- return false;
+ return;
}
const columns = view.columns.filter(column => !column.hidden);
- const rowIndexes = new Map(view.rows.map((row, index) => [row.id, index]));
- const colIndexes = new Map(columns.map((column, index) => [column.id, index]));
- const sourceColIndexes = new Map(view.columns.map((column, index) => [column.id, index]));
- const cells: IAVSelectedCell[] = [];
- selection.cells.forEach(selectedCell => {
- const rowIndex = rowIndexes.get(selectedCell.rowID);
- const colIndex = colIndexes.get(selectedCell.colID);
- const sourceColIndex = sourceColIndexes.get(selectedCell.colID);
- const cell = typeof rowIndex === "number" && typeof sourceColIndex === "number" ?
- view.rows[rowIndex]?.cells[sourceColIndex] : undefined;
- if (cell && typeof colIndex === "number" && typeof rowIndex === "number") {
- cells.push({
- groupID: selection.anchor.groupID,
- rowID: selectedCell.rowID,
- colID: selectedCell.colID,
- rowIndex,
- colIndex,
- cell,
- column: columns[colIndex],
- });
- }
- });
+ const rowIndex = view.rows.findIndex(row => row.id === point.rowID);
+ const colIndex = columns.findIndex(column => column.id === point.colID);
+ const sourceColIndex = view.columns.findIndex(column => column.id === point.colID);
+ const cell = rowIndex >= 0 && sourceColIndex >= 0 ? view.rows[rowIndex]?.cells[sourceColIndex] : undefined;
+ if (!cell || colIndex < 0) {
+ return;
+ }
+ return {
+ groupID: point.groupID,
+ rowID: point.rowID,
+ colID: point.colID,
+ rowIndex,
+ colIndex,
+ cell,
+ column: columns[colIndex],
+ };
+};
+
+export const refreshAVCellSelection = (blockElement: HTMLElement, data: IAV) => {
+ const selection = getAVCellSelection(blockElement);
+ if (!selection) {
+ return true;
+ }
+ const cells = selection.cells.map(selectedCell => resolveAVSelectedCell(data, selectedCell)).
+ filter((cell): cell is IAVSelectedCell => Boolean(cell));
if (cells.length !== selection.cells.length) {
clearAVCellSelectionState(blockElement);
return false;
diff --git a/kernel/model/upload.go b/kernel/model/upload.go
index 03766316a4..dd6c53796d 100644
--- a/kernel/model/upload.go
+++ b/kernel/model/upload.go
@@ -132,7 +132,9 @@ func assetNameWithoutID(name string) string {
// newAssetFileName 为新增资源生成新的资源 ID,避免外部文件名指定已有资源的写入路径。
func newAssetFileName(name string) string {
- return util.AssetName(assetNameWithoutID(name), ast.NewNodeID())
+ name = assetNameWithoutID(name)
+ ext := util.Ext(name)
+ return strings.TrimSuffix(name, ext) + "-" + ast.NewNodeID() + ext
}
func readRTFDDir(dir string) ([]os.DirEntry, error) {
@@ -335,6 +337,12 @@ func Upload(c *gin.Context) {
// assetsDirPath 可能指向加密 box(调用方未传 id),反查 boxID 让文件名脱敏和内容加密生效
if pathBox := ExtractBoxIDFromAssetsPath(assetsDirPath); pathBox != "" && IsEncryptedBox(pathBox) {
uploadBoxID = pathBox
+ boxAssetsDir := filepath.Join(util.DataDir, pathBox, "assets")
+ if rel, relErr := filepath.Rel(boxAssetsDir, assetsDirPath); relErr == nil && rel != ".." &&
+ !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
+ // 加密资源通过 box 查询参数定位,响应转换为 box 内的标准 assets 相对路径。
+ relAssetsDirPath = path.Join("assets", filepath.ToSlash(rel))
+ }
}
}
if !gulu.File.IsExist(assetsDirPath) {
@@ -421,7 +429,10 @@ func Upload(c *gin.Context) {
// 复制 PDF 矩形注解时不再重复插入图片 No longer upload image repeatedly when copying PDF rectangle annotation https://github.com/siyuan-note/siyuan/issues/10666
pattern := assetsDirPath + string(os.PathSeparator) + strings.TrimSuffix(fName, ext)
_, patternLastID := util.LastID(fName)
- if lastID != "" && lastID != patternLastID {
+ if IsEncryptedBox(uploadBoxID) && lastID != "" {
+ // 加密资源的磁盘名称使用随机前缀,通过标注 ID 查找已生成的截图。
+ pattern = assetsDirPath + string(os.PathSeparator) + "*" + lastID + ext
+ } else if lastID != "" && lastID != patternLastID {
// 文件名太长被截断了,通过之前的 lastID 来匹配 PDF files with too long file names cannot generate annotated images https://github.com/siyuan-note/siyuan/issues/15739
pattern = assetsDirPath + string(os.PathSeparator) + "*" + lastID + ext
} else {
@@ -434,8 +445,11 @@ func Upload(c *gin.Context) {
} else {
if 0 < len(matches) {
fName = filepath.Base(matches[0])
- recordAssetUploadSuccess(succMap, &succFiles, index, baseName,
- strings.TrimPrefix(path.Join(relAssetsDirPath, fName), "/"))
+ p := strings.TrimPrefix(path.Join(relAssetsDirPath, fName), "/")
+ if uploadBoxID != "" && IsEncryptedBox(uploadBoxID) {
+ p += "?box=" + uploadBoxID
+ }
+ recordAssetUploadSuccess(succMap, &succFiles, index, baseName, p)
f.Close()
continue
}
diff --git a/kernel/model/upload_test.go b/kernel/model/upload_test.go
index 4bdd140e99..2a043a0c21 100644
--- a/kernel/model/upload_test.go
+++ b/kernel/model/upload_test.go
@@ -25,6 +25,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
+ "strings"
"testing"
"github.com/gin-gonic/gin"
@@ -39,7 +40,8 @@ type assetUploadTestFile struct {
}
type assetUploadTestResponse struct {
- Code int `json:"code"`
+ Code int `json:"code"`
+ Msg string `json:"msg"`
Data struct {
ErrFiles []string `json:"errFiles"`
FailedFiles []AssetUploadFailure `json:"failedFiles"`
@@ -264,6 +266,83 @@ func TestMultipartUploadContinuesAfterDuplicateMatch(t *testing.T) {
}
}
+func TestMultipartUploadUsesEncryptedDirectoryAttribution(t *testing.T) {
+ setupAssetUploadTest(t)
+ originalWorkspaceDir := util.WorkspaceDir
+ util.WorkspaceDir = filepath.Dir(util.DataDir)
+ t.Cleanup(func() { util.WorkspaceDir = originalWorkspaceDir })
+ const boxID = "20260908000000-abcdefg"
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted = true
+ confData, err := json.Marshal(boxConf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ confDir := filepath.Join(util.DataDir, boxID, ".siyuan")
+ if err = os.MkdirAll(confDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(confDir, "conf.json"), confData, 0644); err != nil {
+ t.Fatal(err)
+ }
+ dek, err := util.GenerateDEK()
+ if err != nil {
+ t.Fatal(err)
+ }
+ setDEKForTest(boxID, dek)
+ t.Cleanup(func() {
+ cachedDEKsLock.Lock()
+ delete(cachedDEKs, boxID)
+ cachedDEKsLock.Unlock()
+ forgetRuntimeEncryptedBox(boxID)
+ })
+
+ plainData := []byte("private PDF rectangle capture")
+ request := newAssetUploadTestRequest(t, []assetUploadTestFile{
+ {name: "annotation-20260908000001-hijklmn.png", data: plainData},
+ {name: "annotation-20260908000001-hijklmn.png", data: plainData},
+ }, map[string]string{"assetsDirPath": boxID + "/assets/", "skipIfDuplicated": "true"})
+ response := executeAssetUploadTestRequest(t, request)
+
+ if response.Code != 0 || len(response.Data.FailedFiles) != 0 || len(response.Data.SuccFiles) != 2 {
+ t.Fatalf("unexpected encrypted upload response: %+v", response)
+ }
+ assetPath := response.Data.SuccFiles[0].Path
+ if !strings.HasPrefix(assetPath, "assets/") || !strings.HasSuffix(assetPath, "?box="+boxID) {
+ t.Fatalf("unexpected encrypted asset path: %s", assetPath)
+ }
+ if response.Data.SuccFiles[1].Path != assetPath {
+ t.Fatalf("duplicate PDF capture was not reused: %+v", response.Data.SuccFiles)
+ }
+ diskName := filepath.Base(strings.SplitN(assetPath, "?", 2)[0])
+ ciphertext, err := os.ReadFile(filepath.Join(util.DataDir, boxID, "assets", diskName))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Equal(ciphertext, plainData) {
+ t.Fatal("encrypted notebook upload was stored as plaintext")
+ }
+ decrypted, originalName, err := DecryptAssetWithName(boxID, diskName, dek, ciphertext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(decrypted, plainData) || originalName != "annotation-20260908000001-hijklmn.png" {
+ t.Fatalf("unexpected decrypted upload: name=%q data=%q", originalName, decrypted)
+ }
+ entries, err := os.ReadDir(filepath.Join(util.DataDir, boxID, "assets"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 1 {
+ t.Fatalf("duplicate PDF capture created %d encrypted assets", len(entries))
+ }
+ if entries, readErr := os.ReadDir(filepath.Join(util.DataDir, "assets")); readErr == nil && len(entries) > 0 {
+ t.Fatalf("encrypted upload created global assets: %+v", entries)
+ } else if readErr != nil && !os.IsNotExist(readErr) {
+ t.Fatal(readErr)
+ }
+}
+
func TestMultipartUploadDoesNotOverwriteFilesWithTheSameAssetID(t *testing.T) {
assetsDir := setupAssetUploadTest(t)
name := "photo-20260828120000-abcdefg.png"
@@ -300,6 +379,45 @@ func TestMultipartUploadDoesNotOverwriteFilesWithTheSameAssetID(t *testing.T) {
}
}
+func TestMultipartUploadDoesNotReuseAnyConsecutiveAssetID(t *testing.T) {
+ assetsDir := setupAssetUploadTest(t)
+ name := "photo-20260828120000-abcdefg-20260907120000-hijklmn.png"
+ firstData := []byte("first file with consecutive asset IDs")
+ secondData := []byte("second file with consecutive asset IDs")
+ cacheAssetUploadTestFile(t, assetsDir, "first-consecutive-seed.png", firstData)
+ cacheAssetUploadTestFile(t, assetsDir, "second-consecutive-seed.png", secondData)
+ request := newAssetUploadTestRequest(t, []assetUploadTestFile{
+ {name: name, data: firstData},
+ {name: name, data: secondData},
+ }, nil)
+
+ response := executeAssetUploadTestRequest(t, request)
+ cleanupAssetUploadTestHashes(t, response.Data.SuccFiles)
+
+ if len(response.Data.FailedFiles) != 0 || len(response.Data.SuccFiles) != 2 {
+ t.Fatalf("unexpected upload response: %+v", response)
+ }
+ if response.Data.SuccFiles[0].Path == response.Data.SuccFiles[1].Path {
+ t.Fatalf("consecutive asset IDs reused the same path: %+v", response.Data.SuccFiles)
+ }
+ for index, success := range response.Data.SuccFiles {
+ if strings.Contains(filepath.Base(success.Path), "-20260907120000-hijklmn.png") {
+ t.Fatalf("upload %d retained the final external asset ID: %s", index, success.Path)
+ }
+ }
+ firstUploaded, err := os.ReadFile(filepath.Join(assetsDir, filepath.Base(response.Data.SuccFiles[0].Path)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ secondUploaded, err := os.ReadFile(filepath.Join(assetsDir, filepath.Base(response.Data.SuccFiles[1].Path)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(firstUploaded, firstData) || !bytes.Equal(secondUploaded, secondData) {
+ t.Fatalf("uploaded contents were overwritten: first=%q second=%q", firstUploaded, secondUploaded)
+ }
+}
+
func TestMultipartUploadReusesSameContentWhenAssetIDsDiffer(t *testing.T) {
assetsDir := setupAssetUploadTest(t)
existingName := "photo-20260828120001-hijklmn.png"
@@ -369,6 +487,46 @@ func TestInsertLocalAssetsDoesNotOverwriteFilesWithTheSameAssetID(t *testing.T)
}
}
+func TestInsertLocalAssetsDoesNotReuseAnyConsecutiveAssetID(t *testing.T) {
+ assetsDir := setupAssetUploadTest(t)
+ name := "photo-20260828120000-abcdefg-20260907120000-hijklmn.png"
+ firstData := []byte("first local file with consecutive asset IDs")
+ secondData := []byte("second local file with consecutive asset IDs")
+ cacheAssetUploadTestFile(t, assetsDir, "first-local-consecutive-seed.png", firstData)
+ cacheAssetUploadTestFile(t, assetsDir, "second-local-consecutive-seed.png", secondData)
+ firstPath := filepath.Join(t.TempDir(), name)
+ secondPath := filepath.Join(t.TempDir(), name)
+ if err := os.WriteFile(firstPath, firstData, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(secondPath, secondData, 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ _, successes, failures, err := InsertLocalAssets("", []string{firstPath, secondPath}, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cleanupAssetUploadTestHashes(t, successes)
+ if len(failures) != 0 || len(successes) != 2 {
+ t.Fatalf("unexpected local upload result: successes=%+v failures=%+v", successes, failures)
+ }
+ if successes[0].Path == successes[1].Path {
+ t.Fatalf("consecutive asset IDs reused the same local path: %+v", successes)
+ }
+ firstUploaded, err := os.ReadFile(filepath.Join(assetsDir, filepath.Base(successes[0].Path)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ secondUploaded, err := os.ReadFile(filepath.Join(assetsDir, filepath.Base(successes[1].Path)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(firstUploaded, firstData) || !bytes.Equal(secondUploaded, secondData) {
+ t.Fatalf("local uploaded contents were overwritten: first=%q second=%q", firstUploaded, secondUploaded)
+ }
+}
+
func TestReadRTFDDirReturnsAnErrorForAFile(t *testing.T) {
filePath := filepath.Join(t.TempDir(), ".DS_Store")
if err := os.WriteFile(filePath, []byte("metadata"), 0644); err != nil {