Files
knox/internal/ingest/karakeep.go
T
david 0b8ac34aee chore: checkpoint uncommitted work before session store fix
Pre-existing work-in-progress in the tree: karakeep, snippets,
skills-health and redaction ingesters, the opencode.db session sweep,
gossip and metrics changes. Checkpointed as-is so the adapter fix in the
next commit stays reviewable on its own.
2026-11-01 13:48:09 -08:00

262 lines
6.9 KiB
Go

package ingest
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"
)
// KarakeepIngester indexes bookmarks from a self-hosted Karakeep instance via
// its REST API. For link bookmarks it also pulls Karakeep's crawled article
// text (the "content download" asset) so the full page is searchable in knox.
//
// Configured entirely by environment: KARAKEEP_URL (e.g.
// https://keep.example.com) and KARAKEEP_API_KEY. When either is unset the
// source is a no-op.
type KarakeepIngester struct {
Version string
BaseURL string
APIKey string
MaxPages int
client *http.Client
}
func NewKarakeepIngester() *KarakeepIngester {
return &KarakeepIngester{
Version: "karakeep/v1",
BaseURL: strings.TrimRight(os.Getenv("KARAKEEP_URL"), "/"),
APIKey: os.Getenv("KARAKEEP_API_KEY"),
MaxPages: 25, // 25 * 100 = up to 2500 bookmarks per sweep
client: &http.Client{Timeout: 20 * time.Second},
}
}
func (k *KarakeepIngester) SourceID() string { return "karakeep" }
// kaAssetCache caches downloaded content assets (assetID -> extracted text) so
// unchanged bookmarks are not re-downloaded on every watch tick.
var kaAssetCache = struct {
sync.Mutex
m map[string]string
}{m: map[string]string{}}
func (k *KarakeepIngester) IngestAll() ([]*IngestResult, error) {
if k.BaseURL == "" || k.APIKey == "" {
return nil, nil // not configured
}
var results []*IngestResult
cursor := ""
for page := 0; page < k.MaxPages; page++ {
bookmarks, next, err := k.fetchPage(cursor)
if err != nil {
return results, err
}
for _, b := range bookmarks {
if r := k.toResult(b); r != nil {
results = append(results, r)
}
}
if next == "" {
break
}
cursor = next
}
return results, nil
}
type kaTag struct {
Name string `json:"name"`
AttachedBy string `json:"attachedBy"`
}
type kaContent struct {
Type string `json:"type"`
URL string `json:"url"`
Title string `json:"title"`
Description string `json:"description"`
Content string `json:"content"` // inline text for type=text bookmarks
ContentAssetID string `json:"contentAssetId"`
Author string `json:"author"`
Publisher string `json:"publisher"`
CrawlStatus string `json:"crawlStatus"`
}
type kaBookmark struct {
ID string `json:"id"`
Title *string `json:"title"`
CreatedAt string `json:"createdAt"`
ModifiedAt string `json:"modifiedAt"`
Archived bool `json:"archived"`
Favourited bool `json:"favourited"`
Note *string `json:"note"`
Summary *string `json:"summary"`
Tags []kaTag `json:"tags"`
Content kaContent `json:"content"`
}
func (k *KarakeepIngester) fetchPage(cursor string) ([]kaBookmark, string, error) {
u := k.BaseURL + "/api/v1/bookmarks?limit=100"
if cursor != "" {
u += "&cursor=" + cursor
}
body, err := k.get(u)
if err != nil {
return nil, "", err
}
var payload struct {
Bookmarks []kaBookmark `json:"bookmarks"`
NextCursor string `json:"nextCursor"`
}
if err := json.Unmarshal(body, &payload); err != nil {
return nil, "", fmt.Errorf("karakeep decode: %w", err)
}
return payload.Bookmarks, payload.NextCursor, nil
}
func (k *KarakeepIngester) get(u string) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, u, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+k.APIKey)
req.Header.Set("Accept", "application/json")
resp, err := k.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("karakeep GET %s: status %d", u, resp.StatusCode)
}
return io.ReadAll(io.LimitReader(resp.Body, 8<<20))
}
// fetchAssetText downloads a content asset (readability-extracted HTML) and
// returns plain text, caching by asset id.
func (k *KarakeepIngester) fetchAssetText(assetID string) string {
kaAssetCache.Lock()
if t, ok := kaAssetCache.m[assetID]; ok {
kaAssetCache.Unlock()
return t
}
kaAssetCache.Unlock()
body, err := k.get(k.BaseURL + "/api/v1/assets/" + assetID)
if err != nil {
return ""
}
text := htmlToText(string(body))
kaAssetCache.Lock()
kaAssetCache.m[assetID] = text
kaAssetCache.Unlock()
return text
}
func (k *KarakeepIngester) toResult(b kaBookmark) *IngestResult {
url := strings.TrimSpace(b.Content.URL)
title := firstNonEmpty(deref(b.Title), b.Content.Title, url, b.ID)
if title == "" {
return nil
}
// Body text: prefer the crawled article, then inline text bookmark, then
// description.
var content string
switch {
case b.Content.ContentAssetID != "":
content = k.fetchAssetText(b.Content.ContentAssetID)
case b.Content.Type == "text" && b.Content.Content != "":
content = htmlToText(b.Content.Content)
}
if content == "" {
content = b.Content.Description
}
summary := firstNonEmpty(deref(b.Note), deref(b.Summary), b.Content.Description, url)
if r := []rune(summary); len(r) > 300 {
summary = string(r[:300]) + "…"
}
tagNames := make([]string, 0, len(b.Tags))
for _, t := range b.Tags {
tagNames = append(tagNames, t.Name)
}
confidence := 0.8
if b.Favourited {
confidence = 0.9
}
createdAt := b.CreatedAt
if createdAt == "" {
createdAt = b.ModifiedAt
}
return &IngestResult{
Fingerprint: FingerprintWithMeta([]byte("karakeep:"+b.ID), map[string]string{"source": "karakeep"}),
SourceID: k.SourceID(),
SourcePath: url,
Project: "",
ContentType: "bookmark/" + b.Content.Type,
Title: title,
Summary: summary,
Content: content,
CreatedAt: createdAt,
Confidence: confidence,
IngesterVersion: k.Version,
ContentHash: Fingerprint([]byte(b.ModifiedAt + "|" + b.Content.ContentAssetID + "|" + fmt.Sprint(len(content)))),
Provenance: map[string]any{
"bookmark_id": b.ID,
"url": url,
"tags": tagNames,
"archived": b.Archived,
"favourited": b.Favourited,
"author": b.Content.Author,
"publisher": b.Content.Publisher,
"content_len": len(content),
},
}
}
func deref(s *string) string {
if s == nil {
return ""
}
return strings.TrimSpace(*s)
}
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if s := strings.TrimSpace(v); s != "" {
return s
}
}
return ""
}
var (
htmlScriptStyleRE = regexp.MustCompile(`(?is)<(script|style|noscript|template)[^>]*>.*?</(script|style|noscript|template)>`)
htmlTagRE = regexp.MustCompile(`(?s)<[^>]+>`)
htmlWSRE = regexp.MustCompile(`\s+`)
)
// htmlToText crudely reduces HTML to searchable text (tags/scripts stripped,
// whitespace collapsed).
func htmlToText(h string) string {
h = htmlScriptStyleRE.ReplaceAllString(h, " ")
h = htmlTagRE.ReplaceAllString(h, " ")
replacer := strings.NewReplacer(
"&nbsp;", " ", "&amp;", "&", "&lt;", "<", "&gt;", ">",
"&#39;", "'", "&quot;", `"`, "&#x27;", "'", "&hellip;", "…",
)
h = replacer.Replace(h)
return strings.TrimSpace(htmlWSRE.ReplaceAllString(h, " "))
}