fix(canvas): 画布 - 防止旧内容覆盖并支持版本历史恢复
This commit is contained in:
1 parent
b6bae4f957
commit
35ebed3097
69 files changed
+3575
-294
No files matched your search
@@ -0,0 +1,185 @@
|
||||
package canvas
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/assets"
|
||||
"infinite-canvas/backend/internal/kernel"
|
||||
"infinite-canvas/backend/internal/model"
|
||||
"infinite-canvas/backend/internal/repository"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const canvasHistoryLimit = 20
|
||||
const canvasHistoryInterval = 5 * time.Minute
|
||||
|
||||
// 浏览器、云端 Agent 和创作任务共用此入口;外层事务仍负责任务和画布的一致性。
|
||||
func SaveDocumentWithHistory(repo *repository.Repository, before *model.CanvasProject, after *model.CanvasProject, reason string) error {
|
||||
snapshot, resourceIDs, err := buildCanvasSnapshot(before, *after, reason)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var restoredIDs []string
|
||||
if reason == "before_restore" {
|
||||
refs := map[string]struct{}{}
|
||||
if err := assets.CollectOwnedDocumentReferences(after.PayloadJSON, refs); err != nil {
|
||||
return err
|
||||
}
|
||||
restoredIDs = assets.SortedIDs(refs)
|
||||
}
|
||||
return repo.SaveCanvasWithSnapshot(after, snapshot, resourceIDs, restoredIDs, after.UpdatedAt.Add(-canvasHistoryInterval), canvasHistoryLimit, reason == "before_restore")
|
||||
}
|
||||
|
||||
func canvasRevisionConflict() error {
|
||||
return kernel.NewAppError(http.StatusConflict, "云端画布已有更新,已停止覆盖;请保留本地草稿并加载最新版本")
|
||||
}
|
||||
|
||||
type CanvasHistoryList struct {
|
||||
Snapshots []model.CanvasSnapshot `json:"snapshots"`
|
||||
CurrentRevision int64 `json:"currentRevision"`
|
||||
}
|
||||
|
||||
func (s *Service) scopedCanvasHistoryProject(userID string, canvasID string) (*model.CanvasProject, error) {
|
||||
project, err := s.repo.CanvasProjectMetadata(userID, strings.TrimSpace(canvasID))
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, kernel.NewAppError(http.StatusNotFound, "画布不存在或无权访问")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return project, nil
|
||||
}
|
||||
|
||||
func (s *Service) CanvasHistory(userID string, canvasID string) (CanvasHistoryList, error) {
|
||||
project, err := s.scopedCanvasHistoryProject(userID, canvasID)
|
||||
if err != nil {
|
||||
return CanvasHistoryList{}, err
|
||||
}
|
||||
items, err := s.repo.CanvasSnapshots(project.UserID, project.ID, canvasHistoryLimit)
|
||||
return CanvasHistoryList{Snapshots: items, CurrentRevision: project.Revision}, err
|
||||
}
|
||||
|
||||
func (s *Service) CanvasHistorySnapshot(userID string, canvasID, snapshotID string) (*model.CanvasSnapshot, error) {
|
||||
project, err := s.scopedCanvasHistoryProject(userID, canvasID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item, err := s.repo.CanvasSnapshot(project.UserID, project.ID, snapshotID)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, kernel.NewAppError(http.StatusNotFound, "历史版本不存在或已过期,请刷新历史列表")
|
||||
}
|
||||
return item, err
|
||||
}
|
||||
|
||||
func (s *Service) RestoreCanvasHistory(userID string, canvasID, snapshotID string, revision *int64) (UserDataSummary, error) {
|
||||
if revision == nil {
|
||||
return UserDataSummary{}, kernel.NewAppError(http.StatusPreconditionRequired, "请先刷新画布版本再恢复")
|
||||
}
|
||||
current, err := s.scopedCanvasHistoryProject(userID, canvasID)
|
||||
if err != nil {
|
||||
return UserDataSummary{}, err
|
||||
}
|
||||
if current.Revision != *revision {
|
||||
return UserDataSummary{}, canvasRevisionConflict()
|
||||
}
|
||||
item, err := s.CanvasHistorySnapshot(userID, canvasID, snapshotID)
|
||||
if err != nil {
|
||||
return UserDataSummary{}, err
|
||||
}
|
||||
var payload map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(item.PayloadJSON), &payload); err != nil {
|
||||
return UserDataSummary{}, err
|
||||
}
|
||||
// Restore document content while retaining its present ownership and business association.
|
||||
for key, value := range map[string]any{
|
||||
"id": current.ID, "revision": *revision, "createdAt": current.CreatedAt,
|
||||
"projectId": current.ProjectID,
|
||||
} {
|
||||
payload[key], _ = json.Marshal(value)
|
||||
}
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return UserDataSummary{}, err
|
||||
}
|
||||
return s.upsertUserCanvasProjectWithHistory(userID, raw, "before_restore")
|
||||
}
|
||||
|
||||
func canvasHistoryContent(project model.CanvasProject) ([]byte, error) {
|
||||
raw, err := canvasProjectPayload(project)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var payload map[string]any
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.UseNumber()
|
||||
if err := decoder.Decode(&payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, key := range []string{"revision", "updatedAt", "createdAt", "viewport", "remoteContentHash"} {
|
||||
delete(payload, key)
|
||||
}
|
||||
return json.Marshal(payload)
|
||||
}
|
||||
|
||||
func buildCanvasSnapshot(before *model.CanvasProject, after model.CanvasProject, reason string) (*model.CanvasSnapshot, []string, error) {
|
||||
if before == nil {
|
||||
return nil, nil, nil
|
||||
}
|
||||
oldContent, err := canvasHistoryContent(*before)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
newContent, err := canvasHistoryContent(after)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if reason != "before_restore" && bytes.Equal(oldContent, newContent) {
|
||||
return nil, nil, nil
|
||||
}
|
||||
raw, err := canvasProjectPayload(*before)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var counts struct {
|
||||
Nodes []json.RawMessage
|
||||
Connections []json.RawMessage
|
||||
}
|
||||
if err := json.Unmarshal(raw, &counts); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
resources := map[string]struct{}{}
|
||||
if err := assets.CollectOwnedDocumentReferences(string(raw), resources); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return &model.CanvasSnapshot{
|
||||
ID: kernel.NewID(), CanvasID: before.ID, UserID: before.UserID, Revision: before.Revision,
|
||||
Title: before.Title, NodeCount: len(counts.Nodes), ConnectionCount: len(counts.Connections),
|
||||
PayloadJSON: string(raw), PayloadBytes: len(raw), Reason: reason,
|
||||
ContentUpdatedAt: before.UpdatedAt, CreatedAt: after.UpdatedAt,
|
||||
}, assets.SortedIDs(resources), nil
|
||||
}
|
||||
|
||||
// Row metadata is authoritative, including changes made by project association operations.
|
||||
func canvasProjectPayload(project model.CanvasProject) (json.RawMessage, error) {
|
||||
var payload map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(project.PayloadJSON), &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if payload == nil {
|
||||
return nil, kernel.BadAuthRequest("画布数据格式错误")
|
||||
}
|
||||
for key, value := range map[string]any{"id": project.ID, "title": project.Title, "projectId": project.ProjectID, "revision": project.Revision, "createdAt": project.CreatedAt, "updatedAt": project.UpdatedAt} {
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload[key] = encoded
|
||||
}
|
||||
return json.Marshal(payload)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package canvas
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"infinite-canvas/backend/internal/kernel"
|
||||
"infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestCanvasHistoryRestore(t *testing.T) {
|
||||
svc := newCanvasHistoryTestService(t)
|
||||
actor := &model.User{ID: "owner"}
|
||||
save := func(raw string) UserDataSummary {
|
||||
t.Helper()
|
||||
result, err := svc.UpsertUserCanvasProject(actor.ID, json.RawMessage(raw))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
save(`{"id":"canvas","revision":0,"title":"original","nodes":[{"id":"video"}],"connections":[]}`)
|
||||
save(`{"id":"canvas","revision":1,"title":"original","nodes":[{"id":"video"}],"connections":[],"viewport":{"x":20}}`)
|
||||
list, err := svc.CanvasHistory(actor.ID, "canvas")
|
||||
if err != nil || len(list.Snapshots) != 0 {
|
||||
t.Fatalf("no-op created snapshot: %#v %v", list, err)
|
||||
}
|
||||
save(`{"id":"canvas","revision":2,"title":"edited","nodes":[],"connections":[]}`)
|
||||
list, err = svc.CanvasHistory(actor.ID, "canvas")
|
||||
if err != nil || len(list.Snapshots) != 1 || list.CurrentRevision != 3 || list.Snapshots[0].NodeCount != 1 {
|
||||
t.Fatalf("history: %#v %v", list, err)
|
||||
}
|
||||
entry := list.Snapshots[0]
|
||||
if entry.PayloadJSON != "" {
|
||||
t.Fatal("history list loaded full payload")
|
||||
}
|
||||
preview, err := svc.CanvasHistorySnapshot(actor.ID, "canvas", entry.ID)
|
||||
if err != nil || !strings.Contains(preview.PayloadJSON, "video") {
|
||||
t.Fatalf("preview = %#v %v", preview, err)
|
||||
}
|
||||
for _, scenario := range []struct {
|
||||
actor *model.User
|
||||
canvasID string
|
||||
}{
|
||||
{actor: &model.User{ID: "stranger"}, canvasID: "canvas"},
|
||||
{actor: actor, canvasID: "missing-canvas"},
|
||||
} {
|
||||
var notFound *kernel.AppError
|
||||
if _, err := svc.CanvasHistory(scenario.actor.ID, scenario.canvasID); !errors.As(err, ¬Found) || notFound.Status != http.StatusNotFound {
|
||||
t.Fatalf("inaccessible history must return 404: %v", err)
|
||||
}
|
||||
if _, err := svc.CanvasHistorySnapshot(scenario.actor.ID, scenario.canvasID, entry.ID); !errors.As(err, ¬Found) || notFound.Status != http.StatusNotFound {
|
||||
t.Fatalf("inaccessible preview must return 404: %v", err)
|
||||
}
|
||||
currentRevision := int64(3)
|
||||
if _, err := svc.RestoreCanvasHistory(scenario.actor.ID, scenario.canvasID, entry.ID, ¤tRevision); !errors.As(err, ¬Found) || notFound.Status != http.StatusNotFound {
|
||||
t.Fatalf("inaccessible restore must return 404: %v", err)
|
||||
}
|
||||
}
|
||||
if _, err := svc.CanvasHistorySnapshot(actor.ID, "canvas", "other-canvas-snapshot"); err == nil {
|
||||
t.Fatal("unrelated snapshot readable")
|
||||
}
|
||||
if _, err := svc.RestoreCanvasHistory(actor.ID, "canvas", entry.ID, nil); err == nil {
|
||||
t.Fatal("missing revision accepted")
|
||||
}
|
||||
stale := int64(2)
|
||||
_, err = svc.RestoreCanvasHistory(actor.ID, "canvas", entry.ID, &stale)
|
||||
var appError *kernel.AppError
|
||||
if !errors.As(err, &appError) || appError.Status != http.StatusConflict {
|
||||
t.Fatalf("stale restore = %v", err)
|
||||
}
|
||||
current := int64(3)
|
||||
result, err := svc.RestoreCanvasHistory(actor.ID, "canvas", entry.ID, ¤t)
|
||||
if err != nil || result.Revision != 4 {
|
||||
t.Fatalf("restore = %#v %v", result, err)
|
||||
}
|
||||
raw, _ := svc.UserCanvasProject(actor.ID, "canvas")
|
||||
if !strings.Contains(string(raw), "video") || !strings.Contains(string(raw), "original") {
|
||||
t.Fatalf("wrong restored content: %s", raw)
|
||||
}
|
||||
list, _ = svc.CanvasHistory(actor.ID, "canvas")
|
||||
if len(list.Snapshots) != 2 || list.Snapshots[0].Revision != 3 || list.Snapshots[0].Reason != "before_restore" {
|
||||
t.Fatalf("pre-restore backup missing: %#v", list)
|
||||
}
|
||||
current = 4
|
||||
if _, err := svc.RestoreCanvasHistory(actor.ID, "canvas", list.Snapshots[0].ID, ¤t); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ = svc.UserCanvasProject(actor.ID, "canvas")
|
||||
if strings.Contains(string(raw), "video") {
|
||||
t.Fatal("could not undo restore")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package canvas
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"infinite-canvas/backend/internal/repository"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"infinite-canvas/backend/internal/kernel"
|
||||
"infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestCanvasSaveRevisionContract(t *testing.T) {
|
||||
svc := newCanvasHistoryTestService(t)
|
||||
actor := &model.User{ID: "owner"}
|
||||
missing := json.RawMessage(`{"id":"canvas","nodes":[]}`)
|
||||
_, err := svc.UpsertUserCanvasProject(actor.ID, missing)
|
||||
var appError *kernel.AppError
|
||||
if !errors.As(err, &appError) || appError.Status != http.StatusPreconditionRequired {
|
||||
t.Fatalf("unversioned save = %v", err)
|
||||
}
|
||||
raw := json.RawMessage(`{"id":"canvas","revision":0,"title":"initial","nodes":[{"id":"old"}],"viewport":{"x":999,"y":0,"k":2}}`)
|
||||
created, err := svc.UpsertUserCanvasProject(actor.ID, raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if created.Revision != 1 {
|
||||
t.Fatalf("revision = %d", created.Revision)
|
||||
}
|
||||
update := json.RawMessage(`{"id":"canvas","revision":1,"title":"new","nodes":[{"id":"old"},{"id":"video"}],"updatedAt":"2099-01-01T00:00:00Z","remoteContentHash":"local-only","viewport":{"x":500,"y":10,"k":3}}`)
|
||||
saved, err := svc.UpsertUserCanvasProject(actor.ID, update)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if saved.Revision != 2 || saved.UpdatedAt.Year() == 2099 {
|
||||
t.Fatalf("invalid server metadata: %#v", saved)
|
||||
}
|
||||
_, err = svc.UpsertUserCanvasProject(actor.ID, update)
|
||||
if !errors.As(err, &appError) || appError.Status != http.StatusConflict {
|
||||
t.Fatalf("stale save = %v", err)
|
||||
}
|
||||
got, err := svc.UserCanvasProject(actor.ID, "canvas")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var project map[string]any
|
||||
if err := json.Unmarshal(got, &project); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if project["revision"] != float64(2) || len(project["nodes"].([]any)) != 2 {
|
||||
t.Fatalf("read lost metadata/content: %s", got)
|
||||
}
|
||||
if project["remoteContentHash"] != nil || project["viewport"].(map[string]any)["x"] != float64(0) {
|
||||
t.Fatalf("content save persisted local preferences: %s", got)
|
||||
}
|
||||
if _, err := svc.UserCanvasProject("unrelated", "canvas"); err == nil {
|
||||
t.Fatal("unrelated user could read canvas")
|
||||
}
|
||||
}
|
||||
|
||||
func newCanvasHistoryTestService(t *testing.T) *Service {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "canvas.db")), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.CanvasProject{}, &model.CanvasSnapshot{}, &model.CanvasSnapshotResource{}, &model.Resource{}, &model.Asset{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sqlDB, _ := db.DB()
|
||||
t.Cleanup(func() { _ = sqlDB.Close() })
|
||||
return New(repository.New(db), nil)
|
||||
}
|
||||
@@ -4,11 +4,13 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"infinite-canvas/backend/internal/kernel"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
"infinite-canvas/backend/internal/repository"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -17,19 +19,30 @@ type AssetsSyncRequest struct {
|
||||
Assets []json.RawMessage `json:"assets"`
|
||||
}
|
||||
|
||||
type CanvasProjectsSyncRequest struct {
|
||||
Projects []json.RawMessage `json:"projects"`
|
||||
type UserDataSummary struct {
|
||||
ID string `json:"id"`
|
||||
FolderID string `json:"folderId,omitempty"`
|
||||
Kind string `json:"kind,omitempty"`
|
||||
Category string `json:"category,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Title string `json:"title"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
Revision int64 `json:"revision,omitempty"`
|
||||
SaveAudit *CanvasSaveAudit `json:"-"`
|
||||
}
|
||||
|
||||
type UserDataSummary struct {
|
||||
ID string `json:"id"`
|
||||
FolderID string `json:"folderId,omitempty"`
|
||||
Kind string `json:"kind,omitempty"`
|
||||
Category string `json:"category,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Title string `json:"title"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
type CanvasSaveAudit struct {
|
||||
NodesBefore int
|
||||
NodesAfter int
|
||||
}
|
||||
|
||||
func canvasNodeCount(payload string) int {
|
||||
var document struct {
|
||||
Nodes []json.RawMessage `json:"nodes"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(payload), &document)
|
||||
return len(document.Nodes)
|
||||
}
|
||||
|
||||
type UserDataSnapshot struct {
|
||||
@@ -173,7 +186,11 @@ func (s *Service) UserCanvasProjects(userID string) ([]json.RawMessage, error) {
|
||||
result := make([]json.RawMessage, 0, len(projects))
|
||||
for _, project := range projects {
|
||||
if strings.TrimSpace(project.PayloadJSON) != "" {
|
||||
result = append(result, json.RawMessage(project.PayloadJSON))
|
||||
payload, err := canvasProjectPayload(project)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, payload)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
@@ -186,7 +203,7 @@ func (s *Service) UserCanvasProjectSummaries(userID string) ([]UserDataSummary,
|
||||
}
|
||||
result := make([]UserDataSummary, 0, len(projects))
|
||||
for _, project := range projects {
|
||||
result = append(result, UserDataSummary{ID: project.ID, Title: project.Title, CreatedAt: project.CreatedAt, UpdatedAt: project.UpdatedAt})
|
||||
result = append(result, UserDataSummary{ID: project.ID, Title: project.Title, CreatedAt: project.CreatedAt, UpdatedAt: project.UpdatedAt, Revision: project.Revision})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -196,14 +213,31 @@ func (s *Service) UserCanvasProject(userID string, id string) (json.RawMessage,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.RawMessage(project.PayloadJSON), nil
|
||||
return canvasProjectPayload(*project)
|
||||
}
|
||||
|
||||
func (s *Service) UpsertUserCanvasProject(userID string, raw json.RawMessage) (UserDataSummary, error) {
|
||||
return s.upsertUserCanvasProjectWithHistory(userID, raw, "automatic")
|
||||
}
|
||||
|
||||
func (s *Service) upsertUserCanvasProjectWithHistory(userID string, raw json.RawMessage, reason string) (UserDataSummary, error) {
|
||||
var version struct {
|
||||
Revision *int64 `json:"revision"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &version); err != nil {
|
||||
return UserDataSummary{}, kernel.BadAuthRequest("画布版本格式错误")
|
||||
}
|
||||
if version.Revision == nil {
|
||||
return UserDataSummary{}, kernel.NewAppError(http.StatusPreconditionRequired, "缺少画布版本,请保留本地草稿后重新加载画布")
|
||||
}
|
||||
if *version.Revision < 0 || *version.Revision >= 9007199254740991 {
|
||||
return UserDataSummary{}, kernel.BadAuthRequest("画布版本无效")
|
||||
}
|
||||
project, err := canvasProjectFromJSON(userID, raw)
|
||||
if err != nil {
|
||||
return UserDataSummary{}, err
|
||||
}
|
||||
var audit CanvasSaveAudit
|
||||
err = s.host.WithStorageLock(func() error {
|
||||
if err := s.ValidateCanvasMediaAssets(userID, raw); err != nil {
|
||||
return err
|
||||
@@ -213,15 +247,51 @@ func (s *Service) UpsertUserCanvasProject(userID string, raw json.RawMessage) (U
|
||||
return existingErr
|
||||
}
|
||||
existingBytes := int64(0)
|
||||
project.Revision = *version.Revision
|
||||
project.UpdatedAt = time.Now().UTC()
|
||||
if existing != nil {
|
||||
existingBytes = int64(len([]byte(existing.PayloadJSON)))
|
||||
project.CreatedAt = existing.CreatedAt
|
||||
}
|
||||
if err := s.host.StructuredQuota(userID, "canvas", errors.Is(existingErr, gorm.ErrRecordNotFound), int64(len(raw))-existingBytes); err != nil {
|
||||
if (existing == nil && project.Revision != 0) || (existing != nil && project.Revision != existing.Revision) {
|
||||
return canvasRevisionConflict()
|
||||
}
|
||||
var payload map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &payload); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.repo.UpsertCanvasProject(&project); err != nil {
|
||||
delete(payload, "revision")
|
||||
delete(payload, "remoteContentHash")
|
||||
payload["viewport"] = json.RawMessage(`{"x":0,"y":0,"k":1}`)
|
||||
if existing != nil {
|
||||
var previous map[string]json.RawMessage
|
||||
if json.Unmarshal([]byte(existing.PayloadJSON), &previous) == nil && previous["viewport"] != nil {
|
||||
payload["viewport"] = previous["viewport"]
|
||||
}
|
||||
}
|
||||
payload["createdAt"], _ = json.Marshal(project.CreatedAt)
|
||||
payload["updatedAt"], _ = json.Marshal(project.UpdatedAt)
|
||||
cleaned, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
project.PayloadJSON = string(cleaned)
|
||||
if err := s.host.StructuredQuota(userID, "canvas", errors.Is(existingErr, gorm.ErrRecordNotFound), int64(len(cleaned))-existingBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := SaveDocumentWithHistory(s.repo, existing, &project, reason); err != nil {
|
||||
if errors.Is(err, repository.ErrCanvasRevisionConflict) {
|
||||
return canvasRevisionConflict()
|
||||
}
|
||||
if errors.Is(err, repository.ErrCanvasHistoryResourceMissing) {
|
||||
return kernel.NewAppError(http.StatusConflict, "画布引用的素材已变化,当前内容未被覆盖,请保留草稿并重新加载")
|
||||
}
|
||||
return err
|
||||
}
|
||||
audit.NodesAfter = canvasNodeCount(project.PayloadJSON)
|
||||
if existing != nil {
|
||||
audit.NodesBefore = canvasNodeCount(existing.PayloadJSON)
|
||||
}
|
||||
if existingErr != nil || existing.PayloadJSON != project.PayloadJSON || existing.Title != project.Title {
|
||||
s.host.RecordActivity(userID, "canvas", 1)
|
||||
}
|
||||
@@ -230,47 +300,13 @@ func (s *Service) UpsertUserCanvasProject(userID string, raw json.RawMessage) (U
|
||||
if err != nil {
|
||||
return UserDataSummary{}, err
|
||||
}
|
||||
return UserDataSummary{ID: project.ID, Title: project.Title, CreatedAt: project.CreatedAt, UpdatedAt: project.UpdatedAt}, nil
|
||||
return UserDataSummary{ID: project.ID, Title: project.Title, CreatedAt: project.CreatedAt, UpdatedAt: project.UpdatedAt, Revision: project.Revision, SaveAudit: &audit}, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteUserCanvasProject(userID string, id string) error {
|
||||
return s.repo.DeleteCanvasProject(userID, id)
|
||||
}
|
||||
|
||||
func (s *Service) ReplaceUserCanvasProjects(userID string, req CanvasProjectsSyncRequest) ([]json.RawMessage, error) {
|
||||
projects := make([]model.CanvasProject, 0, len(req.Projects))
|
||||
var totalBytes int64
|
||||
for _, raw := range req.Projects {
|
||||
item, err := canvasProjectFromJSON(userID, raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
projects = append(projects, item)
|
||||
totalBytes += int64(len(raw))
|
||||
}
|
||||
err := s.host.WithStorageLock(func() error {
|
||||
for _, raw := range req.Projects {
|
||||
if err := s.ValidateCanvasMediaAssets(userID, raw); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := s.host.StructuredReplacementQuota(userID, "canvas", len(projects), totalBytes); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.repo.ReplaceCanvasProjects(userID, projects); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(projects) > 0 {
|
||||
s.host.RecordActivity(userID, "canvas", 1)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.UserCanvasProjects(userID)
|
||||
}
|
||||
|
||||
func AssetFromJSON(userID string, raw json.RawMessage) (model.Asset, error) {
|
||||
if err := ValidateSyncedPayload(raw, "素材"); err != nil {
|
||||
return model.Asset{}, err
|
||||
|
||||
@@ -40,6 +40,7 @@ type CanvasLibrarySummary struct {
|
||||
ID string `json:"id"`
|
||||
ProjectID string `json:"projectId,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Revision int64 `json:"revision"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
NodeCount int `json:"nodeCount"`
|
||||
@@ -107,7 +108,7 @@ func (s *Service) UserCanvasProjectsPage(userID string, page int, pageSize int,
|
||||
item["metadata"] = metadata
|
||||
preview = append(preview, item)
|
||||
}
|
||||
result.Projects = append(result.Projects, CanvasLibrarySummary{ID: project.ID, ProjectID: project.ProjectID, Title: project.Title, CreatedAt: project.CreatedAt, UpdatedAt: project.UpdatedAt, NodeCount: len(document.Nodes), PreviewNodes: preview})
|
||||
result.Projects = append(result.Projects, CanvasLibrarySummary{ID: project.ID, ProjectID: project.ProjectID, Title: project.Title, Revision: project.Revision, CreatedAt: project.CreatedAt, UpdatedAt: project.UpdatedAt, NodeCount: len(document.Nodes), PreviewNodes: preview})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
Reference in new issue
Block a user