Link previews: link cards for GitHub issues, pull requests and repositories, Linear issues and Figma files are read through the services' APIs and show a status pill (Open, Merged, In Progress…) and a line of details. Public items need nothing; a workspace's tokens, set by its admins under Workspace settings → Integrations and checked with each service before being sealed, reach private ones and Linear. GET /link-preview takes the workspace; the link card stores kind, status, state and meta. Slack: each workspace connects its own Slack app, made from a manifest the settings page fills in. Docwell posts chosen page and comment events to a channel (edits at most every 30 minutes per page), previews links to Docwell pages posted in Slack, and answers /docwell with a search as the member whose email matches the Slack user, shown only to them. Only pages every member can open are posted or previewed. Requests from Slack are signature-checked; the webhook dispatcher gained listeners so Slack follows the same events. Confluence: a space's HTML export imports with its page tree (from index.html, else breadcrumbs), links between pages, pictures and attachments. Panels become callouts, code macros code blocks with their language, expand macros toggles, task lists to-dos. New collection workspace_integrations (schema snapshot regenerated), OpenAPI and generated Go, TypeScript and Dart types, strings in all five languages, the user guide, and a rebuilt mobile editor bundle. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
364 lines
11 KiB
Go
364 lines
11 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package unfurl
|
|
|
|
// Rich previews: a few services describe their links better through their
|
|
// APIs than through the page's meta tags (which, for private items, are a
|
|
// sign-in page). GitHub issues, pull requests and repositories, Linear issues
|
|
// and Figma files get a status and a line of details. A workspace's tokens
|
|
// reach private items; without them only public data is read, and Linear
|
|
// (which has no public API) falls back to the page itself.
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Tokens are a workspace's keys for the services; each may be empty.
|
|
type Tokens struct {
|
|
GitHub string
|
|
Linear string
|
|
Figma string
|
|
}
|
|
|
|
// APIs are the services' addresses (tests point them at a local server).
|
|
type APIs struct {
|
|
GitHub string // https://api.github.com
|
|
Linear string // https://api.linear.app
|
|
Figma string // https://api.figma.com
|
|
FigmaWeb string // https://www.figma.com (oEmbed for public files)
|
|
}
|
|
|
|
// DefaultAPIs are the services' real addresses.
|
|
var DefaultAPIs = APIs{
|
|
GitHub: "https://api.github.com",
|
|
Linear: "https://api.linear.app",
|
|
Figma: "https://api.figma.com",
|
|
FigmaWeb: "https://www.figma.com",
|
|
}
|
|
|
|
// Kinds of rich preview.
|
|
const (
|
|
KindGitHubIssue = "github.issue"
|
|
KindGitHubPull = "github.pull"
|
|
KindGitHubRepo = "github.repo"
|
|
KindLinearIssue = "linear.issue"
|
|
KindFigmaFile = "figma.file"
|
|
)
|
|
|
|
// WithAPIs returns a copy of f that calls apis instead of the real services.
|
|
func (f *Fetcher) WithAPIs(apis APIs) *Fetcher {
|
|
c := *f
|
|
c.apis = &apis
|
|
return &c
|
|
}
|
|
|
|
func (f *Fetcher) api() APIs {
|
|
if f.apis != nil {
|
|
return *f.apis
|
|
}
|
|
return DefaultAPIs
|
|
}
|
|
|
|
var (
|
|
githubItem = regexp.MustCompile(`^/([\w.-]+)/([\w.-]+)/(issues|pull)/(\d+)(?:/.*)?$`)
|
|
githubRepo = regexp.MustCompile(`^/([\w.-]+)/([\w.-]+)/?$`)
|
|
linearItem = regexp.MustCompile(`^/[\w-]+/issue/([A-Za-z][A-Za-z0-9]*-\d+)(?:/.*)?$`)
|
|
figmaFile = regexp.MustCompile(`^/(file|design|proto|board|slides|deck)/([A-Za-z0-9]{10,})(?:/.*)?$`)
|
|
)
|
|
|
|
// GitHub paths that look like a repository but are pages of the site.
|
|
var githubReserved = map[string]bool{
|
|
"settings": true, "orgs": true, "marketplace": true, "explore": true, "topics": true, "notifications": true,
|
|
"login": true, "join": true, "features": true, "pricing": true, "sponsors": true, "about": true, "search": true,
|
|
"pulls": true, "issues": true, "new": true, "organizations": true, "apps": true, "collections": true, "trending": true,
|
|
}
|
|
|
|
// rich returns the service's preview of u; ok is false when u is not one of
|
|
// theirs or the service could not describe it.
|
|
func (f *Fetcher) rich(ctx context.Context, u *url.URL, t Tokens) (Preview, bool) {
|
|
host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
|
|
switch host {
|
|
case "github.com":
|
|
if m := githubItem.FindStringSubmatch(u.Path); m != nil {
|
|
return f.githubItem(ctx, u, t.GitHub, m[1], m[2], m[4])
|
|
}
|
|
if m := githubRepo.FindStringSubmatch(u.Path); m != nil && !githubReserved[strings.ToLower(m[1])] {
|
|
return f.githubRepo(ctx, u, t.GitHub, m[1], m[2])
|
|
}
|
|
case "linear.app":
|
|
if m := linearItem.FindStringSubmatch(u.Path); m != nil && t.Linear != "" {
|
|
return f.linearIssue(ctx, u, t.Linear, strings.ToUpper(m[1]))
|
|
}
|
|
case "figma.com":
|
|
if m := figmaFile.FindStringSubmatch(u.Path); m != nil {
|
|
return f.figmaFile(ctx, u, t.Figma, m[2])
|
|
}
|
|
}
|
|
return Preview{}, false
|
|
}
|
|
|
|
// getJSON reads a JSON answer into out; ok is false for anything but 200.
|
|
func (f *Fetcher) getJSON(req *http.Request, out any) bool {
|
|
req.Header.Set("Accept", "application/json")
|
|
req.Header.Set("User-Agent", "DocwellLinkPreview/1.0 (+https://docwell.app)")
|
|
res, err := f.client.Do(req)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
defer func() { _ = res.Body.Close() }()
|
|
if res.StatusCode != http.StatusOK {
|
|
return false
|
|
}
|
|
return json.NewDecoder(io.LimitReader(res.Body, maxBody)).Decode(out) == nil
|
|
}
|
|
|
|
func (f *Fetcher) github(ctx context.Context, token, path string, out any) bool {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(f.api().GitHub, "/")+path, nil)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
|
|
if token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
return f.getJSON(req, out)
|
|
}
|
|
|
|
func (f *Fetcher) githubItem(ctx context.Context, u *url.URL, token, owner, repo, num string) (Preview, bool) {
|
|
var it struct {
|
|
Title string `json:"title"`
|
|
Body string `json:"body"`
|
|
State string `json:"state"`
|
|
StateReason string `json:"state_reason"`
|
|
Draft bool `json:"draft"`
|
|
Comments int `json:"comments"`
|
|
User struct {
|
|
Login string `json:"login"`
|
|
AvatarURL string `json:"avatar_url"`
|
|
} `json:"user"`
|
|
PullRequest *struct {
|
|
MergedAt *string `json:"merged_at"`
|
|
} `json:"pull_request"`
|
|
}
|
|
if !f.github(ctx, token, fmt.Sprintf("/repos/%s/%s/issues/%s", url.PathEscape(owner), url.PathEscape(repo), num), &it) {
|
|
return Preview{}, false
|
|
}
|
|
p := Preview{URL: u.String(), Site: "GitHub", Title: clip(it.Title, 300), Description: clip(plainText(it.Body), 300)}
|
|
p.Kind = KindGitHubIssue
|
|
switch {
|
|
case it.PullRequest != nil && it.PullRequest.MergedAt != nil:
|
|
p.State, p.Status = "merged", "Merged"
|
|
case it.State == "closed" && it.StateReason == "not_planned":
|
|
p.State, p.Status = "canceled", "Closed"
|
|
case it.State == "closed":
|
|
p.State, p.Status = "closed", "Closed"
|
|
case it.Draft:
|
|
p.State, p.Status = "draft", "Draft"
|
|
default:
|
|
p.State, p.Status = "open", "Open"
|
|
}
|
|
if it.PullRequest != nil {
|
|
p.Kind = KindGitHubPull
|
|
}
|
|
meta := []string{fmt.Sprintf("%s/%s #%s", owner, repo, num)}
|
|
if it.User.Login != "" {
|
|
meta = append(meta, it.User.Login)
|
|
}
|
|
if it.Comments > 0 {
|
|
meta = append(meta, fmt.Sprintf("💬 %d", it.Comments))
|
|
}
|
|
p.Meta = strings.Join(meta, " · ")
|
|
p.Image = safeImage(it.User.AvatarURL)
|
|
return p, true
|
|
}
|
|
|
|
func (f *Fetcher) githubRepo(ctx context.Context, u *url.URL, token, owner, repo string) (Preview, bool) {
|
|
var r struct {
|
|
FullName string `json:"full_name"`
|
|
Description string `json:"description"`
|
|
Stars int `json:"stargazers_count"`
|
|
Language string `json:"language"`
|
|
Archived bool `json:"archived"`
|
|
Private bool `json:"private"`
|
|
Owner struct {
|
|
AvatarURL string `json:"avatar_url"`
|
|
} `json:"owner"`
|
|
}
|
|
if !f.github(ctx, token, fmt.Sprintf("/repos/%s/%s", url.PathEscape(owner), url.PathEscape(repo)), &r) || r.FullName == "" {
|
|
return Preview{}, false
|
|
}
|
|
p := Preview{URL: u.String(), Site: "GitHub", Title: clip(r.FullName, 300), Description: clip(r.Description, 300), Kind: KindGitHubRepo}
|
|
meta := []string{"★ " + shortCount(r.Stars)}
|
|
if r.Language != "" {
|
|
meta = append(meta, r.Language)
|
|
}
|
|
p.Meta = strings.Join(meta, " · ")
|
|
switch {
|
|
case r.Archived:
|
|
p.State, p.Status = "closed", "Archived"
|
|
case r.Private:
|
|
p.State, p.Status = "draft", "Private"
|
|
}
|
|
p.Image = safeImage(r.Owner.AvatarURL)
|
|
return p, true
|
|
}
|
|
|
|
func (f *Fetcher) linearIssue(ctx context.Context, u *url.URL, key, id string) (Preview, bool) {
|
|
body, _ := json.Marshal(map[string]any{
|
|
"query": `query($id: String!) { issue(id: $id) { identifier title description priorityLabel state { name type } assignee { name } team { name } } }`,
|
|
"variables": map[string]string{"id": id},
|
|
})
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(f.api().Linear, "/")+"/graphql", bytes.NewReader(body))
|
|
if err != nil {
|
|
return Preview{}, false
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", key)
|
|
var out struct {
|
|
Data struct {
|
|
Issue *struct {
|
|
Identifier string `json:"identifier"`
|
|
Title string `json:"title"`
|
|
Description string `json:"description"`
|
|
PriorityLabel string `json:"priorityLabel"`
|
|
State struct {
|
|
Name string `json:"name"`
|
|
Type string `json:"type"`
|
|
} `json:"state"`
|
|
Assignee *struct {
|
|
Name string `json:"name"`
|
|
} `json:"assignee"`
|
|
Team struct {
|
|
Name string `json:"name"`
|
|
} `json:"team"`
|
|
} `json:"issue"`
|
|
} `json:"data"`
|
|
}
|
|
if !f.getJSON(req, &out) || out.Data.Issue == nil {
|
|
return Preview{}, false
|
|
}
|
|
is := out.Data.Issue
|
|
p := Preview{URL: u.String(), Site: "Linear", Title: clip(is.Title, 300), Description: clip(plainText(is.Description), 300), Kind: KindLinearIssue}
|
|
p.Status = clip(is.State.Name, 40)
|
|
p.State = linearState(is.State.Type)
|
|
meta := []string{is.Identifier}
|
|
if is.Team.Name != "" {
|
|
meta = append(meta, is.Team.Name)
|
|
}
|
|
if is.Assignee != nil && is.Assignee.Name != "" {
|
|
meta = append(meta, is.Assignee.Name)
|
|
}
|
|
if is.PriorityLabel != "" && is.PriorityLabel != "No priority" {
|
|
meta = append(meta, is.PriorityLabel)
|
|
}
|
|
p.Meta = clip(strings.Join(meta, " · "), 200)
|
|
return p, true
|
|
}
|
|
|
|
// linearState maps Linear's workflow state types onto the preview's states.
|
|
func linearState(t string) string {
|
|
switch t {
|
|
case "started":
|
|
return "started"
|
|
case "completed":
|
|
return "done"
|
|
case "canceled":
|
|
return "canceled"
|
|
case "backlog", "triage":
|
|
return "draft"
|
|
default:
|
|
return "open"
|
|
}
|
|
}
|
|
|
|
func (f *Fetcher) figmaFile(ctx context.Context, u *url.URL, token, key string) (Preview, bool) {
|
|
p := Preview{URL: u.String(), Site: "Figma", Kind: KindFigmaFile}
|
|
if token != "" {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(f.api().Figma, "/")+"/v1/files/"+url.PathEscape(key)+"?depth=1", nil)
|
|
if err == nil {
|
|
req.Header.Set("X-Figma-Token", token)
|
|
var file struct {
|
|
Name string `json:"name"`
|
|
ThumbnailURL string `json:"thumbnailUrl"`
|
|
LastModified string `json:"lastModified"`
|
|
EditorType string `json:"editorType"`
|
|
}
|
|
if f.getJSON(req, &file) && file.Name != "" {
|
|
p.Title = clip(file.Name, 300)
|
|
p.Image = safeImage(file.ThumbnailURL)
|
|
p.Meta = figmaMeta(file.EditorType, file.LastModified)
|
|
return p, true
|
|
}
|
|
}
|
|
}
|
|
// Public files describe themselves through oEmbed.
|
|
q := url.Values{"url": {u.String()}}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(f.api().FigmaWeb, "/")+"/api/oembed?"+q.Encode(), nil)
|
|
if err != nil {
|
|
return Preview{}, false
|
|
}
|
|
var oe struct {
|
|
Title string `json:"title"`
|
|
ThumbnailURL string `json:"thumbnail_url"`
|
|
}
|
|
if !f.getJSON(req, &oe) || oe.Title == "" {
|
|
return Preview{}, false
|
|
}
|
|
p.Title = clip(oe.Title, 300)
|
|
p.Image = safeImage(oe.ThumbnailURL)
|
|
p.Meta = figmaMeta("", "")
|
|
return p, true
|
|
}
|
|
|
|
func figmaMeta(editor, modified string) string {
|
|
kind := "Figma design"
|
|
switch editor {
|
|
case "figjam":
|
|
kind = "FigJam board"
|
|
case "slides":
|
|
kind = "Figma Slides"
|
|
}
|
|
if t, err := time.Parse(time.RFC3339, modified); err == nil {
|
|
return kind + " · " + t.UTC().Format("2006-01-02")
|
|
}
|
|
return kind
|
|
}
|
|
|
|
// safeImage keeps an https picture address and drops anything else.
|
|
func safeImage(s string) string {
|
|
u, err := url.Parse(s)
|
|
if err != nil || u.Scheme != "https" || u.Host == "" || len(s) > 2000 {
|
|
return ""
|
|
}
|
|
return s
|
|
}
|
|
|
|
// markup is what plainText strips from Markdown bodies.
|
|
var markup = regexp.MustCompile("(?m)^#+\\s*|[*_`>]+|!?\\[([^\\]]*)\\]\\([^)]*\\)|<[^>]+>")
|
|
|
|
// plainText is the start of a Markdown body as one line of text.
|
|
func plainText(md string) string {
|
|
return markup.ReplaceAllString(md, "$1")
|
|
}
|
|
|
|
// shortCount writes 1234 as 1.2k.
|
|
func shortCount(n int) string {
|
|
switch {
|
|
case n >= 1_000_000:
|
|
return strconv.FormatFloat(float64(n)/1e6, 'f', 1, 64) + "M"
|
|
case n >= 1000:
|
|
return strconv.FormatFloat(float64(n)/1e3, 'f', 1, 64) + "k"
|
|
}
|
|
return strconv.Itoa(n)
|
|
}
|