// SPDX-License-Identifier: AGPL-3.0-or-later // Package readwise keeps a person's Readwise highlights in Docwell (Phase F, // ADR-16). With their Readwise access token, the readwise.sync job asks the // Readwise export API every hour for what changed: a new book, article or // tweet thread gets a page under a "Readwise" page in the space they chose, // and new highlights are added to the end of the page that already has the // book. Pages are made and changed as the person, with their rights. package readwise import ( "context" "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "io" "log/slog" "net" "net/http" "net/url" "strconv" "strings" "sync" "time" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/convert" "docwell/server/internal/directory" "docwell/server/internal/store/pocketbase" "docwell/server/internal/webhooks" ) // Directory is the part of directory.Service a sync needs. type Directory interface { CallerOf(ctx context.Context, id string) (access.Caller, error) GetSpace(ctx context.Context, c access.Caller, id string) (directory.Space, error) GetPage(ctx context.Context, c access.Caller, id string) (directory.Page, error) CreatePage(ctx context.Context, c access.Caller, spaceID string, in directory.CreatePageInput) (directory.Page, error) GetPageContent(ctx context.Context, c access.Caller, id string) (directory.PageContent, error) SavePageContent(ctx context.Context, c access.Caller, id string, in directory.SavePageContentInput) (directory.PageContent, error) ImportConverted(ctx context.Context, c access.Caller, spaceID, parent string, pages []convert.NotionPage, assets []convert.Asset) ([]directory.Page, error) } // Options configure the service. type Options struct { Secret string // API replaces https://readwise.io (tests). API string // Client replaces the HTTP client (tests). Client *http.Client // Every is how often each connection is synced (1 h). Every time.Duration // AllowLocal lets requests reach loopback addresses (development). AllowLocal bool } // API is Readwise (a variable for test builds). var API = "https://readwise.io" type Service struct { pb *pocketbase.Client dir Directory aead cipher.AEAD api string client *http.Client every time.Duration mu sync.Mutex busy map[string]bool } func New(pb *pocketbase.Client, dir Directory, o Options) *Service { key := sha256.Sum256([]byte("docwell-readwise:" + o.Secret)) block, _ := aes.NewCipher(key[:]) aead, _ := cipher.NewGCM(block) api := strings.TrimRight(o.API, "/") if api == "" { api = API } client := o.Client if client == nil { dialer := &net.Dialer{Timeout: 10 * time.Second, Control: webhooks.Guard(o.AllowLocal)} client = &http.Client{Timeout: time.Minute, Transport: &http.Transport{DialContext: dialer.DialContext, Proxy: http.ProxyFromEnvironment}} } every := o.Every if every <= 0 { every = time.Hour } return &Service{pb: pb, dir: dir, aead: aead, api: api, client: client, every: every, busy: map[string]bool{}} } func (s *Service) seal(plain string) string { nonce := make([]byte, s.aead.NonceSize()) _, _ = rand.Read(nonce) return "v1:" + base64.StdEncoding.EncodeToString(s.aead.Seal(nonce, nonce, []byte(plain), nil)) } func (s *Service) open(sealed string) (string, error) { raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sealed, "v1:")) n := s.aead.NonceSize() if err != nil || len(raw) < n { return "", errors.New("the stored Readwise token cannot be decrypted (the server secret changed); enter it again") } plain, err := s.aead.Open(nil, raw[:n], raw[n:], nil) if err != nil { return "", errors.New("the stored Readwise token cannot be decrypted (the server secret changed); enter it again") } return string(plain), nil } // book is what a sync remembers of a Readwise book: its page and the // highlights already on it. type book struct { Page string `json:"page"` Highlights []int64 `json:"highlights"` } type record struct { ID string `json:"id"` User string `json:"user"` Workspace string `json:"workspace"` Space string `json:"space"` Parent string `json:"parent"` Secret string `json:"secret"` Enabled bool `json:"enabled"` Cursor string `json:"cursor"` Books map[string]*book `json:"books"` LastSync string `json:"last_sync"` LastError string `json:"last_error"` Highlights float64 `json:"highlights"` } // Connection is a person's Readwise sync as they see it (never the token). type Connection struct { Connected bool `json:"connected"` Workspace string `json:"workspace"` Space string `json:"space"` Parent string `json:"parent"` Enabled bool `json:"enabled"` LastSync string `json:"lastSync"` LastError string `json:"lastError"` Highlights int `json:"highlights"` Books int `json:"books"` } func (r record) view() Connection { return Connection{ Connected: true, Workspace: r.Workspace, Space: r.Space, Parent: r.Parent, Enabled: r.Enabled, LastSync: r.LastSync, LastError: r.LastError, Highlights: int(r.Highlights), Books: len(r.Books), } } func (s *Service) find(ctx context.Context, user string) (*record, error) { if user == "" { return nil, apperr.NotFound("not found") } res, err := pocketbase.List[record](ctx, s.pb, "readwise_syncs", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("user = '%s'", user)}) if err != nil { return nil, err } if len(res.Items) == 0 { return nil, nil } return &res.Items[0], nil } // Get returns the caller's connection ({connected: false} when there is none). func (s *Service) Get(ctx context.Context, c access.Caller) (Connection, error) { r, err := s.find(ctx, c.ID) if err != nil || r == nil { return Connection{}, err } return r.view(), nil } // Input sets up or changes the caller's sync. An empty Token keeps the // stored one. type Input struct { Token string `json:"token"` Space string `json:"space"` Enabled *bool `json:"enabled"` } // Save checks the token with Readwise and the space with Docwell, stores // the connection and starts a first sync in the background. func (s *Service) Save(ctx context.Context, c access.Caller, in Input) (Connection, error) { r, err := s.find(ctx, c.ID) if err != nil { return Connection{}, err } body := map[string]any{} if t := strings.TrimSpace(in.Token); t != "" { if len(t) > 200 { return Connection{}, apperr.InvalidFields(map[string]string{"token": "The token is too long."}) } if err := s.checkToken(ctx, t); err != nil { return Connection{}, apperr.InvalidFields(map[string]string{"token": err.Error()}) } body["secret"] = s.seal(t) } else if r == nil { return Connection{}, apperr.InvalidFields(map[string]string{"token": "Paste your Readwise access token."}) //nolint:gosec // a message, not a credential } if in.Space != "" && (r == nil || in.Space != r.Space) { sp, err := s.dir.GetSpace(ctx, c, in.Space) if err != nil { return Connection{}, err } if sp.Role != access.SpaceEditor && sp.Role != access.SpaceAdmin { return Connection{}, apperr.InvalidFields(map[string]string{"space": "Choose a space you can add pages to."}) } body["space"], body["workspace"], body["parent"] = sp.ID, sp.Workspace, "" // Another space starts over: its books are not there yet. body["books"], body["cursor"], body["highlights"] = map[string]any{}, "", 0 } else if r == nil { return Connection{}, apperr.InvalidFields(map[string]string{"space": "Choose the space highlights go to."}) } if in.Enabled != nil { body["enabled"] = *in.Enabled } else if r == nil { body["enabled"] = true } var saved record if r == nil { body["user"] = c.ID saved, err = pocketbase.Create[record](ctx, s.pb, "readwise_syncs", body) } else { saved, err = pocketbase.Update[record](ctx, s.pb, "readwise_syncs", r.ID, body) } if err != nil { return Connection{}, err } if saved.Enabled { go func() { //nolint:gosec // the first sync outlives the request on purpose ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute) defer cancel() if err := s.sync(ctx, saved); err != nil { slog.Info("readwise sync failed", "user", saved.User, "err", err) } }() } return saved.view(), nil } // Delete disconnects Readwise; the pages made so far stay. func (s *Service) Delete(ctx context.Context, c access.Caller) error { r, err := s.find(ctx, c.ID) if err != nil { return err } if r == nil { return apperr.NotFound("Readwise is not connected") } return s.pb.Delete(ctx, "readwise_syncs", r.ID) } // SyncNow syncs the caller's highlights and returns the result. func (s *Service) SyncNow(ctx context.Context, c access.Caller) (Connection, error) { r, err := s.find(ctx, c.ID) if err != nil { return Connection{}, err } if r == nil { return Connection{}, apperr.NotFound("Readwise is not connected") } if err := s.sync(ctx, *r); err != nil { slog.Debug("readwise sync failed", "user", r.User, "err", err) } r, err = s.find(ctx, c.ID) if err != nil || r == nil { return Connection{}, err } return r.view(), nil } // SyncDue syncs every connection not synced for an hour (the readwise.sync job). func (s *Service) SyncDue(ctx context.Context) error { cutoff := time.Now().Add(-s.every).UTC().Format("2006-01-02 15:04:05.000Z") for page := 1; ; page++ { res, err := pocketbase.List[record](ctx, s.pb, "readwise_syncs", pocketbase.ListOptions{ Page: page, PerPage: 200, Filter: fmt.Sprintf("enabled = true && (last_sync = '' || last_sync < '%s')", cutoff), }) if err != nil { return err } for _, r := range res.Items { if ctx.Err() != nil { return ctx.Err() } if err := s.sync(ctx, r); err != nil { slog.Info("readwise sync failed", "user", r.User, "err", err) } } if page >= res.TotalPages || len(res.Items) == 0 { return nil } } } // ---- Readwise API ------------------------------------------------------------------- func (s *Service) call(ctx context.Context, token, path string, q url.Values, out any) (int, error) { u := s.api + path if len(q) > 0 { u += "?" + q.Encode() } for attempt := 0; ; attempt++ { req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { return 0, err } req.Header.Set("Authorization", "Token "+token) res, err := s.client.Do(req) if err != nil { return 0, fmt.Errorf("the Readwise API did not answer: %w", err) } body, err := io.ReadAll(io.LimitReader(res.Body, 64<<20)) _ = res.Body.Close() if err != nil { return res.StatusCode, err } if res.StatusCode == http.StatusTooManyRequests && attempt < 4 { wait := 5 * time.Second if sec, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && sec > 0 { wait = time.Duration(min(sec, 120)) * time.Second } select { case <-ctx.Done(): return 0, ctx.Err() case <-time.After(wait): } continue } switch { case res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden: return res.StatusCode, errors.New("the access token was refused by Readwise") case res.StatusCode >= 300: return res.StatusCode, fmt.Errorf("the Readwise API answered %s", res.Status) } if out != nil && len(body) > 0 { return res.StatusCode, json.Unmarshal(body, out) } return res.StatusCode, nil } } func (s *Service) checkToken(ctx context.Context, token string) error { code, err := s.call(ctx, token, "/api/v2/auth/", nil, nil) if err != nil { return err } if code != http.StatusNoContent && code != http.StatusOK { return errors.New("the token was not accepted by Readwise") } return nil } type apiTag struct { Name string `json:"name"` } type apiHighlight struct { ID int64 `json:"id"` Text string `json:"text"` Note string `json:"note"` Location any `json:"location"` LocationType string `json:"location_type"` HighlightedAt string `json:"highlighted_at"` Deleted bool `json:"is_deleted"` Tags []apiTag `json:"tags"` } type apiBook struct { ID int64 `json:"user_book_id"` Title string `json:"readable_title"` RawTitle string `json:"title"` Author string `json:"author"` SourceURL string `json:"source_url"` UniqueURL string `json:"unique_url"` Tags []apiTag `json:"book_tags"` Highlights []apiHighlight `json:"highlights"` } func names(tags []apiTag) []string { var out []string for _, t := range tags { if t.Name != "" { out = append(out, t.Name) } } return out } func (h apiHighlight) convert() convert.ReadwiseHighlight { loc := "" switch v := h.Location.(type) { case float64: loc = strconv.FormatFloat(v, 'f', -1, 64) case string: loc = v } return convert.ReadwiseHighlight{ Text: h.Text, Note: h.Note, Location: loc, LocationType: h.LocationType, HighlightedAt: h.HighlightedAt, Tags: names(h.Tags), } } // export reads every book that changed since cursor ("" = all). func (s *Service) export(ctx context.Context, token, cursor string) ([]apiBook, error) { var books []apiBook q := url.Values{} if cursor != "" { q.Set("updatedAfter", cursor) } for pages := 0; pages < 1000; pages++ { var res struct { Results []apiBook `json:"results"` NextCursor any `json:"nextPageCursor"` } if _, err := s.call(ctx, token, "/api/v2/export/", q, &res); err != nil { return nil, err } books = append(books, res.Results...) next := "" switch v := res.NextCursor.(type) { case string: next = v case float64: next = strconv.FormatFloat(v, 'f', -1, 64) } if next == "" { break } q.Set("pageCursor", next) } return books, nil } // ---- Sync ------------------------------------------------------------------------------- // sync brings one connection up to date. func (s *Service) sync(ctx context.Context, r record) (err error) { s.mu.Lock() if s.busy[r.ID] { s.mu.Unlock() return nil } s.busy[r.ID] = true s.mu.Unlock() started := time.Now().UTC() defer func() { s.mu.Lock() delete(s.busy, r.ID) s.mu.Unlock() patch := map[string]any{"last_sync": started.Format("2006-01-02 15:04:05.000Z"), "last_error": "", "books": r.Books, "parent": r.Parent} if err != nil { msg := err.Error() if len(msg) > 500 { msg = msg[:500] } patch["last_error"] = msg } else { patch["cursor"] = started.Format(time.RFC3339) } n := 0 for _, b := range r.Books { n += len(b.Highlights) } patch["highlights"] = n if _, uerr := pocketbase.Update[record](context.WithoutCancel(ctx), s.pb, "readwise_syncs", r.ID, patch); uerr != nil { slog.Warn("readwise status not saved", "user", r.User, "err", uerr) } }() if r.Books == nil { r.Books = map[string]*book{} } c, err := s.dir.CallerOf(ctx, r.User) if err != nil { return err } token, err := s.open(r.Secret) if err != nil { return err } books, err := s.export(ctx, token, r.Cursor) if err != nil { return err } for _, b := range books { if ctx.Err() != nil { return ctx.Err() } if err := s.syncBook(ctx, c, &r, b); err != nil { return fmt.Errorf("%q: %w", b.title(), err) } } return nil } func (b apiBook) title() string { if strings.TrimSpace(b.Title) != "" { return strings.TrimSpace(b.Title) } if strings.TrimSpace(b.RawTitle) != "" { return strings.TrimSpace(b.RawTitle) } return "Untitled" } // parent is the "Readwise" page books go under, made when missing. func (s *Service) parent(ctx context.Context, c access.Caller, r *record) (string, error) { if r.Parent != "" { if p, err := s.dir.GetPage(ctx, c, r.Parent); err == nil && !p.InTrash && p.Space == r.Space { return r.Parent, nil } } p, err := s.dir.CreatePage(ctx, c, r.Space, directory.CreatePageInput{Title: "Readwise"}) if err != nil { return "", err } raw, _ := json.Marshal(convert.ReadwiseIndex()) if _, err := s.dir.SavePageContent(ctx, c, p.ID, directory.SavePageContentInput{Content: raw}); err != nil { return "", err } r.Parent = p.ID return p.ID, nil } func (s *Service) syncBook(ctx context.Context, c access.Caller, r *record, b apiBook) error { key := strconv.FormatInt(b.ID, 10) known := r.Books[key] have := map[int64]bool{} if known != nil { for _, id := range known.Highlights { have[id] = true } } var fresh []apiHighlight for _, h := range b.Highlights { if !h.Deleted && !have[h.ID] && strings.TrimSpace(h.Text) != "" { fresh = append(fresh, h) } } if len(fresh) == 0 { return nil } hs := make([]convert.ReadwiseHighlight, len(fresh)) for i, h := range fresh { hs[i] = h.convert() } // A book whose page is gone (deleted, or in the trash) gets a new one. if known != nil { if p, err := s.dir.GetPage(ctx, c, known.Page); err != nil || p.InTrash { known = nil } } if known == nil { parent, err := s.parent(ctx, c, r) if err != nil { return err } link := b.SourceURL if link == "" { link = b.UniqueURL } page := convert.ReadwiseBook{Title: b.title(), Author: b.Author, URL: link, Tags: names(b.Tags), Highlights: hs}.Page() created, err := s.dir.ImportConverted(ctx, c, r.Space, parent, []convert.NotionPage{page}, nil) if err != nil { return err } if len(created) == 0 { return errors.New("no page was made") } known = &book{Page: created[0].ID} r.Books[key] = known } else { content, err := s.dir.GetPageContent(ctx, c, known.Page) if err != nil { return err } doc := convert.Node{Type: "doc"} if len(content.Content) > 0 && string(content.Content) != "null" { if err := json.Unmarshal(content.Content, &doc); err != nil { return err } } doc.Content = append(doc.Content, convert.ReadwiseNodes(hs)...) raw, err := json.Marshal(doc) if err != nil { return err } if _, err := s.dir.SavePageContent(ctx, c, known.Page, directory.SavePageContentInput{Content: raw}); err != nil { return err } } for _, h := range fresh { known.Highlights = append(known.Highlights, h.ID) } return nil }