Search the text of files attached to pages
CI / go (Server) (push) Failing after 22m44s
CI / go (Media) (push) Canceled after 0s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 10m17s
CI / desktop (ubuntu-latest) (push) Failing after 1h44m2s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / mobile (push) Failing after 5m11s
CI / docker (push) Successful in 1h29m50s
Docs / build (push) Successful in 14m34s
Docs / deploy (push) Skipped
CI / go (Server) (push) Failing after 22m44s
CI / go (Media) (push) Canceled after 0s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 10m17s
CI / desktop (ubuntu-latest) (push) Failing after 1h44m2s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / mobile (push) Failing after 5m11s
CI / docker (push) Successful in 1h29m50s
Docs / build (push) Successful in 14m34s
Docs / deploy (push) Skipped
The search index now reads the files pages link to: PDF text layers, Word (.docx), HTML and text files such as Markdown or CSV, up to 25 MB, and their names. Each file is read once, a few seconds after upload, and its text is kept in the index; each linked file is indexed as its own document under its page, like database records, so a file taken off its page, or a trashed page, drops out. Scanned PDFs are not read. Hits carry a new file field (id and name). The web search palette and the phone's search show the file with an attachment icon and the page it is on; /docwell in Slack names the file too. PDF, Word and HTML reading moved from the AI package into internal/textract, which AI's extra files now use as well. The index mapping version is bumped, so existing indexes rebuild on start. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f1963f1391
commit
1696f2e77e
13 files changed
+675
-82
No files matched your search
@@ -136,6 +136,12 @@ Press **Ctrl+K** (⌘K on a Mac) or click **Search** in the sidebar. With nothin
|
||||
visited last; type to search titles and text in every space you can open. The filters narrow results by space,
|
||||
tag, author or date. Star a page (☆ in the header) to keep it under **Favorites** in the sidebar.
|
||||
|
||||
Search also reads the files attached to pages: the text of PDFs (not scanned ones, which have no text), Word
|
||||
(`.docx`), HTML and text files such as Markdown or CSV, up to 25 MB each, and their names. A match shows the file
|
||||
with 📎 and the page it is on; it opens that page. Only files the page still links to are found, so a file removed
|
||||
from its page drops out of search. Files are read once, a few seconds after they are uploaded; after an upgrade, the
|
||||
files already on the server are read in the background.
|
||||
|
||||
## AI
|
||||
|
||||
When AI is set up in a workspace (see *Administration → AI*), the ✦ button in the header (**Ctrl+J**) opens the
|
||||
|
||||
Vendored
+6
@@ -4278,6 +4278,12 @@ export interface components {
|
||||
row: string;
|
||||
title: string;
|
||||
};
|
||||
/** @description Set when the match is in a file attached to the page (the text of PDFs, Word, HTML and text files is searchable); snippet is from the file */
|
||||
file?: {
|
||||
/** @description The attachment (its address is /api/v1/files/<id>) */
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
icon: string;
|
||||
space: string;
|
||||
spaceName: string;
|
||||
|
||||
@@ -3487,11 +3487,27 @@ class SearchHitRecord {
|
||||
};
|
||||
}
|
||||
|
||||
/// Set when the match is in a file attached to the page (the text of PDFs, Word, HTML and text files is searchable); snippet is from the file
|
||||
class SearchHitFile {
|
||||
const SearchHitFile({required this.id, required this.name});
|
||||
|
||||
factory SearchHitFile.fromJson(Map<String, dynamic> json) =>
|
||||
SearchHitFile(id: json['id'] as String, name: json['name'] as String);
|
||||
|
||||
/// The attachment (its address is /api/v1/files/`<id>`)
|
||||
final String id;
|
||||
|
||||
final String name;
|
||||
|
||||
Map<String, dynamic> toJson() => {'id': id, 'name': name};
|
||||
}
|
||||
|
||||
class SearchHit {
|
||||
const SearchHit({
|
||||
required this.id,
|
||||
required this.title,
|
||||
this.record,
|
||||
this.file,
|
||||
required this.icon,
|
||||
required this.space,
|
||||
required this.spaceName,
|
||||
@@ -3506,6 +3522,9 @@ class SearchHit {
|
||||
record: json['record'] == null
|
||||
? null
|
||||
: SearchHitRecord.fromJson(json['record'] as Map<String, dynamic>),
|
||||
file: json['file'] == null
|
||||
? null
|
||||
: SearchHitFile.fromJson(json['file'] as Map<String, dynamic>),
|
||||
icon: json['icon'] as String,
|
||||
space: json['space'] as String,
|
||||
spaceName: json['spaceName'] as String,
|
||||
@@ -3525,6 +3544,9 @@ class SearchHit {
|
||||
/// Set when the hit is a database record; open it with the page link plus "#r-`<database>`-`<row>`"
|
||||
final SearchHitRecord? record;
|
||||
|
||||
/// Set when the match is in a file attached to the page (the text of PDFs, Word, HTML and text files is searchable); snippet is from the file
|
||||
final SearchHitFile? file;
|
||||
|
||||
final String icon;
|
||||
|
||||
final String space;
|
||||
@@ -3543,6 +3565,7 @@ class SearchHit {
|
||||
'id': id,
|
||||
'title': title,
|
||||
'record': ?record?.toJson(),
|
||||
'file': ?file?.toJson(),
|
||||
'icon': icon,
|
||||
'space': space,
|
||||
'spaceName': spaceName,
|
||||
|
||||
@@ -105,14 +105,18 @@ class _SearchScreenState extends State<SearchScreen> {
|
||||
ListTile(
|
||||
leading: h.record != null
|
||||
? const Icon(Icons.table_chart_outlined)
|
||||
: h.file != null
|
||||
? const Icon(Icons.attach_file)
|
||||
: PageIcon(h.icon),
|
||||
title: Text(switch (h.record?.title ?? h.title) {
|
||||
title: Text(switch (h.record?.title ??
|
||||
h.file?.name ??
|
||||
h.title) {
|
||||
'' => tr('untitled'),
|
||||
final t => t,
|
||||
}),
|
||||
subtitle: Text(
|
||||
[
|
||||
if (h.record != null)
|
||||
if (h.record != null || h.file != null)
|
||||
tr('inPage', {
|
||||
'title': h.title.isEmpty ? tr('untitled') : h.title,
|
||||
}),
|
||||
|
||||
+20
-60
@@ -3,7 +3,6 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -13,10 +12,8 @@ import (
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/convert"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
|
||||
"github.com/ledongthuc/pdf"
|
||||
"docwell/server/internal/textract"
|
||||
)
|
||||
|
||||
// ---- Extra files for retrieval ----------------------------------------------------
|
||||
@@ -49,30 +46,27 @@ type File struct {
|
||||
Created string `json:"created"`
|
||||
}
|
||||
|
||||
// extractText reads the text of a supported file.
|
||||
// extractText reads the text of a supported file (textract), with the
|
||||
// messages admins see.
|
||||
func extractText(name string, data []byte) (string, error) {
|
||||
switch strings.ToLower(filepath.Ext(name)) {
|
||||
case ".txt", ".md", ".markdown", ".csv", ".json", ".yaml", ".yml", ".xml", ".rst", ".org":
|
||||
if !utf8.Valid(data) {
|
||||
return "", apperr.Invalid("The file is not UTF-8 text.")
|
||||
}
|
||||
return string(data), nil
|
||||
case ".html", ".htm":
|
||||
doc, err := convert.FromHTML(string(data))
|
||||
if err != nil {
|
||||
return "", apperr.Invalid("The HTML file could not be read.")
|
||||
}
|
||||
return convert.Markdown(doc, convert.Options{}), nil
|
||||
case ".pdf":
|
||||
return pdfText(data)
|
||||
case ".docx":
|
||||
doc, _, err := convert.FromDOCX(data)
|
||||
if err != nil {
|
||||
return "", apperr.Invalid("The Word document could not be read.")
|
||||
}
|
||||
return convert.Markdown(doc, convert.Options{}), nil
|
||||
text, err := textract.Text(name, data)
|
||||
switch {
|
||||
case err == nil:
|
||||
return text, nil
|
||||
case errors.Is(err, textract.ErrNoText):
|
||||
return "", errNoPDFText
|
||||
case errors.Is(err, textract.ErrNotUTF8):
|
||||
return "", apperr.Invalid("The file is not UTF-8 text.")
|
||||
case errors.Is(err, textract.ErrUnsupported):
|
||||
return "", apperr.Invalid("Add text, Markdown, HTML, Word (.docx) or PDF files.")
|
||||
}
|
||||
return "", apperr.Invalid("Add text, Markdown, HTML, Word (.docx) or PDF files.")
|
||||
switch strings.ToLower(filepath.Ext(name)) {
|
||||
case ".pdf":
|
||||
return "", apperr.Invalid("The PDF could not be read.")
|
||||
case ".docx":
|
||||
return "", apperr.Invalid("The Word document could not be read.")
|
||||
}
|
||||
return "", apperr.Invalid("The HTML file could not be read.")
|
||||
}
|
||||
|
||||
// errNoPDFText is a PDF without a text layer (scanned pages).
|
||||
@@ -101,40 +95,6 @@ func (s *Service) readScannedPDF(ctx context.Context, c access.Caller, wsID stri
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
// pdfText reads a PDF's text page by page. Scanned PDFs have none (no OCR).
|
||||
// The reader panics on some malformed files, so that becomes an error.
|
||||
func pdfText(data []byte) (text string, err error) {
|
||||
bad := apperr.Invalid("The PDF could not be read.")
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
text, err = "", bad
|
||||
}
|
||||
}()
|
||||
r, err := pdf.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return "", bad
|
||||
}
|
||||
var b strings.Builder
|
||||
for i := 1; i <= r.NumPage(); i++ {
|
||||
p := r.Page(i)
|
||||
if p.V.IsNull() {
|
||||
continue
|
||||
}
|
||||
t, err := p.GetPlainText(nil)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if t = strings.TrimSpace(t); t != "" {
|
||||
b.WriteString(t)
|
||||
b.WriteString("\n\n")
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(b.String()) == "" {
|
||||
return "", errNoPDFText
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func (s *Service) fileView(ws string, r fileRecord) File {
|
||||
h, _ := s.store.Hash(ws, "file/"+r.ID)
|
||||
return File{ID: r.ID, Name: r.Name, Size: int(r.Size), Chars: utf8.RuneCountInString(r.ContentText), Indexed: h != "", Created: r.Created}
|
||||
|
||||
@@ -2480,6 +2480,13 @@ type Role string
|
||||
|
||||
// SearchHit defines model for SearchHit.
|
||||
type SearchHit struct {
|
||||
// File Set when the match is in a file attached to the page (the text of PDFs, Word, HTML and text files is searchable); snippet is from the file
|
||||
File *struct {
|
||||
// Id The attachment (its address is /api/v1/files/<id>)
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"file,omitempty"`
|
||||
|
||||
// Highlights [start, end) character offsets of matches in snippet
|
||||
Highlights [][]int `json:"highlights"`
|
||||
Icon string `json:"icon"`
|
||||
|
||||
@@ -661,6 +661,9 @@ func (s *Service) Commands(w http.ResponseWriter, r *http.Request, wsID string)
|
||||
title = "Untitled"
|
||||
}
|
||||
fmt.Fprintf(&b, "\n• <%s/p/%s|%s>", s.webURL, h.ID, escape(title))
|
||||
if h.File != nil {
|
||||
b.WriteString(" · 📎 " + escape(h.File.Name))
|
||||
}
|
||||
if h.SpaceName != "" {
|
||||
b.WriteString(" — _" + escape(h.SpaceName) + "_")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
// 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"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"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{}
|
||||
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 := x.readFile(ctx, a)
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if !ok {
|
||||
continue // a download that failed is tried again by a rebuild
|
||||
}
|
||||
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.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).
|
||||
func (x *Index) readFile(ctx context.Context, a attachmentRow) (text string, ok bool) {
|
||||
if a.File == "" || a.Size > maxFileBytes {
|
||||
return "", 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 "", false
|
||||
}
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
data, err := io.ReadAll(io.LimitReader(res.Body, maxFileBytes+1))
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
if len(data) > maxFileBytes {
|
||||
return "", true
|
||||
}
|
||||
text, err = textract.Text(a.Name, data)
|
||||
if err != nil {
|
||||
return "", true
|
||||
}
|
||||
text = strings.Join(strings.Fields(text), " ")
|
||||
if utf8.RuneCountInString(text) > maxFileText {
|
||||
text = string([]rune(text)[:maxFileText])
|
||||
}
|
||||
return text, 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)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package search
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/go-pdf/fpdf"
|
||||
|
||||
"docwell/server/internal/convert"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// fakeFiles is a PocketBase with pages, attachments and their files.
|
||||
type fakeFiles struct {
|
||||
mu sync.Mutex
|
||||
pages map[string]pageRow
|
||||
atts []attachmentRow
|
||||
files map[string][]byte // attachment id -> bytes
|
||||
downloads int
|
||||
}
|
||||
|
||||
func (f *fakeFiles) server(t *testing.T) *pocketbase.Client {
|
||||
t.Helper()
|
||||
reply := func(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) {
|
||||
reply(w, map[string]string{"token": "su"})
|
||||
})
|
||||
mux.HandleFunc("GET /api/collections/pages/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
items := []pageRow{}
|
||||
for _, p := range f.pages {
|
||||
items = append(items, p)
|
||||
}
|
||||
reply(w, map[string]any{"items": items, "totalItems": len(items), "totalPages": 1})
|
||||
})
|
||||
mux.HandleFunc("GET /api/collections/pages/records/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
p, ok := f.pages[r.PathValue("id")]
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
reply(w, map[string]any{"message": "not found"})
|
||||
return
|
||||
}
|
||||
reply(w, p)
|
||||
})
|
||||
mux.HandleFunc("GET /api/collections/attachments/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
reply(w, map[string]any{"items": f.atts, "totalItems": len(f.atts), "totalPages": 1})
|
||||
})
|
||||
mux.HandleFunc("POST /api/files/token", func(w http.ResponseWriter, r *http.Request) {
|
||||
reply(w, map[string]string{"token": "ft"})
|
||||
})
|
||||
mux.HandleFunc("GET /api/files/attachments/{id}/{file}", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.downloads++
|
||||
_, _ = w.Write(f.files[r.PathValue("id")])
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
return pocketbase.New(srv.URL, "su@x.test", "pw")
|
||||
}
|
||||
|
||||
func pdfWith(t *testing.T, text string) []byte {
|
||||
t.Helper()
|
||||
doc := fpdf.New("P", "mm", "A4", "")
|
||||
doc.AddPage()
|
||||
doc.SetFont("Helvetica", "", 12)
|
||||
doc.Cell(40, 10, text)
|
||||
var buf bytes.Buffer
|
||||
if err := doc.Output(&buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// pageLinking is a page whose content links to the attachments ids.
|
||||
func pageLinking(id, title string, ids ...string) pageRow {
|
||||
var nodes []string
|
||||
for _, a := range ids {
|
||||
nodes = append(nodes, `{"type":"fileAttachment","attrs":{"src":"/api/v1/files/`+a+`","name":"f"}}`)
|
||||
}
|
||||
return pageRow{
|
||||
ID: id, Workspace: "w1", Space: "s1", Title: title, ContentText: "Some notes", Updated: "2026-11-01 10:00:00.000Z",
|
||||
ContentJSON: json.RawMessage(`{"type":"doc","content":[` + strings.Join(nodes, ",") + `]}`),
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentText(t *testing.T) {
|
||||
word, err := convert.DOCX("Plan", convert.Node{Type: "doc", Content: []convert.Node{
|
||||
{Type: "paragraph", Content: []convert.Node{{Type: "text", Text: "Quarterly budget forecast for marketing"}}},
|
||||
}}, convert.DOCXOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := &fakeFiles{
|
||||
pages: map[string]pageRow{
|
||||
"page00000000001": pageLinking("page00000000001", "Finance", "pdf000000000001", "doc000000000001", "img000000000001"),
|
||||
// Links to nothing: its attachment is uploaded but not on the page.
|
||||
"page00000000002": pageLinking("page00000000002", "Drafts"),
|
||||
},
|
||||
atts: []attachmentRow{
|
||||
{ID: "pdf000000000001", Page: "page00000000001", File: "policy_abc.pdf", Name: "Expense policy.pdf", Size: 2000, Updated: "2026-11-01 10:00:00.000Z"},
|
||||
{ID: "doc000000000001", Page: "page00000000001", File: "plan_abc.docx", Name: "Plan.docx", Size: 2000, Updated: "2026-11-01 10:00:01.000Z"},
|
||||
{ID: "img000000000001", Page: "page00000000001", File: "pic_abc.png", Name: "pic.png", Size: 10, Updated: "2026-11-01 10:00:02.000Z"},
|
||||
{ID: "orphan000000001", Page: "page00000000002", File: "orphan_abc.txt", Name: "orphan.txt", Size: 10, Updated: "2026-11-01 10:00:03.000Z"},
|
||||
},
|
||||
files: map[string][]byte{
|
||||
"pdf000000000001": pdfWith(t, "Receipts are reimbursed within thirty days"),
|
||||
"doc000000000001": word,
|
||||
"img000000000001": []byte("PNG"),
|
||||
"orphan000000001": []byte("Zanzibar travel notes"),
|
||||
},
|
||||
}
|
||||
x, err := OpenMemory(f.server(t), slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = x.Close() })
|
||||
ctx := context.Background()
|
||||
if err := x.CatchUp(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := x.CatchUpFiles(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
query := func(text string) []Hit {
|
||||
t.Helper()
|
||||
hits, _, err := x.Query(ctx, "w1", []string{"s1"}, text, Filter{}, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
hits := query("reimbursed")
|
||||
if len(hits) != 1 || hits[0].ID != "page00000000001" || hits[0].Title != "Finance" ||
|
||||
hits[0].File == nil || hits[0].File.ID != "pdf000000000001" || hits[0].File.Name != "Expense policy.pdf" {
|
||||
t.Fatalf("pdf hit %+v", hits)
|
||||
}
|
||||
if !strings.Contains(hits[0].Snippet, "reimbursed") || len(hits[0].Highlights) == 0 {
|
||||
t.Errorf("snippet %q %v", hits[0].Snippet, hits[0].Highlights)
|
||||
}
|
||||
if hits := query("forecast"); len(hits) != 1 || hits[0].File == nil || hits[0].File.Name != "Plan.docx" {
|
||||
t.Errorf("word hit %+v", hits)
|
||||
}
|
||||
// A file name is searchable too.
|
||||
if hits := query("expense"); len(hits) != 1 || hits[0].File == nil {
|
||||
t.Errorf("name hit %+v", hits)
|
||||
}
|
||||
// Uploaded but not linked from its page: not found.
|
||||
if hits := query("zanzibar"); len(hits) != 0 {
|
||||
t.Errorf("unlinked file found: %+v", hits)
|
||||
}
|
||||
// Pages are counted without their files.
|
||||
if n, _ := x.Count(); n != 2 {
|
||||
t.Errorf("count %d", n)
|
||||
}
|
||||
|
||||
// Files are read once: another pass downloads nothing.
|
||||
before := f.downloads
|
||||
if err := x.CatchUpFiles(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.downloads != before {
|
||||
t.Errorf("read again: %d downloads", f.downloads-before)
|
||||
}
|
||||
if before != 3 {
|
||||
t.Errorf("downloads %d, want 3 (the picture is not read)", before)
|
||||
}
|
||||
|
||||
// Taking the PDF out of the page drops it at the page's next indexing.
|
||||
f.mu.Lock()
|
||||
f.pages["page00000000001"] = pageLinking("page00000000001", "Finance", "doc000000000001")
|
||||
p := f.pages["page00000000001"]
|
||||
f.mu.Unlock()
|
||||
batch := x.idx.NewBatch()
|
||||
if err := x.indexPage(batch, p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := x.idx.Batch(batch); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hits := query("reimbursed"); len(hits) != 0 {
|
||||
t.Errorf("unlinked pdf still found: %+v", hits)
|
||||
}
|
||||
if hits := query("forecast"); len(hits) != 1 {
|
||||
t.Errorf("word file lost: %+v", hits)
|
||||
}
|
||||
|
||||
// A trashed page takes its files with it.
|
||||
p.DeletedAt = "2026-11-02 00:00:00.000Z"
|
||||
batch = x.idx.NewBatch()
|
||||
if err := x.indexPage(batch, p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := x.idx.Batch(batch); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if hits := query("forecast"); len(hits) != 0 {
|
||||
t.Errorf("trashed page's file found: %+v", hits)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Package search keeps a Bleve full-text index of page titles and text, and
|
||||
// of the records of the databases in them (ADR-13): a record is its own
|
||||
// document, so a search can open it rather than only its page.
|
||||
// Package search keeps a Bleve full-text index of page titles and text, of
|
||||
// the records of the databases in them (ADR-13), and of the text of the
|
||||
// files attached to them (files.go): a record or a file is its own document,
|
||||
// so a search can say what it found rather than only its page.
|
||||
//
|
||||
// The index follows PocketBase instead of being told about every change: an
|
||||
// indexer polls for pages whose "updated" moved since its checkpoint (titles,
|
||||
@@ -44,6 +45,7 @@ type doc struct {
|
||||
PageTitle string `json:"pageTitle,omitempty"`
|
||||
Database string `json:"database,omitempty"`
|
||||
Row string `json:"row,omitempty"`
|
||||
File string `json:"file,omitempty"`
|
||||
Workspace string `json:"workspace"`
|
||||
Space string `json:"space"`
|
||||
Title string `json:"title"`
|
||||
@@ -105,6 +107,7 @@ type RecordHit struct {
|
||||
type Hit struct {
|
||||
ID string `json:"id"`
|
||||
Record *RecordHit `json:"record,omitempty"`
|
||||
File *FileHit `json:"file,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Icon string `json:"icon"`
|
||||
Space string `json:"space"`
|
||||
@@ -137,7 +140,7 @@ const (
|
||||
// mappingKey holds mappingVersion; an index built with another mapping is
|
||||
// rebuilt on open. Bump the version whenever newMapping changes.
|
||||
mappingKey = "mapping"
|
||||
mappingVersion = "3"
|
||||
mappingVersion = "4"
|
||||
)
|
||||
|
||||
func newMapping() mapping.IndexMapping {
|
||||
@@ -164,6 +167,7 @@ func newMapping() mapping.IndexMapping {
|
||||
page.AddFieldMappingsAt("pageTitle", stored)
|
||||
page.AddFieldMappingsAt("database", stored)
|
||||
page.AddFieldMappingsAt("row", stored)
|
||||
page.AddFieldMappingsAt("file", stored)
|
||||
|
||||
m := bleve.NewIndexMapping()
|
||||
m.DefaultMapping = page
|
||||
@@ -224,11 +228,11 @@ func OpenMemory(pb *pocketbase.Client, log *slog.Logger) (*Index, error) {
|
||||
|
||||
func (x *Index) Close() error { return x.idx.Close() }
|
||||
|
||||
// Count is the number of indexed pages (records not counted).
|
||||
// Count is the number of indexed pages (records and files not counted).
|
||||
func (x *Index) Count() (uint64, error) {
|
||||
q := bleve.NewBooleanQuery()
|
||||
q.AddMust(bleve.NewMatchAllQuery())
|
||||
q.AddMustNot(isRecord())
|
||||
q.AddMustNot(isChild())
|
||||
res, err := x.idx.Search(bleve.NewSearchRequestOptions(q, 0, 0, false))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -236,18 +240,23 @@ func (x *Index) Count() (uint64, error) {
|
||||
return res.Total, nil
|
||||
}
|
||||
|
||||
func isRecord() query.Query {
|
||||
q := bleve.NewTermQuery(recordKind)
|
||||
q.SetField("kind")
|
||||
return q
|
||||
// isChild matches the documents inside a page: records and files.
|
||||
func isChild() query.Query {
|
||||
var kinds []query.Query
|
||||
for _, k := range []string{recordKind, fileKind} {
|
||||
q := bleve.NewTermQuery(k)
|
||||
q.SetField("kind")
|
||||
kinds = append(kinds, q)
|
||||
}
|
||||
return bleve.NewDisjunctionQuery(kinds...)
|
||||
}
|
||||
|
||||
// recordsKey is where the index keeps the ids of a page's record documents,
|
||||
// to drop the ones whose records were deleted.
|
||||
func recordsKey(page string) []byte { return []byte("records/" + page) }
|
||||
|
||||
// indexPage adds a page and its records to batch, dropping records it no
|
||||
// longer has; a trashed page goes with all its records.
|
||||
// indexPage adds a page with its records and files to batch, dropping the
|
||||
// ones it no longer has; a trashed page goes with all of them.
|
||||
func (x *Index) indexPage(batch *bleve.Batch, p pageRow) error {
|
||||
var old []string
|
||||
raw, err := x.idx.GetInternal(recordsKey(p.ID))
|
||||
@@ -266,6 +275,16 @@ func (x *Index) indexPage(batch *bleve.Batch, p pageRow) error {
|
||||
return err
|
||||
}
|
||||
recs = recordDocs(p)
|
||||
files, err := x.fileDocs(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if recs == nil && len(files) > 0 {
|
||||
recs = map[string]doc{}
|
||||
}
|
||||
for id, d := range files {
|
||||
recs[id] = d
|
||||
}
|
||||
}
|
||||
for _, id := range old {
|
||||
if _, ok := recs[id]; !ok {
|
||||
@@ -303,6 +322,9 @@ func (x *Index) Run(ctx context.Context, interval, sweepEvery time.Duration) {
|
||||
if err := x.tracked("search.index", func() error { return x.CatchUp(ctx) }); err != nil && ctx.Err() == nil {
|
||||
x.log.Warn("search: indexing failed", "err", err)
|
||||
}
|
||||
if err := x.tracked("search.files", func() error { return x.CatchUpFiles(ctx) }); err != nil && ctx.Err() == nil {
|
||||
x.log.Warn("search: reading attachments failed", "err", err)
|
||||
}
|
||||
if time.Since(lastSweep) >= sweepEvery {
|
||||
if err := x.tracked("search.sweep", func() error { return x.Sweep(ctx) }); err != nil && ctx.Err() == nil {
|
||||
x.log.Warn("search: sweep failed", "err", err)
|
||||
@@ -429,10 +451,17 @@ func (x *Index) Sweep(ctx context.Context) error {
|
||||
func (x *Index) Rebuild(ctx context.Context) error {
|
||||
x.mu.Lock()
|
||||
err := x.idx.SetInternal([]byte(checkpointKey), nil)
|
||||
if err == nil {
|
||||
// Files already read keep their text; the others are tried again.
|
||||
err = x.idx.SetInternal([]byte(fileCheckpointKey), nil)
|
||||
}
|
||||
x.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := x.CatchUpFiles(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := x.CatchUp(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -480,11 +509,11 @@ func (x *Index) Query(ctx context.Context, workspace string, spaces []string, te
|
||||
must = append(must, textQuery(text))
|
||||
} else {
|
||||
// Listing by filter alone lists pages, not every record in them.
|
||||
q.AddMustNot(isRecord())
|
||||
q.AddMustNot(isChild())
|
||||
}
|
||||
q.AddMust(must...)
|
||||
req := bleve.NewSearchRequestOptions(q, max(1, min(limit, 50)), 0, false)
|
||||
req.Fields = []string{"title", "icon", "space", "text", "updated", "kind", "page", "pageTitle", "database", "row"}
|
||||
req.Fields = []string{"title", "icon", "space", "text", "updated", "kind", "page", "pageTitle", "database", "row", "file"}
|
||||
req.IncludeLocations = true
|
||||
if text == "" {
|
||||
req.SortBy([]string{"-modified", "_id"})
|
||||
@@ -507,9 +536,13 @@ func (x *Index) Query(ctx context.Context, workspace string, spaces []string, te
|
||||
ID: h.ID, Title: str("title"), Icon: str("icon"), Space: str("space"),
|
||||
Snippet: snippet, Highlights: marks, Updated: str("updated"),
|
||||
}
|
||||
if str("kind") == recordKind {
|
||||
switch str("kind") {
|
||||
case recordKind:
|
||||
hit.ID, hit.Title = str("page"), str("pageTitle")
|
||||
hit.Record = &RecordHit{Database: str("database"), Row: str("row"), Title: str("title")}
|
||||
case fileKind:
|
||||
hit.ID, hit.Title = str("page"), str("pageTitle")
|
||||
hit.File = &FileHit{ID: str("file"), Name: str("title")}
|
||||
}
|
||||
hits = append(hits, hit)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Package textract reads the text of documents people upload: PDFs (their
|
||||
// text layer), Word files, HTML and plain text formats. Search indexes
|
||||
// attachments with it, and AI reads its extra files with it.
|
||||
package textract
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/ledongthuc/pdf"
|
||||
|
||||
"docwell/server/internal/convert"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnsupported is a file type Text does not read.
|
||||
ErrUnsupported = errors.New("unsupported file type")
|
||||
// ErrUnreadable is a file of a supported type that could not be read.
|
||||
ErrUnreadable = errors.New("the file could not be read")
|
||||
// ErrNoText is a PDF without a text layer (scanned pages; no OCR here).
|
||||
ErrNoText = errors.New("the PDF has no text layer")
|
||||
// ErrNotUTF8 is a plain text file in another encoding.
|
||||
ErrNotUTF8 = errors.New("the file is not UTF-8 text")
|
||||
)
|
||||
|
||||
var plainTypes = map[string]bool{
|
||||
".txt": true, ".md": true, ".markdown": true, ".csv": true, ".tsv": true, ".json": true, ".yaml": true,
|
||||
".yml": true, ".xml": true, ".rst": true, ".org": true, ".log": true,
|
||||
}
|
||||
|
||||
// Supported reports whether Text reads files named like name.
|
||||
func Supported(name string) bool {
|
||||
switch ext := strings.ToLower(filepath.Ext(name)); ext {
|
||||
case ".html", ".htm", ".pdf", ".docx":
|
||||
return true
|
||||
default:
|
||||
return plainTypes[ext]
|
||||
}
|
||||
}
|
||||
|
||||
// Text reads the text of a file, by its name's extension. HTML and Word
|
||||
// come out as Markdown.
|
||||
func Text(name string, data []byte) (string, error) {
|
||||
ext := strings.ToLower(filepath.Ext(name))
|
||||
switch {
|
||||
case plainTypes[ext]:
|
||||
data = bytes.TrimPrefix(data, []byte{0xEF, 0xBB, 0xBF})
|
||||
if !utf8.Valid(data) {
|
||||
return "", ErrNotUTF8
|
||||
}
|
||||
return string(data), nil
|
||||
case ext == ".html" || ext == ".htm":
|
||||
doc, err := convert.FromHTML(string(data))
|
||||
if err != nil {
|
||||
return "", ErrUnreadable
|
||||
}
|
||||
return convert.Markdown(doc, convert.Options{}), nil
|
||||
case ext == ".pdf":
|
||||
return PDF(data)
|
||||
case ext == ".docx":
|
||||
doc, _, err := convert.FromDOCX(data)
|
||||
if err != nil {
|
||||
return "", ErrUnreadable
|
||||
}
|
||||
return convert.Markdown(doc, convert.Options{}), nil
|
||||
}
|
||||
return "", ErrUnsupported
|
||||
}
|
||||
|
||||
// PDF reads a PDF's text page by page. The reader panics on some malformed
|
||||
// files, so that becomes ErrUnreadable.
|
||||
func PDF(data []byte) (text string, err error) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
text, err = "", ErrUnreadable
|
||||
}
|
||||
}()
|
||||
r, err := pdf.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return "", ErrUnreadable
|
||||
}
|
||||
var b strings.Builder
|
||||
for i := 1; i <= r.NumPage(); i++ {
|
||||
p := r.Page(i)
|
||||
if p.V.IsNull() {
|
||||
continue
|
||||
}
|
||||
t, err := p.GetPlainText(nil)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if t = strings.TrimSpace(t); t != "" {
|
||||
b.WriteString(t)
|
||||
b.WriteString("\n\n")
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(b.String()) == "" {
|
||||
return "", ErrNoText
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
@@ -55,6 +55,8 @@ type Row = {
|
||||
spaceName: string;
|
||||
/** A database record in the page, found on its own. */
|
||||
record?: SearchHit["record"];
|
||||
/** A file attached to the page whose text matched. */
|
||||
file?: SearchHit["file"];
|
||||
parts: { text: string; mark: boolean }[];
|
||||
};
|
||||
|
||||
@@ -77,7 +79,7 @@ const rows = computed<Row[]>(() =>
|
||||
searching.value
|
||||
? hits.value.map((h) => ({
|
||||
...h,
|
||||
key: h.record ? `${h.id}#${h.record.database}-${h.record.row}` : h.id,
|
||||
key: h.record ? `${h.id}#${h.record.database}-${h.record.row}` : h.file ? `${h.id}@${h.file.id}` : h.id,
|
||||
parts: parts(h.snippet, h.highlights),
|
||||
}))
|
||||
: recent.value.map((p) => ({ ...p, key: p.id, parts: [] })),
|
||||
@@ -242,16 +244,20 @@ function onKey(e: KeyboardEvent) {
|
||||
@mousedown.prevent="go(r)"
|
||||
>
|
||||
<DwIcon v-if="r.record" name="database" :size="18" class="mt-0.5 text-ink-muted" />
|
||||
<DwIcon v-else-if="r.file" name="paperclip" :size="18" class="mt-0.5 text-ink-muted" />
|
||||
<span v-else-if="r.icon" class="w-5 shrink-0 text-center">{{ r.icon }}</span>
|
||||
<DwIcon v-else name="page" :size="18" class="mt-0.5 text-ink-muted" />
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="flex items-baseline gap-2">
|
||||
<span class="truncate text-ui-md font-medium text-ink">{{
|
||||
(r.record ? r.record.title : r.title) || $t("home.untitled")
|
||||
}}</span>
|
||||
<span v-if="r.record" class="truncate text-ui-xs text-ink-muted" data-testid="search-record-page">{{
|
||||
$t("search.inPage", { page: r.title || $t("home.untitled") })
|
||||
(r.record ? r.record.title : r.file ? r.file.name : r.title) || $t("home.untitled")
|
||||
}}</span>
|
||||
<span
|
||||
v-if="r.record || r.file"
|
||||
class="truncate text-ui-xs text-ink-muted"
|
||||
data-testid="search-record-page"
|
||||
>{{ $t("search.inPage", { page: r.title || $t("home.untitled") }) }}</span
|
||||
>
|
||||
<span class="shrink-0 text-ui-xs text-ink-muted">{{ r.spaceName }}</span>
|
||||
</span>
|
||||
<span v-if="r.parts.length" class="mt-0.5 line-clamp-2 block text-ui-sm text-ink-muted">
|
||||
|
||||
@@ -5094,6 +5094,15 @@ components:
|
||||
database: { type: string }
|
||||
row: { type: string }
|
||||
title: { type: string }
|
||||
file:
|
||||
type: object
|
||||
description: >-
|
||||
Set when the match is in a file attached to the page (the text of PDFs, Word, HTML and text files is
|
||||
searchable); snippet is from the file
|
||||
required: [id, name]
|
||||
properties:
|
||||
id: { type: string, description: "The attachment (its address is /api/v1/files/<id>)" }
|
||||
name: { type: string }
|
||||
icon: { type: string }
|
||||
space: { type: string }
|
||||
spaceName: { type: string }
|
||||
|
||||
Reference in new issue
Block a user