Files
Docwell/Server/internal/onenote/onenote.go
T
tajniak81andClaude Opus 5.5 6984c7d162 Connect Google Calendar, import OneNote notebooks, sync Readwise, and package the clipper
Phase F follow-ups (ADR-16):

- Calendars: events are now stored in calendar_events by a
  calendars.sync job (every 15 minutes per account, 90 days back and
  400 ahead), so journals open at once and keep showing events while a
  source is down. Google accounts connect with OAuth (calendar.readonly)
  through DOCWELL_GOOGLE_CLIENT_ID/SECRET; reconnecting renews access.
- OneNote: whole notebooks import through Microsoft Graph (Notes.Read,
  DOCWELL_MICROSOFT_CLIENT_ID/SECRET/TENANT) in the background, with
  section groups, sections, subpages, pictures and attached files. The
  Microsoft sign-in lives in memory for an hour and is never stored.
- Readwise: an hourly sync with the person's sealed access token; new
  books get a page under "Readwise", new highlights are appended once.
  New readwise_syncs collection.
- internal/oauth: signed states and one callback route per provider,
  routed by purpose. directory gains ImportConverted and CallerOf.
- Phone app: "Today's journal" on the home screen and calendar events
  on journal pages.
- Web clipper: `npm run package` builds Chrome/Edge, Firefox and source
  zips; store/ holds listing texts, permission notes and a privacy
  policy.
- OpenAPI, generated clients, translations, compose and .env examples,
  and user docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 14:59:34 +01:00

603 lines
18 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
// Package onenote imports whole OneNote notebooks through Microsoft Graph
// (Phase F, ADR-16). A person signs in to Microsoft (Notes.Read), picks a
// notebook, and the import runs in the background: the notebook, its
// section groups and sections become pages, each OneNote page a page under
// its section (subpages under their parent page), with images and attached
// files stored as attachments. The sign-in is kept in memory for an hour,
// only for the import; Docwell keeps no Microsoft tokens.
package onenote
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"mime"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/convert"
"docwell/server/internal/directory"
"docwell/server/internal/oauth"
"docwell/server/internal/webhooks"
)
// Purpose names the OAuth state of a OneNote sign-in.
const Purpose = "onenote"
var scopes = []string{"offline_access", "openid", "email", "User.Read", "Notes.Read"}
const (
connectionTTL = time.Hour
maxPages = 2000
maxResource = 50 << 20
maxResources = 512 << 20
)
// Importer is the part of directory.Service an import needs.
type Importer interface {
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 {
Provider oauth.Provider
States *oauth.States
PublicURL string
WebURL string
// Graph replaces https://graph.microsoft.com/v1.0 (tests).
Graph string
// Client replaces the HTTP client (tests).
Client *http.Client
// AllowLocal lets requests reach loopback addresses (development).
AllowLocal bool
}
// Graph is Microsoft Graph (a variable for test builds).
var Graph = "https://graph.microsoft.com/v1.0"
type Service struct {
o Options
dir Importer
client *http.Client
graph string
mu sync.Mutex
conns map[string]*connection
jobs map[string]*Job
}
type connection struct {
user string
email string
token oauth.Token
refresh string
expires time.Time
}
// Job is an import running in the background.
type Job struct {
ID string `json:"id"`
Notebook string `json:"notebook"`
// Status is running, done or failed.
Status string `json:"status"`
// Pages counts the OneNote pages read so far.
Pages int `json:"pages"`
Error string `json:"error"`
// Created lists the pages made at the top (the notebook's page).
Created []directory.Page `json:"created"`
user string
ended time.Time
}
// Notebook is a notebook the signed-in Microsoft account can read.
type Notebook struct {
ID string `json:"id"`
Name string `json:"name"`
Modified string `json:"modified"`
}
func New(dir Importer, o Options) *Service {
client := o.Client
if client == nil {
dialer := &net.Dialer{Timeout: 10 * time.Second, Control: webhooks.Guard(o.AllowLocal)}
client = &http.Client{Timeout: 2 * time.Minute, Transport: &http.Transport{DialContext: dialer.DialContext, Proxy: http.ProxyFromEnvironment}}
}
graph := strings.TrimRight(o.Graph, "/")
if graph == "" {
graph = Graph
}
o.PublicURL = strings.TrimRight(o.PublicURL, "/")
o.WebURL = strings.TrimRight(o.WebURL, "/")
return &Service{o: o, dir: dir, client: client, graph: graph, conns: map[string]*connection{}, jobs: map[string]*Job{}}
}
// Enabled reports whether the server has a Microsoft OAuth app.
func (s *Service) Enabled() bool { return s.o.Provider.Enabled() }
func (s *Service) redirect() string { return s.o.PublicURL + "/api/v1/oauth/microsoft/callback" }
func newID() string {
var b [12]byte
_, _ = rand.Read(b[:])
return hex.EncodeToString(b[:])
}
// ConnectURL is where the caller signs in to Microsoft; afterwards the
// browser returns to the space (?onenote=<connection>).
func (s *Service) ConnectURL(c access.Caller, space, parent string) (string, error) {
if c.ID == "" {
return "", apperr.NotFound("not found")
}
if !s.Enabled() {
return "", apperr.NotFound("Microsoft sign-in is not set up on this server")
}
if space == "" || len(space) > 64 || len(parent) > 64 {
return "", apperr.InvalidFields(map[string]string{"space": "Choose the space to import into."})
}
state := s.o.States.Sign(oauth.State{User: c.ID, Purpose: Purpose, Data: map[string]string{"space": space, "parent": parent}})
return s.o.Provider.AuthCodeURL(state, s.redirect(), scopes), nil
}
// Callback finishes the sign-in and returns where the browser goes next.
func (s *Service) Callback(ctx context.Context, st oauth.State, code, providerErr string) string {
space := st.Data["space"]
back := func(q url.Values) string {
if p := st.Data["parent"]; p != "" {
q.Set("onenoteParent", p)
}
return s.o.WebURL + "/s/" + url.PathEscape(space) + "?" + q.Encode()
}
if providerErr != "" {
return back(url.Values{"onenoteError": {"Microsoft did not connect the account (" + providerErr + ")"}})
}
tok, err := s.o.Provider.Exchange(ctx, s.client, code, s.redirect())
if err != nil {
return back(url.Values{"onenoteError": {err.Error()}})
}
conn := &connection{user: st.User, token: tok, refresh: tok.RefreshToken, expires: time.Now().Add(connectionTTL)}
var me struct {
Mail string `json:"mail"`
UserPrincipalName string `json:"userPrincipalName"`
}
if err := s.get(ctx, conn, s.graph+"/me?$select=mail,userPrincipalName", &me); err == nil {
conn.email = me.Mail
if conn.email == "" {
conn.email = me.UserPrincipalName
}
}
id := newID()
s.mu.Lock()
s.sweepLocked()
s.conns[id] = conn
s.mu.Unlock()
return back(url.Values{"onenote": {id}})
}
func (s *Service) sweepLocked() {
now := time.Now()
for id, c := range s.conns {
if now.After(c.expires) {
delete(s.conns, id)
}
}
for id, j := range s.jobs {
if !j.ended.IsZero() && now.Sub(j.ended) > connectionTTL {
delete(s.jobs, id)
}
}
}
func (s *Service) connection(c access.Caller, id string) (*connection, error) {
s.mu.Lock()
defer s.mu.Unlock()
conn := s.conns[id]
if conn == nil || conn.user != c.ID || time.Now().After(conn.expires) {
return nil, apperr.NotFound("the Microsoft sign-in has expired; connect again")
}
return conn, nil
}
// ---- Graph -------------------------------------------------------------------------
var errThrottled = errors.New("the Microsoft Graph API is busy; try again later")
// do sends one Graph request, refreshing the token and waiting out
// throttling. A nil out returns the body.
func (s *Service) do(ctx context.Context, conn *connection, u string, out any) ([]byte, error) {
for attempt := 0; ; attempt++ {
if time.Now().After(conn.token.Expires) && conn.refresh != "" {
tok, err := s.o.Provider.Refresh(ctx, s.client, conn.refresh, scopes)
if err != nil {
return nil, err
}
conn.token, conn.refresh = tok, tok.RefreshToken
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+conn.token.AccessToken)
res, err := s.client.Do(req)
if err != nil {
return nil, fmt.Errorf("the Microsoft Graph API did not answer: %w", err)
}
if res.StatusCode == http.StatusTooManyRequests || res.StatusCode == http.StatusServiceUnavailable {
_ = res.Body.Close()
if attempt >= 5 {
return nil, errThrottled
}
wait := time.Duration(1<<attempt) * time.Second
if sec, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && sec > 0 {
wait = time.Duration(min(sec, 60)) * time.Second
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(wait):
}
continue
}
body, err := io.ReadAll(io.LimitReader(res.Body, maxResource+1))
_ = res.Body.Close()
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
var e struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
_ = json.Unmarshal(body, &e)
if e.Error.Message == "" {
e.Error.Message = res.Status
}
return nil, fmt.Errorf("the Microsoft Graph API answered: %s", e.Error.Message)
}
if len(body) > maxResource {
return nil, errors.New("a file in the notebook is larger than 50 MB")
}
if out != nil {
return body, json.Unmarshal(body, out)
}
return body, nil
}
}
func (s *Service) get(ctx context.Context, conn *connection, u string, out any) error {
_, err := s.do(ctx, conn, u, out)
return err
}
// list reads every page of a Graph collection.
func list[T any](ctx context.Context, s *Service, conn *connection, u string) ([]T, error) {
var all []T
for u != "" && len(all) < 10000 {
var res struct {
Value []T `json:"value"`
Next string `json:"@odata.nextLink"`
}
if err := s.get(ctx, conn, u, &res); err != nil {
return nil, err
}
all = append(all, res.Value...)
u = res.Next
if u != "" && !strings.HasPrefix(u, s.graph) {
break // Never follow a link off Graph with the token.
}
}
return all, nil
}
// Notebooks lists the notebooks of the signed-in Microsoft account.
func (s *Service) Notebooks(ctx context.Context, c access.Caller, connID string) ([]Notebook, error) {
conn, err := s.connection(c, connID)
if err != nil {
return nil, err
}
type nb struct {
ID string `json:"id"`
Name string `json:"displayName"`
Modified string `json:"lastModifiedDateTime"`
}
rows, err := list[nb](ctx, s, conn, s.graph+"/me/onenote/notebooks?$select=id,displayName,lastModifiedDateTime&$orderby=displayName")
if err != nil {
return nil, apperr.Invalid(err.Error())
}
out := make([]Notebook, len(rows))
for i, r := range rows {
out[i] = Notebook(r)
}
return out, nil
}
// Account is the Microsoft account a connection signed in as.
func (s *Service) Account(c access.Caller, connID string) (string, error) {
conn, err := s.connection(c, connID)
if err != nil {
return "", err
}
return conn.email, nil
}
// ---- Import ------------------------------------------------------------------------
// Import starts importing a notebook under parent in space.
func (s *Service) Import(ctx context.Context, c access.Caller, connID, notebook, space, parent string) (Job, error) {
conn, err := s.connection(c, connID)
if err != nil {
return Job{}, err
}
if notebook == "" || strings.ContainsAny(notebook, "/?#") {
return Job{}, apperr.InvalidFields(map[string]string{"notebook": "Choose a notebook."})
}
job := &Job{ID: newID(), Notebook: notebook, Status: "running", user: c.ID, Created: []directory.Page{}}
s.mu.Lock()
s.jobs[job.ID] = job
s.mu.Unlock()
go func() {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Hour)
defer cancel()
pages, assets, err := s.read(ctx, conn, notebook, func(n int) {
s.mu.Lock()
job.Pages = n
s.mu.Unlock()
})
var created []directory.Page
if err == nil {
created, err = s.dir.ImportConverted(ctx, c, space, parent, pages, assets)
}
s.mu.Lock()
defer s.mu.Unlock()
job.ended = time.Now()
if err != nil {
slog.Warn("onenote import failed", "notebook", notebook, "err", err)
job.Status, job.Error = "failed", err.Error()
if e, ok := apperr.As(err); ok && len(e.Fields) > 0 {
for _, v := range e.Fields {
job.Error = v
}
}
return
}
job.Status, job.Created = "done", created
}()
return s.view(job), nil
}
func (s *Service) view(j *Job) Job {
v := *j
v.Created = append([]directory.Page{}, j.Created...)
return v
}
// JobStatus reports an import the caller started.
func (s *Service) JobStatus(c access.Caller, id string) (Job, error) {
s.mu.Lock()
defer s.mu.Unlock()
j := s.jobs[id]
if j == nil || j.user != c.ID {
return Job{}, apperr.NotFound("import not found")
}
return s.view(j), nil
}
type graphPage struct {
ID string `json:"id"`
Title string `json:"title"`
Level int `json:"level"`
Order float64 `json:"order"`
}
type graphNamed struct {
ID string `json:"id"`
Name string `json:"displayName"`
}
// read turns a notebook into pages and the files they use.
func (s *Service) read(ctx context.Context, conn *connection, notebook string, progress func(int)) ([]convert.NotionPage, []convert.Asset, error) {
var nb graphNamed
if err := s.get(ctx, conn, s.graph+"/me/onenote/notebooks/"+url.PathEscape(notebook)+"?$select=id,displayName", &nb); err != nil {
return nil, nil, err
}
r := &reader{s: s, conn: conn, ctx: ctx, progress: progress, assetAt: map[string]string{}, names: map[string]string{}}
root := r.add(convert.NotionPage{Title: nb.Name, Parent: -1, Doc: emptyDoc()})
if err := r.container(root, "/me/onenote/notebooks/"+url.PathEscape(notebook), 0); err != nil {
return nil, nil, err
}
return r.pages, r.assets, nil
}
func emptyDoc() convert.Node {
return convert.Node{Type: "doc", Content: []convert.Node{{Type: "paragraph"}}}
}
type reader struct {
s *Service
conn *connection
ctx context.Context
progress func(int)
pages []convert.NotionPage
assets []convert.Asset
assetAt map[string]string
names map[string]string // resource URL -> attached file's name
size int64
read int
}
func (r *reader) add(p convert.NotionPage) int {
r.pages = append(r.pages, p)
return len(r.pages) - 1
}
// container reads a notebook's or section group's section groups and sections.
func (r *reader) container(parent int, path string, depth int) error {
if depth > 10 {
return nil
}
groups, err := list[graphNamed](r.ctx, r.s, r.conn, r.s.graph+path+"/sectionGroups?$select=id,displayName")
if err != nil {
return err
}
sections, err := list[graphNamed](r.ctx, r.s, r.conn, r.s.graph+path+"/sections?$select=id,displayName")
if err != nil {
return err
}
for _, sec := range sections {
at := r.add(convert.NotionPage{Title: sec.Name, Parent: parent, Doc: emptyDoc()})
if err := r.section(at, sec.ID); err != nil {
return err
}
}
for _, g := range groups {
at := r.add(convert.NotionPage{Title: g.Name, Parent: parent, Doc: emptyDoc()})
if err := r.container(at, "/me/onenote/sectionGroups/"+url.PathEscape(g.ID), depth+1); err != nil {
return err
}
}
return nil
}
// section reads a section's pages in their order; a subpage goes under the
// page before it one level up.
func (r *reader) section(parent int, id string) error {
pages, err := list[graphPage](r.ctx, r.s, r.conn, r.s.graph+"/me/onenote/sections/"+url.PathEscape(id)+"/pages?pagelevel=true&$select=id,title&$top=100")
if err != nil {
return err
}
sort.SliceStable(pages, func(i, j int) bool { return pages[i].Order < pages[j].Order })
var stack []int // the last page read at each level
for _, p := range pages {
if len(r.pages) >= maxPages {
return fmt.Errorf("the notebook has more than %d pages; import fewer", maxPages)
}
under := parent
level := max(0, min(p.Level, len(stack)))
if level > 0 {
under = stack[level-1]
}
doc, err := r.content(p.ID)
if err != nil {
return fmt.Errorf("%q: %w", p.Title, err)
}
title, body := convert.Title(doc)
if strings.TrimSpace(p.Title) != "" {
title = p.Title
}
if strings.TrimSpace(title) == "" {
title = "Untitled"
}
if len(body.Content) == 0 {
body = emptyDoc()
}
at := r.add(convert.NotionPage{Title: strings.TrimSpace(title), Parent: under, Doc: body})
stack = append(stack[:level], at)
r.read++
r.progress(r.read)
}
return nil
}
// object turns OneNote's attached files into links, which import keeps.
var object = regexp.MustCompile(`(?is)<object\b[^>]*>.*?</object>|<object\b[^>]*/>`)
var attr = regexp.MustCompile(`(?i)\b(data-attachment|data)\s*=\s*"([^"]*)"`)
// content reads one page's HTML as a document, with its files as assets.
func (r *reader) content(id string) (convert.Node, error) {
raw, err := r.s.do(r.ctx, r.conn, r.s.graph+"/me/onenote/pages/"+url.PathEscape(id)+"/content", nil)
if err != nil {
return convert.Node{}, err
}
html := object.ReplaceAllStringFunc(string(raw), func(tag string) string {
var name, data string
for _, m := range attr.FindAllStringSubmatch(tag, -1) {
if strings.EqualFold(m[1], "data-attachment") {
name = m[2]
} else {
data = m[2]
}
}
if data == "" {
return ""
}
if name == "" {
name = "Attachment"
} else {
r.names[strings.ReplaceAll(data, "&amp;", "&")] = name
}
return `<p><a href="` + data + `">` + name + `</a></p>`
})
var fail error
doc, err := convert.FromHTMLWith(html, convert.ImportOptions{Resolve: func(u string) (string, bool) {
u = strings.ReplaceAll(u, "&amp;", "&")
if !strings.HasPrefix(u, r.s.graph+"/") {
return "", false
}
if ref, ok := r.assetAt[u]; ok {
return ref, true
}
data, err := r.s.do(r.ctx, r.conn, u, nil)
if err != nil {
if fail == nil {
fail = err
}
return "", true
}
if r.size += int64(len(data)); r.size > maxResources {
fail = errors.New("the notebook's files add up to more than 512 MB")
return "", true
}
ref := convert.AssetRef(len(r.assets))
name := r.names[u]
if name == "" {
name = resourceName(u, len(r.assets), data)
}
r.assets = append(r.assets, convert.Asset{Ref: ref, Name: name, Data: data})
r.assetAt[u] = ref
return ref, true
}})
if fail != nil {
return convert.Node{}, fail
}
return doc, err
}
// resourceName names a OneNote picture: Graph gives none, so its id is
// used, with the extension of the type its bytes show.
func resourceName(u string, n int, data []byte) string {
ext := ""
if exts, _ := mime.ExtensionsByType(strings.SplitN(http.DetectContentType(data), ";", 2)[0]); len(exts) > 0 {
ext = exts[0]
for _, e := range exts {
if e == ".png" || e == ".jpg" || e == ".gif" || e == ".pdf" {
ext = e
}
}
}
if i := strings.Index(u, "/resources/"); i >= 0 {
id := strings.TrimSuffix(u[i+len("/resources/"):], "/$value")
if j := strings.IndexAny(id, "/?!"); j >= 0 {
id = id[:j]
}
if id != "" && len(id) < 120 {
return "onenote-" + id + ext
}
}
return fmt.Sprintf("onenote-file-%d%s", n+1, ext)
}