package repository import ( "crypto/rand" "database/sql" "encoding/hex" "errors" "fmt" "strings" "time" "github.com/lib/pq" ) // ErrNotFound is returned when a row is absent (or not owned by the scoping device). var ErrNotFound = errors.New("resource not found") // ErrNameConflict is returned when a sibling with the same name already exists. var ErrNameConflict = errors.New("name conflict") // NewID returns an opaque lowercase 32-hex identifier (charset ^[0-9a-f]{32}$), // mirroring the mobile's lower(hex(randomblob(16))). Never a UUID. // Panics on entropy failure (legacy) — prefer NewIDErr for new code. func NewID() string { id, err := NewIDErr() if err != nil { panic(fmt.Sprintf("crypto/rand failed: %v", err)) } return id } // NewIDErr is the non-panicking variant (cf. FEEDBACK A5). func NewIDErr() (string, error) { buf := make([]byte, 16) if _, err := rand.Read(buf); err != nil { return "", fmt.Errorf("crypto/rand failed: %w", err) } return hex.EncodeToString(buf), nil } func isUniqueViolation(err error) bool { var pqErr *pq.Error return errors.As(err, &pqErr) && pqErr.Code == "23505" } // isForeignKeyViolation reports a Postgres FK violation (23503). Une // violation de FK parent (dossier cible disparu en course) est mappée vers // ErrNotFound — cible inexistante — plutôt que de fuir en 500. func isForeignKeyViolation(err error) bool { var pqErr *pq.Error return errors.As(err, &pqErr) && pqErr.Code == "23503" } // SetContentHash stores the SHA-256 of the live bytes (V3 S5 duplicates). // Owner-scoped, live rows. Best-effort côté service (jamais d'erreur vers // le client). func (r *Resources) SetContentHash(ownerID, resourceID, hash string) error { result, err := r.DB.Exec( `UPDATE resources SET content_hash = NULLIF($3, ''), updated_at = NOW() WHERE resource_id = $1 AND user_id = $2 AND type = 'file' AND deleted_at IS NULL`, resourceID, ownerID, hash, ) if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return ErrNotFound } return nil } // SetScanSession records the opaque client scan-session of a resource // (V3 S5 same_scan — drift informatif, jamais autorisant). Owner-scoped. func (r *Resources) SetScanSession(ownerID, resourceID, sessionID string) error { result, err := r.DB.Exec( `UPDATE resources SET scan_session_id = NULLIF($3, ''), updated_at = NOW() WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL`, resourceID, ownerID, sessionID, ) if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return ErrNotFound } return nil } // MissingHash identifies a live file without content_hash (boot backfill). type MissingHash struct { UserID string ResourceID string } // ListMissingHashes returns up to limit live files with bytes but no hash. func (r *Resources) ListMissingHashes(limit int) ([]MissingHash, error) { rows, err := r.DB.Query( `SELECT user_id, resource_id FROM resources WHERE type = 'file' AND deleted_at IS NULL AND user_id IS NOT NULL AND has_content = TRUE AND (content_hash IS NULL OR content_hash = '') ORDER BY updated_at ASC LIMIT $1`, limit, ) if err != nil { return nil, err } defer rows.Close() var out []MissingHash for rows.Next() { var m MissingHash if err := rows.Scan(&m.UserID, &m.ResourceID); err != nil { return nil, err } out = append(out, m) } return out, rows.Err() } // StorageUsage aggregates a user's footprint (V3 S6 A2 — calculé, jamais // stocké). Les trashés sont exclus (octets récupérables à la purge). type StorageUsage struct { UsedBytes int64 FileCount int TrashCount int TrashedBytes int64 } // StorageUsage sums live file bytes + counts (live + trashed) for a user. func (r *Resources) StorageUsage(ownerID string) (StorageUsage, error) { var u StorageUsage err := r.DB.QueryRow( `SELECT COALESCE(SUM(size_bytes), 0), COUNT(*) FROM resources WHERE user_id = $1 AND type = 'file' AND deleted_at IS NULL`, ownerID, ).Scan(&u.UsedBytes, &u.FileCount) if err != nil { return StorageUsage{}, err } err = r.DB.QueryRow( `SELECT COUNT(*), COALESCE(SUM(size_bytes), 0) FROM resources WHERE user_id = $1 AND deleted_at IS NOT NULL`, ownerID, ).Scan(&u.TrashCount, &u.TrashedBytes) if err != nil { return StorageUsage{}, err } return u, nil } type FileRow struct { ID string Name string Size int64 MimeType string FolderID string CreatedAt time.Time UpdatedAt time.Time OcrText string HasContent bool } type FolderRow struct { ID string Name string ParentID string } // Resources implements resource persistence, always scoped by owner device. type Resources struct { DB *sql.DB } // sortColumns maps contract `sort` values to safe SQL columns. var sortColumns = map[string]string{ "size": "size_bytes", "created_at": "created_at", "updated_at": "updated_at", "added_at": "created_at", } func sortClause(sort, order string) (string, string) { column, ok := sortColumns[sort] if !ok { column = "created_at" } direction := "DESC" if order == "asc" { direction = "ASC" } return column, direction } // grantedCTE expands, for the user bound to $1, the set of accessible // resource ids — owned rows (each its own seed) + active direct grants + // every node reached by an inherit=true grant up its chain (passing through // intermediate nodes, per docs/api-v1.md §6.2 rule 5). Only the visibility // SET matters here (which resources the user can read, viewer+); the effective // rank is validated by repository.Shares.EffectiveAccess. Walk bounded at // depth < 100. Append a query that references // `resource_id IN (SELECT id FROM granted)`. const grantedCTE = ` seeded(id, type, rank, inherit, depth) AS ( SELECT r.resource_id, r.type, 4::int, FALSE, 0 FROM resources r WHERE r.user_id = $1 AND r.deleted_at IS NULL UNION ALL SELECT r.resource_id, r.type, CASE sh.access WHEN 'viewer' THEN 1 WHEN 'commenter' THEN 2 WHEN 'editor' THEN 3 ELSE 0 END, sh.inherit, 0 FROM shares sh JOIN resources r ON r.resource_id = sh.resource_id WHERE ` + granteeMatch + ` AND sh.revoked_at IS NULL AND (sh.expires_at IS NULL OR sh.expires_at > NOW()) AND r.deleted_at IS NULL ), granted(id, rank, inherit, depth) AS ( SELECT id, rank, inherit, 0 FROM seeded UNION ALL SELECT r.resource_id, g.rank, TRUE, g.depth + 1 FROM resources r JOIN granted g ON r.parent_id = g.id WHERE g.inherit AND g.rank BETWEEN 1 AND 3 AND r.deleted_at IS NULL AND g.depth < 100 )` // insert persiste une ligne file/folder avec parent-check ATOMIQUE // (single-statement INSERT...SELECT) : le dossier parent (quand non vide) // doit exister, appartenir au même owner, être un folder non supprimé — // sinon ErrNotFound. L'ancien SELECT-then-INSERT (TOCTOU : parent supprimé // entre check et insert → FK 500) est remplacé ; une violation FK résiduelle // (course) est mappée vers ErrNotFound, jamais 500. func (r *Resources) insert(ownerID, id, name, parentResourceID, resourceType string, size int64, mimeType, extension *string) error { result, err := r.DB.Exec( `INSERT INTO resources (resource_id, type, name, parent_id, user_id, size_bytes, mime_type, extension) SELECT $1, $2, $3, NULLIF($4, ''), $5, $6, $7, $8 WHERE $4 = '' OR EXISTS ( SELECT 1 FROM resources WHERE resource_id = $4 AND user_id = $5 AND type = 'folder' AND deleted_at IS NULL )`, id, resourceType, name, parentResourceID, ownerID, size, mimeType, extension, ) if isUniqueViolation(err) { return ErrNameConflict } if isForeignKeyViolation(err) { return fmt.Errorf("folder %s: %w", parentResourceID, ErrNotFound) } if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return fmt.Errorf("folder %s: %w", parentResourceID, ErrNotFound) } return nil } // InsertFile persists a file metadata row for the owner device. The parent // folder (when non-empty) must belong to the same device. func (r *Resources) InsertFile(ownerID, id, name, folderResourceID string, size int64, mimeType, extension *string) error { return r.insert(ownerID, id, name, folderResourceID, "file", size, mimeType, extension) } // InsertFolder persists a folder metadata row. func (r *Resources) InsertFolder(ownerID, id, name, parentResourceID string) error { return r.insert(ownerID, id, name, parentResourceID, "folder", 0, nil, nil) } const fileColumns = `resource_id, name, size_bytes, COALESCE(mime_type, ''), COALESCE(parent_id, ''), created_at, updated_at, COALESCE(ocr_text, ''), COALESCE(has_content, FALSE)` func (r *Resources) scanFile(scan func(...any) error) (FileRow, error) { var row FileRow err := scan(&row.ID, &row.Name, &row.Size, &row.MimeType, &row.FolderID, &row.CreatedAt, &row.UpdatedAt, &row.OcrText, &row.HasContent) return row, err } // ListFiles returns the owner device's files (within a folder, or at the // root when folderResourceID is empty), plus the total count. func (r *Resources) ListFiles(ownerID, folderResourceID string, limit, offset int, sort, order string) ([]FileRow, int, error) { column, direction := sortClause(sort, order) where := `type = 'file' AND deleted_at IS NULL AND user_id = $1 AND ($2::text = '' AND parent_id IS NULL OR parent_id = $2)` var total int if err := r.DB.QueryRow(`SELECT COUNT(*) FROM resources WHERE `+where, ownerID, folderResourceID).Scan(&total); err != nil { return nil, 0, err } rows, err := r.DB.Query( fmt.Sprintf(`SELECT %s FROM resources WHERE %s ORDER BY %s %s LIMIT $3 OFFSET $4`, fileColumns, where, column, direction), ownerID, folderResourceID, limit, offset, ) if err != nil { return nil, 0, err } defer rows.Close() files := make([]FileRow, 0) for rows.Next() { row, err := r.scanFile(rows.Scan) if err != nil { return nil, 0, err } files = append(files, row) } return files, total, rows.Err() } // ListFilesVisible returns the user's accessible files (owned or shared, // viewer+) within a folder (or at the root when folderResourceID is empty). func (r *Resources) ListFilesVisible(userID, folderResourceID string, limit, offset int, sort, order string) ([]FileRow, int, error) { column, direction := sortClause(sort, order) where := `type = 'file' AND deleted_at IS NULL AND resource_id IN (SELECT id FROM granted) AND ($2::text = '' AND parent_id IS NULL OR parent_id = $2)` var total int if err := r.DB.QueryRow(`WITH RECURSIVE `+grantedCTE+` SELECT COUNT(*) FROM resources WHERE `+where, userID, folderResourceID).Scan(&total); err != nil { return nil, 0, err } rows, err := r.DB.Query( fmt.Sprintf(`WITH RECURSIVE %s SELECT %s FROM resources WHERE %s ORDER BY %s %s LIMIT $3 OFFSET $4`, grantedCTE, fileColumns, where, column, direction), userID, folderResourceID, limit, offset, ) if err != nil { return nil, 0, err } defer rows.Close() files := make([]FileRow, 0) for rows.Next() { row, err := r.scanFile(rows.Scan) if err != nil { return nil, 0, err } files = append(files, row) } return files, total, rows.Err() } // GetFile returns a file owned by the device (no-rows → ErrNotFound). func (r *Resources) GetFile(ownerID, resourceID string) (FileRow, error) { row := r.DB.QueryRow( `SELECT `+fileColumns+` FROM resources WHERE type = 'file' AND deleted_at IS NULL AND user_id = $1 AND resource_id = $2`, ownerID, resourceID, ) file, err := r.scanFile(row.Scan) if errors.Is(err, sql.ErrNoRows) { return FileRow{}, ErrNotFound } return file, err } // GetFileVisible returns a file the user can access (owned or shared, viewer+). func (r *Resources) GetFileVisible(userID, resourceID string) (FileRow, error) { row := r.DB.QueryRow(`WITH RECURSIVE `+grantedCTE+` SELECT `+fileColumns+` FROM resources WHERE type = 'file' AND deleted_at IS NULL AND resource_id = $2 AND resource_id IN (SELECT id FROM granted)`, userID, resourceID, ) file, err := r.scanFile(row.Scan) if errors.Is(err, sql.ErrNoRows) { return FileRow{}, ErrNotFound } return file, err } // GetResourceOwner returns the owning user_id of any resource (file or folder). // No-rows → ErrNotFound. func (r *Resources) GetResourceOwner(resourceID string) (string, error) { var ownerID string err := r.DB.QueryRow( `SELECT user_id FROM resources WHERE resource_id = $1 AND deleted_at IS NULL`, resourceID, ).Scan(&ownerID) if errors.Is(err, sql.ErrNoRows) { return "", ErrNotFound } return ownerID, err } // GetParentID returns the parent_id ('""' si racine) d'une ressource non // supprimée. No-rows → ErrNotFound. Sert au check de cycle des moves. func (r *Resources) GetParentID(resourceID string) (string, error) { var parent sql.NullString err := r.DB.QueryRow( `SELECT parent_id FROM resources WHERE resource_id = $1 AND deleted_at IS NULL`, resourceID, ).Scan(&parent) if errors.Is(err, sql.ErrNoRows) { return "", ErrNotFound } if err != nil { return "", err } if !parent.Valid { return "", nil } return parent.String, nil } // DeleteFile soft-deletes the file (deleted_at), returning its id. func (r *Resources) DeleteFile(ownerID, resourceID string) (string, error) { result, err := r.DB.Exec( `UPDATE resources SET deleted_at = NOW(), updated_at = NOW() WHERE type = 'file' AND deleted_at IS NULL AND user_id = $1 AND resource_id = $2`, ownerID, resourceID, ) if err != nil { return "", err } affected, err := result.RowsAffected() if err != nil { return "", err } if affected == 0 { return "", ErrNotFound } return resourceID, nil } // SearchFiles returns the owner device's files whose name matches q // (case-insensitive substring, wildcards escaped), plus the total count. func (r *Resources) SearchFiles(ownerID, q string, limit, offset int) ([]FileRow, int, error) { pattern := `%` + escapeLike(q) + `%` where := `type = 'file' AND deleted_at IS NULL AND user_id = $1 AND name ILIKE $2 ESCAPE '\'` var total int if err := r.DB.QueryRow(`SELECT COUNT(*) FROM resources WHERE `+where, ownerID, pattern).Scan(&total); err != nil { return nil, 0, err } rows, err := r.DB.Query( fmt.Sprintf(`SELECT %s FROM resources WHERE %s ORDER BY name ASC LIMIT $3 OFFSET $4`, fileColumns, where), ownerID, pattern, limit, offset, ) if err != nil { return nil, 0, err } defer rows.Close() files := make([]FileRow, 0) for rows.Next() { row, err := r.scanFile(rows.Scan) if err != nil { return nil, 0, err } files = append(files, row) } return files, total, rows.Err() } // SearchFilesVisible returns the user's accessible files (owned or shared, // viewer+) whose name matches q (case-insensitive substring). func (r *Resources) SearchFilesVisible(userID, q string, limit, offset int) ([]FileRow, int, error) { pattern := `%` + escapeLike(q) + `%` where := `type = 'file' AND deleted_at IS NULL AND resource_id IN (SELECT id FROM granted) AND name ILIKE $2 ESCAPE '\'` var total int if err := r.DB.QueryRow(`WITH RECURSIVE `+grantedCTE+` SELECT COUNT(*) FROM resources WHERE `+where, userID, pattern).Scan(&total); err != nil { return nil, 0, err } rows, err := r.DB.Query( fmt.Sprintf(`WITH RECURSIVE %s SELECT %s FROM resources WHERE %s ORDER BY name ASC LIMIT $3 OFFSET $4`, grantedCTE, fileColumns, where), userID, pattern, limit, offset, ) if err != nil { return nil, 0, err } defer rows.Close() files := make([]FileRow, 0) for rows.Next() { row, err := r.scanFile(rows.Scan) if err != nil { return nil, 0, err } files = append(files, row) } return files, total, rows.Err() } func escapeLike(q string) string { replacer := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`) return replacer.Replace(q) } // GetFolder returns a folder row owned by the device (no-rows → ErrNotFound). func (r *Resources) GetFolder(ownerID, resourceID string) (FolderRow, error) { var row FolderRow err := r.DB.QueryRow( `SELECT resource_id, name, COALESCE(parent_id, '') FROM resources WHERE type = 'folder' AND deleted_at IS NULL AND user_id = $1 AND resource_id = $2`, ownerID, resourceID, ).Scan(&row.ID, &row.Name, &row.ParentID) if err == sql.ErrNoRows { return FolderRow{}, ErrNotFound } return row, err } // MoveResource sets parent_id (root when parentResourceID empty) avec // parent-check ATOMIQUE (single-statement) : la cible doit exister, // appartenir au même owner, être un folder non supprimé. Source absente / // non-owned OU cible absente → ErrNotFound (même code : le choix A8 // move-non-owned → NOT_FOUND est appliqué ici, cf. LOT 3 pour la doc // sync). Violation FK résiduelle (course) → ErrNotFound, jamais 500. func (r *Resources) MoveResource(ownerID, resourceID, parentResourceID string) error { result, err := r.DB.Exec( `UPDATE resources SET parent_id = NULLIF($3, ''), updated_at = NOW() WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL AND ($3 = '' OR EXISTS ( SELECT 1 FROM resources WHERE resource_id = $3 AND user_id = $2 AND type = 'folder' AND deleted_at IS NULL ))`, resourceID, ownerID, parentResourceID, ) if err != nil && isUniqueViolation(err) { return ErrNameConflict } if err != nil && isForeignKeyViolation(err) { return fmt.Errorf("folder %s: %w", parentResourceID, ErrNotFound) } if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return ErrNotFound } return nil } // UpdateName renames a resource. Absent / not owned → ErrNotFound. func (r *Resources) UpdateName(ownerID, resourceID, name string) error { result, err := r.DB.Exec( `UPDATE resources SET name = $3, updated_at = NOW() WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL`, resourceID, ownerID, name, ) if err != nil && isUniqueViolation(err) { return ErrNameConflict } if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return ErrNotFound } return nil } // UpdateNameOwned renames a resource OWNED by ownerID. Absent / not owned → // ErrNotFound, sibling homonyme → ErrNameConflict. Variante scopée // canonique (sémantique identique à UpdateName, nom aligné sur TouchOwned // pour LOT 3). func (r *Resources) UpdateNameOwned(ownerID, resourceID, name string) error { return r.UpdateName(ownerID, resourceID, name) } // UpdateNameByID renames a resource without owner scoping — the caller // (service) has already verified the user's effective access (editor+). // Conservée volontairement pour update_metadata : un editor non-owner peut // renommer, UpdateNameOwned rejetterait à tort. func (r *Resources) UpdateNameByID(resourceID, name string) error { result, err := r.DB.Exec( `UPDATE resources SET name = $2, updated_at = NOW() WHERE resource_id = $1 AND deleted_at IS NULL`, resourceID, name, ) if err != nil && isUniqueViolation(err) { return ErrNameConflict } if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return ErrNotFound } return nil } // UpdatePhysical refreshes an existing file row's physical metadata // (size_bytes / mime_type / extension) after a targeted re-upload — used so a // resource created metadata-only (outbox create_resource) receives its bytes // for server-side OCR. Absent / not owned → ErrNotFound. Never renames or moves. // Des octets viennent d'arriver : `has_content` passe à TRUE (V2 lazy). func (r *Resources) UpdatePhysical(ownerID, resourceID string, size int64, mimeType, extension *string) error { result, err := r.DB.Exec( `UPDATE resources SET size_bytes = $3, mime_type = $4, extension = $5, has_content = TRUE, updated_at = NOW() WHERE resource_id = $1 AND user_id = $2 AND type = 'file' AND deleted_at IS NULL`, resourceID, ownerID, size, mimeType, extension, ) if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return ErrNotFound } return nil } // SetHasContent flips the V2 `has_content` flag (lazy healing) : TRUE quand // des octets sont constatés (upload, OpenContent réussi), FALSE quand ils ont // disparu sous UPLOAD_DIR. Best-effort côté service (jamais d'erreur vers le // client). Absent / not owned → ErrNotFound (ignoré par l'appelant). func (r *Resources) SetHasContent(ownerID, resourceID string, has bool) error { result, err := r.DB.Exec( `UPDATE resources SET has_content = $3, updated_at = NOW() WHERE resource_id = $1 AND user_id = $2 AND type = 'file' AND deleted_at IS NULL`, resourceID, ownerID, has, ) if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return ErrNotFound } return nil } // UpdateOcrText writes the server-computed OCR extract onto the resource // (owner-scoped, bumping updated_at so the change flows through the sync // snapshot). The text is then readable by every device of the user AND by // grantees via GET /files/:id/ocr (viewer+, cf. docs/api-v1.md §5). func (r *Resources) UpdateOcrText(ownerID, resourceID, text string) error { result, err := r.DB.Exec( `UPDATE resources SET ocr_text = $3, updated_at = NOW() WHERE resource_id = $1 AND user_id = $2 AND type = 'file' AND deleted_at IS NULL`, resourceID, ownerID, text, ) if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return ErrNotFound } return nil } // SyncDelete soft-deletes a resource; absence is NOT an error (idempotent // terminal state for the outbox). // // Deprecated: V3 trash — préférer TrashResource (récursif sur le subtree). // Conservé comme alias pour compatibilité (même effet sur une ressource // sans enfant : TrashResource ne touche que deleted_at IS NULL). func (r *Resources) SyncDelete(ownerID, resourceID string) error { return r.TrashResource(ownerID, resourceID) } // ExistsOwner reports whether a non-deleted resource belongs to the device. func (r *Resources) ExistsOwner(ownerID, resourceID string) (bool, error) { var exists int err := r.DB.QueryRow( `SELECT 1 FROM resources WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL`, resourceID, ownerID, ).Scan(&exists) if err == sql.ErrNoRows { return false, nil } return err == nil, err } // TouchOwned bumps updated_at on a non-deleted resource OWNED by ownerID so // that the grantee's delta snapshot picks it up after a share is created. // Absent / not owned → ErrNotFound. C'est la variante scopée à utiliser // (LOT 3 : migrer les appelants sync vers TouchOwned). func (r *Resources) TouchOwned(ownerID, resourceID string) error { result, err := r.DB.Exec( `UPDATE resources SET updated_at = NOW() WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL`, resourceID, ownerID, ) if err != nil { return err } affected, err := result.RowsAffected() if err != nil { return err } if affected == 0 { return ErrNotFound } return nil } // TouchResource bumps updated_at on a non-deleted resource so that the // grantee's delta snapshot picks it up after a share is created. // // Deprecated: non scopée (touche n'importe quel owner) — préférer TouchOwned. // Plus aucun appelant sync (migrés vers TouchOwned) ; conservée pour // compatibilité des appelants externes éventuels. func (r *Resources) TouchResource(resourceID string) error { _, err := r.DB.Exec( `UPDATE resources SET updated_at = NOW() WHERE resource_id = $1 AND deleted_at IS NULL`, resourceID, ) return err } // LiveNameAndUpdatedAt returns the current name and updated_at (ms epoch) of // a live resource, any type, unscoped — the caller (sync) has already // verified effective access. Absent/trashed → ErrNotFound. Sert à la // détection de conflits de rename (S6 A4 : baseUpdatedAt périmé). func (r *Resources) LiveNameAndUpdatedAt(resourceID string) (string, int64, error) { var name string var ms int64 err := r.DB.QueryRow( `SELECT name, (EXTRACT(EPOCH FROM updated_at) * 1000)::bigint FROM resources WHERE resource_id = $1 AND deleted_at IS NULL`, resourceID, ).Scan(&name, &ms) if err == sql.ErrNoRows { return "", 0, ErrNotFound } return name, ms, err } // OwnedRow is a snapshot row: resource identity + freshness. type OwnedRow struct { ID string Type string UpdatedAt time.Time } // ListOwned returns the device's non-deleted resources whose updated_at // (in epoch ms) is strictly greater than afterMs (0 = all). func (r *Resources) ListOwned(ownerID string, afterMs int64) ([]OwnedRow, error) { rows, err := r.DB.Query( `SELECT resource_id, type, updated_at FROM resources WHERE user_id = $1 AND deleted_at IS NULL AND (EXTRACT(EPOCH FROM updated_at) * 1000)::bigint > $2 ORDER BY updated_at DESC LIMIT 10000`, ownerID, afterMs, ) if err != nil { return nil, err } defer rows.Close() out := make([]OwnedRow, 0) for rows.Next() { var row OwnedRow if err := rows.Scan(&row.ID, &row.Type, &row.UpdatedAt); err != nil { return nil, err } out = append(out, row) } return out, rows.Err() } // ListRootFolders returns the owner device's top-level folders (parent_id NULL). func (r *Resources) ListRootFolders(ownerID string) ([]FolderRow, error) { rows, err := r.DB.Query( `SELECT resource_id, name, COALESCE(parent_id, '') FROM resources WHERE type = 'folder' AND parent_id IS NULL AND deleted_at IS NULL AND user_id = $1 ORDER BY name ASC`, ownerID, ) if err != nil { return nil, err } defer rows.Close() folders := make([]FolderRow, 0) for rows.Next() { var folder FolderRow if err := rows.Scan(&folder.ID, &folder.Name, &folder.ParentID); err != nil { return nil, err } folders = append(folders, folder) } return folders, rows.Err() } // ListRootFoldersVisible returns the user's accessible top-level folders — // owned (rank 4) or shared (viewer+) at the root. func (r *Resources) ListRootFoldersVisible(userID string) ([]FolderRow, error) { rows, err := r.DB.Query(`WITH RECURSIVE `+grantedCTE+` SELECT resource_id, name, COALESCE(parent_id, '') FROM resources WHERE type = 'folder' AND parent_id IS NULL AND deleted_at IS NULL AND resource_id IN (SELECT id FROM granted) ORDER BY name ASC`, userID, ) if err != nil { return nil, err } defer rows.Close() folders := make([]FolderRow, 0) for rows.Next() { var folder FolderRow if err := rows.Scan(&folder.ID, &folder.Name, &folder.ParentID); err != nil { return nil, err } folders = append(folders, folder) } return folders, rows.Err() } // ExportFileRow is one live file for full export (V3 S7 C3). type ExportFileRow struct { ID string Name string ParentID string Size int64 MimeType string Extension string Hash string OcrText string HasContent bool } // ExportFiles returns ALL live files of a user (bounded — full export). func (r *Resources) ExportFiles(ownerID string, limit int) ([]ExportFileRow, error) { rows, err := r.DB.Query( `SELECT resource_id, name, COALESCE(parent_id, ''), COALESCE(size_bytes, 0), COALESCE(mime_type, ''), COALESCE(extension, ''), COALESCE(content_hash, ''), COALESCE(ocr_text, ''), COALESCE(has_content, FALSE) FROM resources WHERE user_id = $1 AND type = 'file' AND deleted_at IS NULL ORDER BY created_at ASC LIMIT $2`, ownerID, limit, ) if err != nil { return nil, err } defer rows.Close() out := make([]ExportFileRow, 0) for rows.Next() { var row ExportFileRow if err := rows.Scan(&row.ID, &row.Name, &row.ParentID, &row.Size, &row.MimeType, &row.Extension, &row.Hash, &row.OcrText, &row.HasContent); err != nil { return nil, err } out = append(out, row) } return out, rows.Err() } // ExportFolders returns ALL live folders of a user (bounded — full export). func (r *Resources) ExportFolders(ownerID string, limit int) ([]FolderRow, error) { rows, err := r.DB.Query( `SELECT resource_id, name, COALESCE(parent_id, '') FROM resources WHERE user_id = $1 AND type = 'folder' AND deleted_at IS NULL ORDER BY created_at ASC LIMIT $2`, ownerID, limit, ) if err != nil { return nil, err } defer rows.Close() out := make([]FolderRow, 0) for rows.Next() { var folder FolderRow if err := rows.Scan(&folder.ID, &folder.Name, &folder.ParentID); err != nil { return nil, err } out = append(out, folder) } return out, rows.Err() }