feat: ingest Brevier reading copies and phone notes (#53)
feat: ingest Brevier reading copies and phone notes (#53) Co-authored-by: David Gwilliam <dhgwilliam@gmail.com> Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #53.
This commit is contained in:
@@ -0,0 +1,447 @@
|
||||
package ingest
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pierrec/lz4/v4"
|
||||
)
|
||||
|
||||
// BrevierIngester indexes what the Brevier reader (github.com/gurov/brevier)
|
||||
// keeps locally: its archive of pages that were read, and the notes it exports
|
||||
// from the phone.
|
||||
//
|
||||
// Brevier writes a copy as Markdown with YAML front matter:
|
||||
//
|
||||
// ---
|
||||
// title: "…"
|
||||
// source: "https://…"
|
||||
// read: 2026-11-08T14:03:00-08:00
|
||||
// ---
|
||||
// <body>
|
||||
//
|
||||
// under <archive>/<host>/<date>-<slug>.md.lz4, or .md when "plain copies" is
|
||||
// switched on. Both forms are read here: the setting only changes how new
|
||||
// copies are written, and older ones stay compressed.
|
||||
//
|
||||
// Notes exported from the phone come through the share sheet as one .md, or a
|
||||
// .zip with one .md per page. The phone's archive itself is app-private and
|
||||
// never leaves the device, so notes are what the phone can contribute.
|
||||
type BrevierIngester struct {
|
||||
Version string
|
||||
Archive string // archive root; empty = not present
|
||||
Inbox string // directory where phone exports are dropped
|
||||
}
|
||||
|
||||
func NewBrevierIngester() *BrevierIngester {
|
||||
return &BrevierIngester{
|
||||
Version: "brevier/v1",
|
||||
Archive: firstNonEmpty(os.Getenv("BREVIER_ARCHIVE"), defaultBrevierArchive()),
|
||||
Inbox: firstNonEmpty(os.Getenv("BREVIER_INBOX"), defaultBrevierInbox()),
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BrevierIngester) SourceID() string { return "brevier" }
|
||||
|
||||
func defaultBrevierArchive() string {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
candidates := []string{}
|
||||
if xdg := os.Getenv("XDG_DATA_HOME"); xdg != "" {
|
||||
candidates = append(candidates, filepath.Join(xdg, "brevier", "archive"))
|
||||
}
|
||||
candidates = append(candidates,
|
||||
filepath.Join(home, ".local", "share", "brevier", "archive"),
|
||||
// The Flatpak keeps its data inside the sandbox, which is where a
|
||||
// desktop install will actually write.
|
||||
filepath.Join(home, ".var", "app", "io.github.gurov.brevier", "data", "brevier", "archive"),
|
||||
)
|
||||
for _, c := range candidates {
|
||||
if st, err := os.Stat(c); err == nil && st.IsDir() {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return candidates[0]
|
||||
}
|
||||
|
||||
func defaultBrevierInbox() string {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(home, ".local", "share", "knox", "inbox", "brevier")
|
||||
}
|
||||
|
||||
// maxBrevierFile bounds one copy or one zip member. A long article is tens of
|
||||
// kilobytes; anything near this is not a page.
|
||||
const maxBrevierFile = 8 << 20
|
||||
|
||||
func (b *BrevierIngester) IngestAll() ([]*IngestResult, error) {
|
||||
copies, err := b.readArchive()
|
||||
if err != nil {
|
||||
return copies, err
|
||||
}
|
||||
notes, err := b.readInbox()
|
||||
results := append(copies, notes...)
|
||||
|
||||
// A page read on several days has several copies, all sharing a
|
||||
// fingerprint. Oldest first so the newest copy is the one that lands last
|
||||
// and becomes the entry's content.
|
||||
sort.SliceStable(results, func(i, j int) bool {
|
||||
if results[i].SourcePath != results[j].SourcePath {
|
||||
return results[i].SourcePath < results[j].SourcePath
|
||||
}
|
||||
return results[i].CreatedAt < results[j].CreatedAt
|
||||
})
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (b *BrevierIngester) readArchive() ([]*IngestResult, error) {
|
||||
if b.Archive == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if _, err := os.Stat(b.Archive); err != nil {
|
||||
return nil, nil // no Brevier on this machine
|
||||
}
|
||||
|
||||
var out []*IngestResult
|
||||
err := filepath.WalkDir(b.Archive, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil // skip an unreadable file, keep walking
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
name := d.Name()
|
||||
compressed := strings.HasSuffix(name, ".md.lz4")
|
||||
if !compressed && !strings.HasSuffix(name, ".md") {
|
||||
return nil
|
||||
}
|
||||
text, err := readBrevierFile(path, compressed)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if r := b.copyResult(path, text); r != nil {
|
||||
out = append(out, r)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
func readBrevierFile(path string, compressed bool) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var reader io.Reader = io.LimitReader(f, maxBrevierFile)
|
||||
if compressed {
|
||||
reader = lz4.NewReader(reader)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(reader, maxBrevierFile))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(body), nil
|
||||
}
|
||||
|
||||
// copyResult turns one archived copy into an entry. Fingerprinting by the
|
||||
// source URL means a page read again on another day updates the entry (the
|
||||
// content hash carries the version) instead of adding a second entry for the
|
||||
// same page.
|
||||
func (b *BrevierIngester) copyResult(path, text string) *IngestResult {
|
||||
meta, body := splitFrontMatter(text)
|
||||
source := strings.TrimSpace(meta["source"])
|
||||
if source == "" {
|
||||
return nil // an archive copy always carries its address
|
||||
}
|
||||
title := strings.TrimSpace(meta["title"])
|
||||
if title == "" {
|
||||
title = source
|
||||
}
|
||||
body = strings.TrimSpace(body)
|
||||
if body == "" {
|
||||
return nil
|
||||
}
|
||||
read := strings.TrimSpace(meta["read"])
|
||||
|
||||
return &IngestResult{
|
||||
Fingerprint: Fingerprint([]byte("brevier:" + source)),
|
||||
SourceID: b.SourceID(),
|
||||
SourcePath: source,
|
||||
Project: brevierHost(source, path),
|
||||
ContentType: "reading/copy",
|
||||
Title: title,
|
||||
Summary: plainPreview(body, 300),
|
||||
Content: body,
|
||||
CreatedAt: normalizeTime(read),
|
||||
Confidence: 0.9,
|
||||
IngesterVersion: b.Version,
|
||||
ContentHash: Fingerprint([]byte(body)),
|
||||
Provenance: map[string]any{
|
||||
"file": path,
|
||||
"source": source,
|
||||
"read": read,
|
||||
"kind": "copy",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (b *BrevierIngester) readInbox() ([]*IngestResult, error) {
|
||||
if b.Inbox == "" {
|
||||
return nil, nil
|
||||
}
|
||||
entries, err := os.ReadDir(b.Inbox)
|
||||
if err != nil {
|
||||
return nil, nil // nothing dropped yet
|
||||
}
|
||||
|
||||
var out []*IngestResult
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(b.Inbox, e.Name())
|
||||
switch {
|
||||
case strings.HasSuffix(e.Name(), ".zip"):
|
||||
out = append(out, b.readNotesZip(path)...)
|
||||
case strings.HasSuffix(e.Name(), ".md"):
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, b.parseNotes(path, string(data))...)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (b *BrevierIngester) readNotesZip(path string) []*IngestResult {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []*IngestResult
|
||||
for _, f := range zr.File {
|
||||
if !strings.HasSuffix(f.Name, ".md") {
|
||||
continue // images/ and anything else
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(rc, maxBrevierFile))
|
||||
rc.Close()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, b.parseNotes(path+"#"+f.Name, string(body))...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// parseNotes handles the shapes Brevier exports:
|
||||
//
|
||||
// - one page, front matter with title/source/created;
|
||||
// - several pages, a `## [title](url)` section each;
|
||||
// - a saved article with no front matter at all (the address is not written
|
||||
// into a saved copy), which is fingerprinted by content instead.
|
||||
func (b *BrevierIngester) parseNotes(file, text string) []*IngestResult {
|
||||
meta, body := splitFrontMatter(text)
|
||||
if source := strings.TrimSpace(meta["source"]); source != "" {
|
||||
if r := b.notesResult(file, source, strings.TrimSpace(meta["title"]), strings.TrimSpace(body), normalizeTime(meta["created"])); r != nil {
|
||||
return []*IngestResult{r}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var out []*IngestResult
|
||||
for _, s := range splitSections(text) {
|
||||
out = append(out, b.notesResult(file, s.url, s.title, s.body, ""))
|
||||
}
|
||||
if len(out) > 0 {
|
||||
return out
|
||||
}
|
||||
|
||||
// A saved article: keep it, keyed by its content, since re-saving an
|
||||
// unchanged page must not add a second entry.
|
||||
body = strings.TrimSpace(text)
|
||||
if body == "" {
|
||||
return nil
|
||||
}
|
||||
title := firstHeading(body)
|
||||
return []*IngestResult{{
|
||||
Fingerprint: Fingerprint([]byte("brevier-save:" + Fingerprint([]byte(body)))),
|
||||
SourceID: b.SourceID(),
|
||||
SourcePath: firstNonEmpty(title, file),
|
||||
ContentType: "reading/saved",
|
||||
Title: firstNonEmpty(title, "Saved page"),
|
||||
Summary: plainPreview(body, 300),
|
||||
Content: body,
|
||||
Confidence: 0.8,
|
||||
IngesterVersion: b.Version,
|
||||
ContentHash: Fingerprint([]byte(body)),
|
||||
Provenance: map[string]any{"file": file, "kind": "save"},
|
||||
}}
|
||||
}
|
||||
|
||||
func (b *BrevierIngester) notesResult(file, source, title, body, created string) *IngestResult {
|
||||
if source == "" || body == "" {
|
||||
return nil
|
||||
}
|
||||
if title == "" {
|
||||
title = source
|
||||
}
|
||||
return &IngestResult{
|
||||
Fingerprint: Fingerprint([]byte("brevier-notes:" + source)),
|
||||
SourceID: "brevier-notes",
|
||||
SourcePath: source,
|
||||
Project: brevierHost(source, file),
|
||||
ContentType: "reading/notes",
|
||||
Title: title,
|
||||
Summary: plainPreview(body, 300),
|
||||
Content: body,
|
||||
CreatedAt: created,
|
||||
Confidence: 0.9,
|
||||
IngesterVersion: b.Version,
|
||||
ContentHash: Fingerprint([]byte(body)),
|
||||
Provenance: map[string]any{
|
||||
"file": file,
|
||||
"source": source,
|
||||
"kind": "notes",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type brevierSection struct {
|
||||
title string
|
||||
url string
|
||||
body string
|
||||
}
|
||||
|
||||
var brevierSectionRe = regexp.MustCompile(`(?m)^## \[(.+?)\]\((\S+?)\)\s*$`)
|
||||
|
||||
func splitSections(text string) []brevierSection {
|
||||
locs := brevierSectionRe.FindAllStringSubmatchIndex(text, -1)
|
||||
out := make([]brevierSection, 0, len(locs))
|
||||
for i, loc := range locs {
|
||||
title := strings.TrimSpace(text[loc[2]:loc[3]])
|
||||
link := strings.TrimSpace(text[loc[4]:loc[5]])
|
||||
start := loc[1]
|
||||
end := len(text)
|
||||
if i+1 < len(locs) {
|
||||
end = locs[i+1][0]
|
||||
}
|
||||
out = append(out, brevierSection{
|
||||
title: title,
|
||||
url: link,
|
||||
body: strings.TrimSpace(text[start:end]),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// splitFrontMatter separates the YAML block Brevier writes from the body.
|
||||
// Only the handful of scalar keys knox needs are read; nothing else is parsed.
|
||||
func splitFrontMatter(text string) (map[string]string, string) {
|
||||
meta := map[string]string{}
|
||||
if !strings.HasPrefix(text, "---\n") {
|
||||
return meta, text
|
||||
}
|
||||
rest := text[len("---\n"):]
|
||||
end := strings.Index(rest, "\n---")
|
||||
if end < 0 {
|
||||
return meta, text
|
||||
}
|
||||
head := rest[:end]
|
||||
body := strings.TrimLeft(rest[end+len("\n---"):], "\n")
|
||||
for _, line := range strings.Split(head, "\n") {
|
||||
key, value, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
meta[strings.TrimSpace(key)] = unquoteYAML(strings.TrimSpace(value))
|
||||
}
|
||||
return meta, body
|
||||
}
|
||||
|
||||
// unquoteYAML undoes the escaping Brevier writes for titles and addresses.
|
||||
func unquoteYAML(v string) string {
|
||||
if len(v) < 2 || v[0] != '"' || v[len(v)-1] != '"' {
|
||||
return v
|
||||
}
|
||||
inner := v[1 : len(v)-1]
|
||||
var b strings.Builder
|
||||
b.Grow(len(inner))
|
||||
for i := 0; i < len(inner); i++ {
|
||||
if inner[i] == '\\' && i+1 < len(inner) {
|
||||
i++
|
||||
}
|
||||
b.WriteByte(inner[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// normalizeTime keeps Brevier's RFC3339 stamp when it parses, and otherwise
|
||||
// returns it untouched: the archive file's own date is still better than
|
||||
// inventing one.
|
||||
func normalizeTime(v string) string {
|
||||
v = strings.TrimSpace(v)
|
||||
if v == "" {
|
||||
return ""
|
||||
}
|
||||
if t, err := time.Parse(time.RFC3339, v); err == nil {
|
||||
return t.UTC().Format(time.RFC3339)
|
||||
}
|
||||
if t, err := time.Parse("2006-01-02", v); err == nil {
|
||||
return t.UTC().Format(time.RFC3339)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func brevierHost(source, path string) string {
|
||||
if u, err := url.Parse(source); err == nil && u.Host != "" {
|
||||
return u.Host
|
||||
}
|
||||
return filepath.Base(filepath.Dir(path))
|
||||
}
|
||||
|
||||
func firstHeading(text string) string {
|
||||
for _, line := range strings.Split(text, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if strings.HasPrefix(line, "# ") {
|
||||
return strings.TrimSpace(strings.TrimPrefix(line, "# "))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// plainPreview flattens Markdown into a one-line summary.
|
||||
func plainPreview(body string, n int) string {
|
||||
flat := strings.Join(strings.Fields(body), " ")
|
||||
if flat == "" {
|
||||
return ""
|
||||
}
|
||||
r := []rune(flat)
|
||||
if len(r) > n {
|
||||
return string(r[:n]) + "…"
|
||||
}
|
||||
return string(r)
|
||||
}
|
||||
Reference in New Issue
Block a user