package ingest import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "sort" "strings" "time" ) // BookOrbitIngester indexes reading highlights from a self-hosted BookOrbit // instance. It uses the annotations export endpoint rather than the Postgres // schema: the export is the contract BookOrbit maintains, and it already // carries the book, chapter and note fields knox needs. // // Configured entirely by environment: BOOKORBIT_URL (e.g. // https://books.example.com), BOOKORBIT_USERNAME and BOOKORBIT_PASSWORD. When // any is unset the source is a no-op. // // Entries are chapters, not individual highlights. A book produces a handful of // dense, readable observations instead of hundreds of fragments, and knox's // observation log still versioning each chapter as highlights are added. type BookOrbitIngester struct { Version string BaseURL string Username string Password string client *http.Client } func NewBookOrbitIngester() *BookOrbitIngester { return &BookOrbitIngester{ Version: "bookorbit/v1", BaseURL: strings.TrimRight(os.Getenv("BOOKORBIT_URL"), "/"), Username: os.Getenv("BOOKORBIT_USERNAME"), Password: os.Getenv("BOOKORBIT_PASSWORD"), client: &http.Client{Timeout: 45 * time.Second}, } } func (b *BookOrbitIngester) SourceID() string { return "bookorbit" } // boAnnotation mirrors one row of GET /api/v1/annotations/export?format=json. // Field names are the API's; the export deliberately omits the author. type boAnnotation struct { ID int64 `json:"id"` BookID int64 `json:"bookId"` BookTitle string `json:"bookTitle"` ChapterTitle string `json:"chapterTitle"` Text string `json:"text"` Note string `json:"note"` Color string `json:"color"` Style string `json:"style"` Origin string `json:"origin"` HighlightedAt string `json:"highlightedAt"` } func (b *BookOrbitIngester) IngestAll() ([]*IngestResult, error) { if b.BaseURL == "" || b.Username == "" || b.Password == "" { return nil, nil // not configured } token, err := b.login() if err != nil { return nil, err } rows, err := b.export(token) if err != nil { return nil, err } return b.toResults(rows), nil } // login exchanges the stored credentials for a short-lived access token. The // endpoint is throttled (3/min), so callers should not retry tightly: one login // per sweep is the intended shape. func (b *BookOrbitIngester) login() (string, error) { payload, err := json.Marshal(map[string]string{ "username": b.Username, "password": b.Password, }) if err != nil { return "", err } req, err := http.NewRequest(http.MethodPost, b.BaseURL+"/api/v1/auth/login", bytes.NewReader(payload)) if err != nil { return "", err } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") resp, err := b.client.Do(req) if err != nil { return "", fmt.Errorf("bookorbit login: %w", err) } defer resp.Body.Close() body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<10)) if resp.StatusCode < 200 || resp.StatusCode >= 300 { return "", fmt.Errorf("bookorbit login: status %d", resp.StatusCode) } var out struct { AccessToken string `json:"accessToken"` } if err := json.Unmarshal(body, &out); err != nil { return "", fmt.Errorf("bookorbit login decode: %w", err) } if out.AccessToken == "" { return "", fmt.Errorf("bookorbit login: no access token returned") } return out.AccessToken, nil } func (b *BookOrbitIngester) export(token string) ([]boAnnotation, error) { req, err := http.NewRequest(http.MethodGet, b.BaseURL+"/api/v1/annotations/export?format=json", nil) if err != nil { return nil, err } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Accept", "application/json") resp, err := b.client.Do(req) if err != nil { return nil, fmt.Errorf("bookorbit export: %w", err) } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, fmt.Errorf("bookorbit export: status %d", resp.StatusCode) } // The whole library is one response. 32 MB is far above the current few // hundred rows and still bounds a bad day. body, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20)) if err != nil { return nil, fmt.Errorf("bookorbit export read: %w", err) } var rows []boAnnotation if err := json.Unmarshal(body, &rows); err != nil { return nil, fmt.Errorf("bookorbit export decode: %w", err) } return rows, nil } // toResults groups annotations by book and chapter. Chapters are the unit of // recall: a reader asks "what did I highlight in this chapter", not "find my // 12th highlight of the book". func (b *BookOrbitIngester) toResults(rows []boAnnotation) []*IngestResult { type key struct { bookID int64 chapter string } groups := make(map[key][]boAnnotation) books := make(map[int64]string) for _, r := range rows { chapter := strings.TrimSpace(r.ChapterTitle) k := key{bookID: r.BookID, chapter: chapter} groups[k] = append(groups[k], r) if r.BookTitle != "" { books[r.BookID] = r.BookTitle } } // Deterministic order: by book title, then chapter, then oldest highlight. keys := make([]key, 0, len(groups)) for k := range groups { keys = append(keys, k) } sort.Slice(keys, func(i, j int) bool { bi, bj := books[keys[i].bookID], books[keys[j].bookID] if bi != bj { return bi < bj } return keys[i].chapter < keys[j].chapter }) results := make([]*IngestResult, 0, len(keys)) for _, k := range keys { book := firstNonEmpty(books[k.bookID], "Unknown book") chapter := k.chapter highlights := groups[k] sort.Slice(highlights, func(i, j int) bool { return highlights[i].HighlightedAt < highlights[j].HighlightedAt }) title := book if chapter != "" { title = book + " — " + chapter } content := renderHighlights(highlights) if strings.TrimSpace(content) == "" { continue // a chapter whose annotations are all empty has nothing to say } ids := make([]int64, 0, len(highlights)) origins := make([]string, 0, 3) latest := "" summary := "" for _, h := range highlights { ids = append(ids, h.ID) if h.Origin != "" && !containsString(origins, h.Origin) { origins = append(origins, h.Origin) } if h.HighlightedAt > latest { latest = h.HighlightedAt } if summary == "" { summary = strings.TrimSpace(firstNonEmpty(h.Text, h.Note)) } } if r := []rune(summary); len(r) > 300 { summary = string(r[:300]) + "…" } results = append(results, &IngestResult{ Fingerprint: FingerprintWithMeta([]byte(fmt.Sprintf("bookorbit:%d:%s", k.bookID, chapter)), map[string]string{"source": "bookorbit"}), SourceID: b.SourceID(), SourcePath: title, Project: book, ContentType: "reading/highlights", Title: title, Summary: summary, Content: content, CreatedAt: latest, Confidence: 0.9, IngesterVersion: b.Version, // Hash the rendered body, not the row timestamps: a highlight // edited in place must update the entry, and re-importing the same // data must not append a duplicate observation. ContentHash: Fingerprint([]byte(content)), Provenance: map[string]any{ "book_id": k.bookID, "book_title": book, "chapter": chapter, "annotation_ids": ids, "origins": origins, "count": len(highlights), }, }) } return results } // renderHighlights mirrors BookOrbit's own Markdown export: a blockquote per // highlight, a Note line, and a provenance footer. func renderHighlights(rows []boAnnotation) string { var b strings.Builder for _, r := range rows { text := strings.TrimSpace(r.Text) note := strings.TrimSpace(r.Note) if text == "" && note == "" { continue } if text != "" { lines := strings.Split(text, "\n") for i, line := range lines { if i == 0 { b.WriteString("> " + strings.TrimSpace(line)) } else { b.WriteString("\n> " + strings.TrimSpace(line)) } } b.WriteString("\n") } if note != "" { if text != "" { b.WriteString("\n") } b.WriteString("Note: " + note + "\n") } if meta := highlightMeta(r); meta != "" { b.WriteString("\n" + meta + "\n") } b.WriteString("\n") } return strings.TrimSpace(b.String()) + "\n" } func highlightMeta(r boAnnotation) string { parts := make([]string, 0, 4) for _, v := range []string{r.Style, r.Color, r.Origin, shortDate(r.HighlightedAt)} { if v = strings.TrimSpace(v); v != "" { parts = append(parts, v) } } return strings.Join(parts, ", ") } // shortDate trims an RFC3339 timestamp to its date; the export always sends one. func shortDate(ts string) string { if len(ts) >= 10 { return ts[:10] } return ts } func containsString(haystack []string, needle string) bool { for _, s := range haystack { if s == needle { return true } } return false }