Files
Docwell/Server/internal/search/files.go
T
tajniak81andClaude Opus 5.5 c98b127f1e
CI / go (Media) (push) Successful in 13m40s
CI / go (Server) (push) Failing after 23m20s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 10m35s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / desktop (ubuntu-latest) (push) Failing after 3h4m42s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / mobile (push) Failing after 9m19s
CI / docker (push) Successful in 2h2m57s
Add columns, suggesting mode, verified pages, scanned PDF search and server translations
- Columns: /columns puts 2 to 4 columns side by side, with widths dragged
  between them; they stack on phones. HTML export and import keep them
  (also Notion column lists and Confluence page layouts).
- Suggesting mode: edits become suggested insertions and deletions that
  editors accept or reject one by one or all at once. Text only.
- Verified pages: editors verify a page for a while or without end; the
  verifier is notified when it runs out (migration 1764700000).
- Scanned PDFs attached to pages are read by AI for search where a
  workspace turns it on.
- The server writes error messages, emails, digests and phone
  notifications in English, Polish, German, French and Spanish; the apps
  send their language with each request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:38:08 +01:00

228 lines
6.2 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package search
// Attachments: the text of files attached to pages (PDF text layers, Word,
// HTML and plain text) is searchable. Reading a file is slow, so it happens
// once: CatchUpFiles reads new attachments into the index's internal store
// ("filetext/<id>"), and each page then indexes, as its own documents, the
// files its content still links to (/api/v1/files/<id>). A file taken out of
// a page, or its page trashed, drops out with the page's next indexing, the
// same way as database records.
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"docwell/server/internal/store/pocketbase"
"docwell/server/internal/textract"
)
const fileKind = "file"
// Limits of what is read from one attachment.
const (
maxFileBytes = 25 << 20
maxFileText = 300_000 // runes kept
)
// FileHit names the attached file a hit found, inside the hit's page.
type FileHit struct {
ID string `json:"id"`
Name string `json:"name"`
}
// fileText is what the index keeps of one attachment.
type fileText struct {
Name string `json:"name"`
Text string `json:"text"`
}
func fileTextKey(id string) []byte { return []byte("filetext/" + id) }
var fileRef = regexp.MustCompile(`/api/v1/files/([a-z0-9]{15})`)
// linkedFiles are the attachment ids a page's content links to, in order.
func linkedFiles(content []byte) []string {
seen := map[string]bool{}
var out []string
for _, m := range fileRef.FindAllSubmatch(content, -1) {
if id := string(m[1]); !seen[id] {
seen[id] = true
out = append(out, id)
}
}
return out
}
// fileDocs are the documents of the files a page links to whose text has
// been read, by document id.
func (x *Index) fileDocs(p pageRow) (map[string]doc, error) {
out := map[string]doc{}
for _, id := range linkedFiles(p.ContentJSON) {
raw, err := x.idx.GetInternal(fileTextKey(id))
if err != nil {
return nil, err
}
var ft fileText
if len(raw) == 0 || json.Unmarshal(raw, &ft) != nil || strings.TrimSpace(ft.Text) == "" {
continue
}
d := newDoc(p)
d.Kind, d.Page, d.PageTitle, d.File = fileKind, p.ID, p.Title, id
d.Title, d.Text = ft.Name, ft.Text
out[p.ID+":file:"+id] = d
}
return out, nil
}
type attachmentRow struct {
ID string `json:"id"`
Page string `json:"page"`
File string `json:"file"`
Name string `json:"name"`
Size int64 `json:"size"`
Updated string `json:"updated"`
}
const fileCheckpointKey = "filecheckpoint"
// CatchUpFiles reads the text of attachments added since the last pass and
// re-indexes their pages. Files Text cannot read are remembered as empty,
// so they are not downloaded again.
func (x *Index) CatchUpFiles(ctx context.Context) error {
x.mu.Lock()
defer x.mu.Unlock()
raw, err := x.idx.GetInternal([]byte(fileCheckpointKey))
if err != nil {
return err
}
checkpoint := string(raw)
for {
filter := ""
if checkpoint != "" {
filter = fmt.Sprintf("updated >= '%s'", checkpoint)
}
res, err := pocketbase.List[attachmentRow](ctx, x.pb, "attachments", pocketbase.ListOptions{
PerPage: 100, Filter: filter, Sort: "updated,id", Fields: "id,page,file,name,size,updated",
})
if err != nil {
return err
}
pages := map[string]bool{}
var scanned []attachmentRow
batch := x.idx.NewBatch()
for _, a := range res.Items {
if !textract.Supported(a.Name) {
continue
}
// Already read: an attachment's file never changes.
if old, err := x.idx.GetInternal(fileTextKey(a.ID)); err != nil {
return err
} else if old != nil {
continue
}
text, ok, scan := x.readFile(ctx, a)
if ctx.Err() != nil {
return ctx.Err()
}
if !ok {
continue // a download that failed is tried again by a rebuild
}
if scan {
scanned = append(scanned, a) // remembered empty until AI reads it (scans.go)
}
ft := fileText{Name: a.Name, Text: text}
data, _ := json.Marshal(ft)
batch.SetInternal(fileTextKey(a.ID), data)
if ft.Text != "" && a.Page != "" {
pages[a.Page] = true
}
}
next := checkpoint
if n := len(res.Items); n > 0 {
next = res.Items[n-1].Updated
}
batch.SetInternal([]byte(fileCheckpointKey), []byte(next))
if err := x.idx.Batch(batch); err != nil {
return err
}
if err := x.queueScans(ctx, scanned); err != nil {
return err
}
if err := x.reindexPages(ctx, pages); err != nil {
return err
}
if len(res.Items) < 100 || next == checkpoint {
return nil
}
checkpoint = next
}
}
// readFile downloads an attachment and reads its text: "" when it has none
// or cannot be read, and ok false when the download failed (not remembered,
// so a rebuild tries it again). scan is true for a PDF without a text layer,
// which AI may read later (scans.go).
func (x *Index) readFile(ctx context.Context, a attachmentRow) (text string, ok, scan bool) {
data, ok := x.download(ctx, a, maxFileBytes)
if !ok || data == nil {
return "", ok, false
}
text, err := textract.Text(a.Name, data)
if errors.Is(err, textract.ErrNoText) {
return "", true, true
}
if err != nil {
return "", true, false
}
return cleanText(text), true, false
}
// download fetches an attachment's file: nil when it is larger than limit
// (or has no file), ok false when the download failed.
func (x *Index) download(ctx context.Context, a attachmentRow, limit int64) (data []byte, ok bool) {
if a.File == "" || a.Size > limit {
return nil, true
}
res, err := x.pb.OpenFile(ctx, "attachments", a.ID, a.File, http.Header{})
if err != nil {
x.log.Warn("search: attachment download", "id", a.ID, "err", err)
return nil, false
}
defer func() { _ = res.Body.Close() }()
data, err = io.ReadAll(io.LimitReader(res.Body, limit+1))
if err != nil {
return nil, false
}
if int64(len(data)) > limit {
return nil, true
}
return data, true
}
// reindexPages indexes these pages again, now that more of their files
// have text.
func (x *Index) reindexPages(ctx context.Context, ids map[string]bool) error {
if len(ids) == 0 {
return nil
}
batch := x.idx.NewBatch()
for id := range ids {
p, err := pocketbase.Get[pageRow](ctx, x.pb, "pages", id)
if err != nil {
continue // purged since: the sweep removes what is left
}
if err := x.indexPage(batch, p); err != nil {
return err
}
}
return x.idx.Batch(batch)
}