// SPDX-License-Identifier: AGPL-3.0-or-later package directory import ( "context" "encoding/json" "fmt" "net/url" "regexp" "sort" "strings" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/store/pocketbase" ) // ---- Links between pages and templates ------------------------------------- // // A page links to another with an ordinary link to /p/ (the editor's "[[" // picker inserts those). pages.links keeps the ids a page links to, so the // pages linking to one ("backlinks") are a single query. var pagePath = regexp.MustCompile(`^/p/([A-Za-z0-9_-]{1,64})/?$`) // linkedPageID is the page id a link href points at, or "". Relative links // and absolute ones to any host count: documents move between addresses. func linkedPageID(href string) string { u, err := url.Parse(strings.TrimSpace(href)) if err != nil { return "" } if m := pagePath.FindStringSubmatch(u.Path); m != nil && validID(m[1]) { return m[1] } return "" } // linkIDs collects the pages a Tiptap document links to, except self. func linkIDs(doc json.RawMessage, self string) []string { var root any if json.Unmarshal(doc, &root) != nil { return []string{} } seen := map[string]bool{self: true} out := []string{} var walk func(n any) walk = func(n any) { m, ok := n.(map[string]any) if !ok { return } if marks, ok := m["marks"].([]any); ok { for _, mk := range marks { mm, _ := mk.(map[string]any) if mm["type"] != "link" { continue } attrs, _ := mm["attrs"].(map[string]any) href, _ := attrs["href"].(string) if id := linkedPageID(href); id != "" && !seen[id] { seen[id] = true out = append(out, id) } } } if kids, ok := m["content"].([]any); ok { for _, k := range kids { walk(k) } } } walk(root) sort.Strings(out) return out } // Backlinks lists the pages c can open that link to a page (viewer). func (s *Service) Backlinks(ctx context.Context, c access.Caller, pageID string) ([]PageItem, error) { p, _, err := s.pageFor(ctx, c, pageID) if err != nil { return nil, err } // links ~ matches inside the JSON text; the id check below drops near misses. rows, err := listAll[struct { pageRecord Links []string `json:"links"` }](ctx, s, "pages", pocketbase.ListOptions{ Filter: fmt.Sprintf("workspace = '%s' && deleted_at = '' && links ~ '\"%s\"'", p.Workspace, p.ID), Fields: pageFields + ",links", Sort: "title", }) if err != nil { return nil, err } out := []PageItem{} spaces := map[string]*spaceView{} for _, r := range rows { links := false for _, id := range r.Links { links = links || id == p.ID } if !links { continue } sp, seen := spaces[r.Space] if !seen { if a, rules, err := s.spaceRules(ctx, c, r.Space); err == nil { sp = &spaceView{name: a.space.Name, rules: rules} } spaces[r.Space] = sp } if sp == nil || sp.rules.role(r.ID) == "" { continue } out = append(out, PageItem{ID: r.ID, Title: r.Title, Icon: r.Icon, Space: r.Space, SpaceName: sp.name, At: r.Updated}) } return out, nil } // BackfillLinks works out pages.links for pages that do not have it yet // (pages from before link tracking). It is a background job. func (s *Service) BackfillLinks(ctx context.Context) error { for { res, err := pocketbase.List[struct { ID string `json:"id"` ContentJSON json.RawMessage `json:"content_json"` }](ctx, s.pb, "pages", pocketbase.ListOptions{PerPage: 200, Filter: "links = null", Fields: "id,content_json"}) if err != nil { return err } if len(res.Items) == 0 { return nil } for _, r := range res.Items { if _, err := pocketbase.Update[struct{}](ctx, s.pb, "pages", r.ID, map[string]any{"links": linkIDs(r.ContentJSON, r.ID)}); err != nil { return err } } } } // ---- Templates ------------------------------------------------------------- // Template is a page marked as a template, offered when filling a new page. type Template struct { ID string `json:"id"` Title string `json:"title"` Icon string `json:"icon"` Space string `json:"space"` SpaceName string `json:"spaceName"` } // ListTemplates lists the template pages of a workspace that c can open. func (s *Service) ListTemplates(ctx context.Context, c access.Caller, wsID string) ([]Template, error) { ws, _, err := s.workspaceFor(ctx, c, wsID) if err != nil { return nil, err } rows, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{ Filter: fmt.Sprintf("workspace = '%s' && is_template = true && deleted_at = ''", ws.ID), Fields: pageFields, Sort: "title", }) if err != nil { return nil, err } out := []Template{} spaces := map[string]*spaceView{} for _, r := range rows { sp, seen := spaces[r.Space] if !seen { if a, rules, err := s.spaceRules(ctx, c, r.Space); err == nil { sp = &spaceView{name: a.space.Name, rules: rules} } spaces[r.Space] = sp } if sp == nil || sp.rules.role(r.ID) == "" { continue } out = append(out, Template{ID: r.ID, Title: r.Title, Icon: r.Icon, Space: r.Space, SpaceName: sp.name}) } return out, nil } type spaceView struct { name string rules pageRules } // ApplyTemplate replaces a page's content with a template's (editor of the // page, viewer of the template, same workspace). An untitled page also takes // the template's title and icon. The change is a history version, so it can // be undone by restoring. func (s *Service) ApplyTemplate(ctx context.Context, c access.Caller, pageID, templateID string) (Page, error) { p, a, err := s.pageFor(ctx, c, pageID) if err != nil { return Page{}, err } if err := access.EditPages(a.role); err != nil { return Page{}, err } if p.DeletedAt != "" { return Page{}, apperr.Invalid("restore the page from the trash first") } t, _, err := s.pageFor(ctx, c, templateID) if err != nil || t.Workspace != p.Workspace || t.DeletedAt != "" { return Page{}, apperr.InvalidFields(map[string]string{"template": "Template not found."}) } doc, err := s.docs.Content(ctx, t.ID) if err != nil { return Page{}, err } if !isDoc(doc) { doc = json.RawMessage(`{"type":"doc","content":[{"type":"paragraph"}]}`) } if err := s.docs.Replace(ctx, p.ID, c.ID, doc, "template"); err != nil { return Page{}, err } if strings.TrimSpace(p.Title) == "" { if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{ "title": t.Title, "icon": t.Icon, "last_editor": c.ID, }); err != nil { return Page{}, mapPB(err, "page not found") } } return s.GetPage(ctx, c, p.ID) }