Files
Docwell/Server/internal/directory/attachments.go
T
tajniak81andClaude Opus 5.5 e49b1ab34f Add page attachments with images and file blocks
Editors upload files to a page (attach button, paste or drop); images go
into the document as images and other files as download cards. Files are
stored in a new attachments collection, so PocketBase's local or S3
storage applies, and docwell-server streams them after checking the
reader's page access.

Documents keep the file's API path. Because <img> tags cannot send the
Authorization header, clients load files with a short-lived signed file
token (?token=) instead of the session token. Uploads are limited by
DOCWELL_MAX_UPLOAD_MB (default 50), their type is sniffed from the
content, and only images, PDFs and media are served inline, so an
uploaded HTML or SVG file never runs on the API's origin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:51:56 +01:00

221 lines
6.5 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"bufio"
"context"
"fmt"
"io"
"mime"
"net/http"
"path"
"strings"
"unicode"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Attachments -----------------------------------------------------------
//
// Files belong to a page: editors upload and delete them, anyone who can read
// the page can download them. Documents refer to a file by its URL,
// /api/v1/files/<id>; clients add a file token to load it in <img> tags.
type Attachment struct {
ID string `json:"id"`
Page string `json:"page"`
Name string `json:"name"`
Mime string `json:"mime"`
Size int64 `json:"size"`
URL string `json:"url"`
Created string `json:"created"`
}
type attachmentRecord struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Page string `json:"page"`
File string `json:"file"`
Name string `json:"name"`
Mime string `json:"mime"`
Size int64 `json:"size"`
Created string `json:"created"`
}
func (r attachmentRecord) view() Attachment {
return Attachment{ID: r.ID, Page: r.Page, Name: r.Name, Mime: r.Mime, Size: r.Size, URL: FileURL(r.ID), Created: r.Created}
}
// FileURL is the API path documents use for an attachment.
func FileURL(id string) string { return "/api/v1/files/" + id }
// SetMaxUpload caps one attachment, in bytes.
func (s *Service) SetMaxUpload(n int64) { s.maxUpload = n }
// cleanFilename keeps a display name safe for headers and file systems.
func cleanFilename(name string) string {
name = path.Base(strings.ReplaceAll(name, "\\", "/"))
name = strings.Map(func(r rune) rune {
if unicode.IsControl(r) || strings.ContainsRune(`"<>:|?*`, r) {
return -1
}
return r
}, name)
name = strings.TrimSpace(name)
if name == "" || name == "." || name == "/" {
name = "file"
}
if len(name) > 200 {
ext := path.Ext(name)
if len(ext) > 20 {
ext = ""
}
name = name[:200-len(ext)] + ext
}
return name
}
// sniffMime decides a file's type from its first bytes, falling back to its
// extension when the content says nothing more specific.
func sniffMime(head []byte, name string) string {
t := http.DetectContentType(head)
if t == "application/octet-stream" || strings.HasPrefix(t, "text/plain") {
if byExt := mime.TypeByExtension(strings.ToLower(path.Ext(name))); byExt != "" {
return byExt
}
}
return t
}
// UploadAttachment stores a file on a page (editor).
func (s *Service) UploadAttachment(ctx context.Context, c access.Caller, pageID, filename string, file io.Reader) (Attachment, error) {
p, err := s.editablePage(ctx, c, pageID)
if err != nil {
return Attachment{}, err
}
limit := s.maxUpload
if limit <= 0 {
limit = 50 << 20
}
name := cleanFilename(filename)
br := bufio.NewReaderSize(io.LimitReader(file, limit+1), 512)
head, _ := br.Peek(512)
mimeType := sniffMime(head, name)
counted := &countingReader{r: br}
rec, err := pocketbase.CreateWithFile[attachmentRecord](ctx, s.pb, "attachments", map[string]string{
"workspace": p.Workspace, "page": p.ID, "name": name, "mime": mimeType, "uploader": c.ID,
}, "file", name, &limitedReader{r: counted, limit: limit})
if counted.n > limit {
if rec.ID != "" {
_ = s.pb.Delete(ctx, "attachments", rec.ID)
}
return Attachment{}, apperr.InvalidFields(map[string]string{"file": fmt.Sprintf("The file is larger than %d MB.", limit>>20)})
}
if err != nil {
return Attachment{}, mapPB(err, "page not found")
}
rec, err = pocketbase.Update[attachmentRecord](ctx, s.pb, "attachments", rec.ID, map[string]any{"size": counted.n})
if err != nil {
return Attachment{}, mapPB(err, "attachment not found")
}
return rec.view(), nil
}
type countingReader struct {
r io.Reader
n int64
}
func (c *countingReader) Read(p []byte) (int, error) {
n, err := c.r.Read(p)
c.n += int64(n)
return n, err
}
// limitedReader fails once more than limit bytes were read, so an oversized
// upload aborts instead of being stored truncated.
type limitedReader struct {
r *countingReader
limit int64
}
func (l *limitedReader) Read(p []byte) (int, error) {
n, err := l.r.Read(p)
if l.r.n > l.limit {
return n, fmt.Errorf("file too large")
}
return n, err
}
// ListAttachments lists a page's files, oldest first (viewer).
func (s *Service) ListAttachments(ctx context.Context, c access.Caller, pageID string) ([]Attachment, error) {
p, _, err := s.pageFor(ctx, c, pageID)
if err != nil {
return nil, err
}
recs, err := listAll[attachmentRecord](ctx, s, "attachments", pocketbase.ListOptions{
Filter: fmt.Sprintf("page = '%s'", p.ID), Sort: "created",
})
if err != nil {
return nil, err
}
out := make([]Attachment, 0, len(recs))
for _, r := range recs {
out = append(out, r.view())
}
return out, nil
}
func (s *Service) getAttachment(ctx context.Context, id string) (attachmentRecord, error) {
if !validID(id) {
return attachmentRecord{}, apperr.NotFound("file not found")
}
rec, err := pocketbase.Get[attachmentRecord](ctx, s.pb, "attachments", id)
return rec, mapPB(err, "file not found")
}
// DeleteAttachment removes a file (editor of its page).
func (s *Service) DeleteAttachment(ctx context.Context, c access.Caller, id string) error {
rec, err := s.getAttachment(ctx, id)
if err != nil {
return err
}
if _, err := s.editablePage(ctx, c, rec.Page); err != nil {
if e, ok := apperr.As(err); ok && e.Kind == apperr.KindNotFound {
return apperr.NotFound("file not found")
}
return err
}
return mapPB(s.pb.Delete(ctx, "attachments", rec.ID), "file not found")
}
// FileDownload is an open attachment; the caller closes Body.
type FileDownload struct {
Attachment
*http.Response
}
// OpenAttachment opens a file for someone who can read its page.
func (s *Service) OpenAttachment(ctx context.Context, c access.Caller, id string, header http.Header) (FileDownload, error) {
rec, err := s.getAttachment(ctx, id)
if err != nil {
return FileDownload{}, err
}
if _, _, err := s.pageFor(ctx, c, rec.Page); err != nil {
return FileDownload{}, apperr.NotFound("file not found")
}
return s.openFile(ctx, rec, header)
}
func (s *Service) openFile(ctx context.Context, rec attachmentRecord, header http.Header) (FileDownload, error) {
resp, err := s.pb.OpenFile(ctx, "attachments", rec.ID, rec.File, header) //nolint:bodyclose // the caller closes FileDownload.Body
if err != nil {
return FileDownload{}, mapPB(err, "file not found")
}
return FileDownload{Attachment: rec.view(), Response: resp}, nil
}