feat(collab): redesign note collaboration with REST auto-save, opt-in live session, and block locking
MindSift CI & Docker Release / Build, Test in Container & Push (push) Successful in 59s
MindSift CI & Docker Release / Build, Test in Container & Push (push) Successful in 59s
This commit is contained in:
1 parent
50b017f387
commit
0e06cc5577
11 files changed
+1373
-239
No files matched your search
@@ -145,6 +145,13 @@ func (s *Server) Router() http.Handler {
|
||||
r.Post("/api/v1/documents/{id}/shares", s.handleCreateDocShare)
|
||||
r.Delete("/api/v1/documents/{id}/shares/{userId}", s.handleDeleteDocShare)
|
||||
|
||||
// Document Locks & Live-Collaboration Sessions
|
||||
r.Get("/api/v1/documents/{id}/locks", s.handleGetDocLocks)
|
||||
r.Post("/api/v1/documents/{id}/blocks/{blockId}/lock", s.handleLockBlock)
|
||||
r.Post("/api/v1/documents/{id}/blocks/{blockId}/unlock", s.handleUnlockBlock)
|
||||
r.Post("/api/v1/documents/{id}/live/start", s.handleStartLiveSession)
|
||||
r.Post("/api/v1/documents/{id}/live/end", s.handleEndLiveSession)
|
||||
|
||||
// Shared Lists & Realtime Collaboration
|
||||
r.Get("/api/v1/lists", s.handleGetAllLists)
|
||||
r.Post("/api/v1/lists", s.handleCreateList)
|
||||
@@ -923,6 +930,19 @@ func (s *Server) handleUpdateDocument(w http.ResponseWriter, r *http.Request) {
|
||||
userID := auth.GetUserID(r.Context())
|
||||
docID := chi.URLParam(r, "id")
|
||||
|
||||
if s.wsHub != nil {
|
||||
if ls := s.wsHub.GetLiveSession(docID); ls != nil && ls.InitiatorID != userID {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusLocked)
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"error": "Dokument wird aktuell in einer Live-Sitzung bearbeitet",
|
||||
"lockedBy": ls.InitiatorName,
|
||||
"isLocked": true,
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Title *string `json:"title"`
|
||||
Icon *string `json:"icon"`
|
||||
@@ -954,6 +974,19 @@ func (s *Server) handlePatchDocumentBlocks(w http.ResponseWriter, r *http.Reques
|
||||
userID := auth.GetUserID(r.Context())
|
||||
docID := chi.URLParam(r, "id")
|
||||
|
||||
if s.wsHub != nil {
|
||||
if ls := s.wsHub.GetLiveSession(docID); ls != nil && ls.InitiatorID != userID {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusLocked)
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"error": "Dokument wird aktuell in einer Live-Sitzung bearbeitet",
|
||||
"lockedBy": ls.InitiatorName,
|
||||
"isLocked": true,
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var req domain.DocBlocksPatchRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Ungültiges JSON")
|
||||
@@ -1381,6 +1414,169 @@ func (s *Server) handleGetCollaborators(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, http.StatusOK, users)
|
||||
}
|
||||
|
||||
// --- DOCUMENT LOCKS & LIVE COLLABORATION SESSIONS ---
|
||||
|
||||
func (s *Server) handleGetDocLocks(w http.ResponseWriter, r *http.Request) {
|
||||
docID := chi.URLParam(r, "id")
|
||||
var blockLocks []domain.BlockLockInfo
|
||||
var liveSession *domain.LiveSessionInfo
|
||||
if s.wsHub != nil {
|
||||
blockLocks = s.wsHub.GetDocBlockLocks(docID)
|
||||
liveSession = s.wsHub.GetLiveSession(docID)
|
||||
}
|
||||
if blockLocks == nil {
|
||||
blockLocks = []domain.BlockLockInfo{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, domain.DocLocksResponse{
|
||||
DocID: docID,
|
||||
BlockLocks: blockLocks,
|
||||
LiveSession: liveSession,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleLockBlock(w http.ResponseWriter, r *http.Request) {
|
||||
userID := auth.GetUserID(r.Context())
|
||||
docID := chi.URLParam(r, "id")
|
||||
blockID := chi.URLParam(r, "blockId")
|
||||
|
||||
// If live session is active by someone else, reject
|
||||
if s.wsHub != nil {
|
||||
if ls := s.wsHub.GetLiveSession(docID); ls != nil && ls.InitiatorID != userID {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusLocked)
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"error": "Dokument wird aktuell in einer Live-Sitzung bearbeitet",
|
||||
"lockedBy": ls.InitiatorName,
|
||||
"isLocked": true,
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
user, _ := s.store.GetUserByID(userID)
|
||||
userName := "Anonym"
|
||||
userColor := "#3b82f6"
|
||||
if user != nil {
|
||||
if user.DisplayName != "" {
|
||||
userName = user.DisplayName
|
||||
} else {
|
||||
userName = user.Username
|
||||
}
|
||||
}
|
||||
|
||||
var req struct {
|
||||
UserColor string `json:"userColor"`
|
||||
TTLSeconds int `json:"ttlSeconds"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||
if req.UserColor != "" {
|
||||
userColor = req.UserColor
|
||||
}
|
||||
ttl := 30 * time.Second
|
||||
if req.TTLSeconds > 5 && req.TTLSeconds <= 120 {
|
||||
ttl = time.Duration(req.TTLSeconds) * time.Second
|
||||
}
|
||||
|
||||
if s.wsHub != nil {
|
||||
lockInfo, ok, existing := s.wsHub.AcquireBlockLock(docID, blockID, userID, userName, userColor, ttl)
|
||||
if !ok && existing != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"error": "Block ist von anderem Benutzer gesperrt",
|
||||
"lockedBy": existing.UserName,
|
||||
"lock": existing,
|
||||
})
|
||||
return
|
||||
}
|
||||
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_BLOCK_LOCKED", lockInfo, nil)
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"success": true,
|
||||
"lock": lockInfo,
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleUnlockBlock(w http.ResponseWriter, r *http.Request) {
|
||||
userID := auth.GetUserID(r.Context())
|
||||
docID := chi.URLParam(r, "id")
|
||||
blockID := chi.URLParam(r, "blockId")
|
||||
|
||||
if s.wsHub != nil {
|
||||
s.wsHub.ReleaseBlockLock(docID, blockID, userID)
|
||||
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_BLOCK_UNLOCKED", map[string]string{
|
||||
"docId": docID,
|
||||
"blockId": blockID,
|
||||
"userId": userID,
|
||||
}, nil)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleStartLiveSession(w http.ResponseWriter, r *http.Request) {
|
||||
userID := auth.GetUserID(r.Context())
|
||||
docID := chi.URLParam(r, "id")
|
||||
|
||||
user, _ := s.store.GetUserByID(userID)
|
||||
userName := "Anonym"
|
||||
if user != nil {
|
||||
if user.DisplayName != "" {
|
||||
userName = user.DisplayName
|
||||
} else {
|
||||
userName = user.Username
|
||||
}
|
||||
}
|
||||
|
||||
ttl := 120 * time.Second // 2 min lease with heartbeat while active
|
||||
if s.wsHub != nil {
|
||||
info, ok, existing := s.wsHub.StartLiveSession(docID, userID, userName, ttl)
|
||||
if !ok && existing != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusConflict)
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"error": "Live-Sitzung bereits von anderem Benutzer aktiv",
|
||||
"session": existing,
|
||||
"initiator": existing.InitiatorName,
|
||||
})
|
||||
return
|
||||
}
|
||||
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_LIVE_STARTED", info, nil)
|
||||
if users, err := s.store.GetAuthorizedDocUsers(docID); err == nil {
|
||||
for _, uid := range users {
|
||||
s.wsHub.BroadcastToUser(uid, "DOC_LIVE_STARTED", info)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"success": true,
|
||||
"session": info,
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) handleEndLiveSession(w http.ResponseWriter, r *http.Request) {
|
||||
userID := auth.GetUserID(r.Context())
|
||||
docID := chi.URLParam(r, "id")
|
||||
|
||||
if s.wsHub != nil {
|
||||
s.wsHub.EndLiveSession(docID, userID)
|
||||
evt := map[string]string{
|
||||
"docId": docID,
|
||||
"userId": userID,
|
||||
}
|
||||
s.wsHub.BroadcastRoom("doc:"+docID, "DOC_LIVE_ENDED", evt, nil)
|
||||
if users, err := s.store.GetAuthorizedDocUsers(docID); err == nil {
|
||||
for _, uid := range users {
|
||||
s.wsHub.BroadcastToUser(uid, "DOC_LIVE_ENDED", evt)
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"success": true})
|
||||
}
|
||||
|
||||
// --- DOCUMENT REALTIME WEBSOCKET ROOM ---
|
||||
|
||||
func (s *Server) authenticateUserFromReq(r *http.Request) string {
|
||||
|
||||
@@ -1295,6 +1295,127 @@ func TestTokenBlacklistingAndTokenVersionRevocation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlockLockingAndLiveSessionGuards(t *testing.T) {
|
||||
srv, store, _ := setupTestServer(t)
|
||||
router := srv.Router()
|
||||
|
||||
userA, _ := store.CreateUser("user_a_lock@example.com", "hash", "User A", "member")
|
||||
tokenA, _ := auth.GenerateToken(srv.cfg.JWTSecret, userA.ID, userA.Email, userA.DisplayName, userA.TokenVersion)
|
||||
|
||||
userB, _ := store.CreateUser("user_b_lock@example.com", "hash", "User B", "member")
|
||||
tokenB, _ := auth.GenerateToken(srv.cfg.JWTSecret, userB.ID, userB.Email, userB.DisplayName, userB.TokenVersion)
|
||||
|
||||
// Create document owned by User A, shared with User B
|
||||
blocks := []domain.DocumentBlock{
|
||||
{ID: "b1", Type: "bullet", Content: "Row 1", Level: 0},
|
||||
{ID: "b2", Type: "bullet", Content: "Row 2", Level: 0},
|
||||
}
|
||||
doc, err := store.CreateDocument(userA.ID, "", "Lock Test Doc", "📝", "", blocks, nil, false)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateDocument failed: %v", err)
|
||||
}
|
||||
_, _ = store.CreateDocShare(userA.ID, doc.ID, userB.ID, "write")
|
||||
|
||||
// 1. Initial locks should be empty
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/documents/"+doc.ID+"/locks", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenA)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("get locks failed: %d", rec.Code)
|
||||
}
|
||||
var locksResp domain.DocLocksResponse
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &locksResp)
|
||||
if len(locksResp.BlockLocks) != 0 || locksResp.LiveSession != nil {
|
||||
t.Fatalf("expected 0 locks initially, got %v", locksResp)
|
||||
}
|
||||
|
||||
// 2. User A locks block b1
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/lock", bytes.NewReader([]byte(`{"ttlSeconds": 30}`)))
|
||||
req.Header.Set("Authorization", "Bearer "+tokenA)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("user A lock b1 failed: %d, body: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// 3. User B tries to lock b1 -> must receive 409 Conflict
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/lock", bytes.NewReader([]byte(`{"ttlSeconds": 30}`)))
|
||||
req.Header.Set("Authorization", "Bearer "+tokenB)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("expected 409 Conflict for user B on b1, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// 4. User A unlocks b1
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/unlock", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenA)
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("user A unlock b1 failed: %d", rec.Code)
|
||||
}
|
||||
|
||||
// 5. User B can now lock b1
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/lock", bytes.NewReader([]byte(`{"ttlSeconds": 30}`)))
|
||||
req.Header.Set("Authorization", "Bearer "+tokenB)
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("user B lock b1 should succeed now, got %d", rec.Code)
|
||||
}
|
||||
// User B unlocks b1
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/blocks/b1/unlock", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenB)
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
// 6. User A starts a Live-Session on doc
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/live/start", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenA)
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("user A start live session failed: %d, body: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// 7. User B tries to patch document blocks while User A's live session is active -> must receive 423 Locked!
|
||||
patchBody, _ := json.Marshal(domain.DocBlocksPatchRequest{
|
||||
Upserted: []domain.DocumentBlock{{ID: "b2", Content: "Hacked by User B"}},
|
||||
})
|
||||
req = httptest.NewRequest(http.MethodPatch, "/api/v1/documents/"+doc.ID+"/blocks", bytes.NewReader(patchBody))
|
||||
req.Header.Set("Authorization", "Bearer "+tokenB)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusLocked {
|
||||
t.Fatalf("expected 423 Locked for User B while live session is active, got %d, body: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// 8. User A ends the Live-Session
|
||||
req = httptest.NewRequest(http.MethodPost, "/api/v1/documents/"+doc.ID+"/live/end", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenA)
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("user A end live session failed: %d", rec.Code)
|
||||
}
|
||||
|
||||
// 9. User B can now edit again
|
||||
req = httptest.NewRequest(http.MethodPatch, "/api/v1/documents/"+doc.ID+"/blocks", bytes.NewReader(patchBody))
|
||||
req.Header.Set("Authorization", "Bearer "+tokenB)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("User B edit should succeed after live session ended, got %d, body: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user