LinkedIn: - The API version was fixed at 202501, retired by LinkedIn (426 NONEXISTENT_VERSION). It's now the month before last, stepping back a month (up to four) if LinkedIn says a version isn't active. - The versioned Posts API needs a title for a link's article card (422). Supermarket reads the linked page's title and description and sends them, falling back to the page's address as the title. Tested for real: a post with a link went out to the member's profile. Inbox is now Posts: the menu, page, messages and docs; the page moves to /posts, and /inbox redirects there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
368 lines
9.8 KiB
Go
368 lines
9.8 KiB
Go
package web
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"supermarket/internal/ai"
|
|
"supermarket/internal/bridge"
|
|
"supermarket/internal/content"
|
|
"supermarket/internal/core"
|
|
"supermarket/internal/inventory"
|
|
"supermarket/internal/profile"
|
|
"supermarket/internal/secrets"
|
|
)
|
|
|
|
// Connection is a social account the user signed in to.
|
|
type Connection struct {
|
|
Account string `json:"account"`
|
|
At time.Time `json:"at"`
|
|
// Expires is when the sign-in stops working, for networks whose tokens
|
|
// can't be renewed (LinkedIn); zero for ones Supermarket renews itself.
|
|
Expires time.Time `json:"expires,omitempty"`
|
|
}
|
|
|
|
// linkedInTokenLife is how long LinkedIn's access tokens last, for
|
|
// sign-ins saved before the expiry was recorded.
|
|
const linkedInTokenLife = 60 * 24 * time.Hour
|
|
|
|
// expiryWarning is how long before a sign-in expires the reminders start.
|
|
const expiryWarning = 14 * 24 * time.Hour
|
|
|
|
// Expiry is when a sign-in runs out, if it does.
|
|
type Expiry struct {
|
|
Network string // e.g. LinkedIn
|
|
At time.Time
|
|
}
|
|
|
|
// Expired reports whether it has run out.
|
|
func (e Expiry) Expired() bool { return !time.Now().Before(e.At) }
|
|
|
|
// Soon reports whether it runs out within expiryWarning (or has).
|
|
func (e Expiry) Soon() bool { return time.Until(e.At) < expiryWarning }
|
|
|
|
// Days is how many whole days are left (0 on the last day).
|
|
func (e Expiry) Days() int { return int(time.Until(e.At) / (24 * time.Hour)) }
|
|
|
|
// linkedInExpiry is when the LinkedIn sign-in runs out, or nil if LinkedIn
|
|
// isn't connected.
|
|
func (s *Server) linkedInExpiry() *Expiry {
|
|
if !s.Secrets.Has(secrets.LinkedInAccessToken) {
|
|
return nil
|
|
}
|
|
c := s.connections()["linkedin"]
|
|
at := c.Expires
|
|
if at.IsZero() {
|
|
if c.At.IsZero() {
|
|
return nil // a token from the old app: when it was made is unknown
|
|
}
|
|
at = c.At.Add(linkedInTokenLife)
|
|
}
|
|
return &Expiry{Network: "LinkedIn", At: at}
|
|
}
|
|
|
|
// reminders are the sign-ins running out soon, or already, for the
|
|
// Overview and Posts.
|
|
func (s *Server) reminders() []Expiry {
|
|
if e := s.linkedInExpiry(); e != nil && e.Soon() {
|
|
return []Expiry{*e}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
const connectionsKey = "connections"
|
|
|
|
func (s *Server) connections() map[string]Connection {
|
|
c := map[string]Connection{}
|
|
if _, err := s.DB.GetJSON(connectionsKey, &c); err != nil {
|
|
s.Log.Error("loading connections", "err", err)
|
|
}
|
|
return c
|
|
}
|
|
|
|
func (s *Server) saveConnection(provider string, c Connection) error {
|
|
all := s.connections()
|
|
all[provider] = c
|
|
return s.DB.PutJSON(connectionsKey, all)
|
|
}
|
|
|
|
type step struct {
|
|
Label string
|
|
Done bool
|
|
Detail string
|
|
Link string
|
|
}
|
|
|
|
func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
|
|
p, err := profile.Load(s.DB)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
entries, err := inventory.List(s.DB, "")
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
counts := map[string]int{}
|
|
for _, e := range entries {
|
|
counts[e.Relationship]++
|
|
}
|
|
aiCfg, err := ai.LoadConfig(s.DB)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
_, aiErr := ai.New(aiCfg, s.Secrets)
|
|
last, err := bridge.Last(s.DB)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
conns := s.connections()
|
|
|
|
steps := []step{
|
|
{Label: "AI provider", Done: aiErr == nil, Link: "/settings/ai",
|
|
Detail: ifElse(aiErr == nil, aiCfg.Provider+" · "+aiCfg.Model, "Choose Anthropic or a server on your network; the profile draft and posts need it")},
|
|
{Label: "Company profile", Done: p.IsSet(), Link: "/settings/profile",
|
|
Detail: ifElse(p.IsSet(), p.Name, "Describe the company, its products and its customers (the AI can draft it from your website)")},
|
|
{Label: "Inventory", Done: len(entries) > 0, Link: "/inventory",
|
|
Detail: inventorySummary(counts)},
|
|
{Label: "Social accounts", Done: s.Secrets.Has(secrets.XAccessToken) || s.Secrets.Has(secrets.LinkedInAccessToken) || s.Secrets.Has(secrets.RedditAccessToken),
|
|
Link: "/settings/accounts", Detail: s.connectionSummary(conns)},
|
|
{Label: "Federated Core", Done: s.Core != nil, Link: "/settings/core",
|
|
Detail: ifElse(s.Core != nil, coreDomain(s.Core), "No Core found; run `configure core` in CoreDesktop")},
|
|
{Label: "Hermes bridge", Done: last != nil, Link: "/settings/core",
|
|
Detail: ifElse(last != nil, "Last check-in "+ago(atOf(last)), "Hermes hasn't checked in yet")},
|
|
}
|
|
|
|
queued, _ := content.CountDrafts(s.DB)
|
|
scheduled, _ := content.ListDrafts(s.DB, 1000, content.StatusScheduled)
|
|
pending := false
|
|
for _, st := range steps {
|
|
pending = pending || !st.Done
|
|
}
|
|
|
|
s.render(w, r, "dashboard", page{Title: "Overview", Nav: "home", Data: map[string]any{
|
|
"Steps": steps,
|
|
"Modules": modules,
|
|
"ImportStatus": s.ImportStatus,
|
|
"ImportErr": errString(s.ImportErr),
|
|
"QueuedPosts": queued,
|
|
"Scheduled": len(scheduled),
|
|
"Reminders": s.reminders(),
|
|
"Pending": pending,
|
|
}})
|
|
}
|
|
|
|
func ifElse(cond bool, a, b string) string {
|
|
if cond {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
|
|
func errString(err error) string {
|
|
if err == nil {
|
|
return ""
|
|
}
|
|
return err.Error()
|
|
}
|
|
|
|
func atOf(c *bridge.Checkin) time.Time {
|
|
if c == nil {
|
|
return time.Time{}
|
|
}
|
|
return c.At
|
|
}
|
|
|
|
func coreDomain(c *core.Core) string {
|
|
if c == nil {
|
|
return ""
|
|
}
|
|
return c.Domain
|
|
}
|
|
|
|
func inventorySummary(c map[string]int) string {
|
|
if c[inventory.Partner]+c[inventory.Competitor]+c[inventory.Watch] == 0 {
|
|
return "Add the partners and competitors you post about"
|
|
}
|
|
return plural(c[inventory.Partner], "partner") + ", " + plural(c[inventory.Competitor], "competitor") + ", " + plural(c[inventory.Watch], "watched")
|
|
}
|
|
|
|
func (s *Server) connectionSummary(c map[string]Connection) string {
|
|
var parts []string
|
|
if a := c["x"].Account; a != "" {
|
|
parts = append(parts, "X @"+a)
|
|
} else if s.Secrets.Has(secrets.XAccessToken) {
|
|
parts = append(parts, "X")
|
|
}
|
|
if e := s.linkedInExpiry(); e != nil && e.Expired() {
|
|
parts = append(parts, "LinkedIn (expired)")
|
|
} else if s.Secrets.Has(secrets.LinkedInAccessToken) {
|
|
parts = append(parts, "LinkedIn")
|
|
}
|
|
if a := c["reddit"].Account; a != "" {
|
|
parts = append(parts, "Reddit u/"+a)
|
|
}
|
|
if len(parts) == 0 {
|
|
return "Connect X, LinkedIn or Reddit"
|
|
}
|
|
return strings.Join(parts, ", ")
|
|
}
|
|
|
|
func plural(n int, word string) string {
|
|
if word == "watched" {
|
|
return strconv.Itoa(n) + " watched"
|
|
}
|
|
if n == 1 {
|
|
return "1 " + word
|
|
}
|
|
return strconv.Itoa(n) + " " + word + "s"
|
|
}
|
|
|
|
// --- Core & Hermes ---
|
|
|
|
type coreData struct {
|
|
Core *core.Core
|
|
User string
|
|
HubURL string
|
|
MCPURL string
|
|
MCPSocket string
|
|
MCPToken string
|
|
Last *bridge.Checkin
|
|
Prompt string
|
|
HermesConfig string
|
|
HermesEnv string
|
|
}
|
|
|
|
func (s *Server) corePage(w http.ResponseWriter, r *http.Request) {
|
|
last, err := bridge.Last(s.DB)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
d := coreData{
|
|
Core: s.Core,
|
|
MCPURL: "http://127.0.0.1:" + publicPort(s.PublicURL) + "/mcp",
|
|
MCPToken: s.MCPToken,
|
|
MCPSocket: s.MCPSocket,
|
|
Last: last,
|
|
Prompt: bridge.CheckinPrompt,
|
|
}
|
|
hub := "https://mcphub.<your Core's domain>/sse?as_user=<your user name>"
|
|
if s.Core != nil {
|
|
d.User = s.Core.User()
|
|
hub = s.Core.MCPHubURL()
|
|
}
|
|
d.HubURL = hub
|
|
d.HermesConfig = `mcp_servers:
|
|
mcphub:
|
|
url: "` + hub + `"
|
|
transport: sse
|
|
headers:
|
|
Authorization: "Basic ${MCPHUB_AUTH}"
|
|
supermarket:
|
|
command: socat
|
|
args: ["STDIO", "UNIX-CONNECT:` + d.MCPSocket + `"]`
|
|
d.HermesEnv = `MCPHUB_AUTH=<your own hub token from your Core: the part after "Basic ">`
|
|
s.render(w, r, "core", page{Title: "Core & Hermes", Nav: "settings/core", Data: d})
|
|
}
|
|
|
|
func publicPort(u string) string {
|
|
if i := strings.LastIndex(u, ":"); i > strings.Index(u, "://")+2 {
|
|
return strings.TrimRight(u[i+1:], "/")
|
|
}
|
|
return "8470"
|
|
}
|
|
|
|
type serviceCheck struct {
|
|
Name, URL, Status string
|
|
OK bool
|
|
}
|
|
|
|
// coreChecks asks each Core service whether it answers. It's an htmx
|
|
// fragment, loaded after the page so a slow service doesn't hold it up.
|
|
func (s *Server) coreChecks(w http.ResponseWriter, r *http.Request) {
|
|
if s.Core == nil {
|
|
s.fragment(w, "core", "checks", nil)
|
|
return
|
|
}
|
|
services := s.Core.Services()
|
|
checks := make([]serviceCheck, len(services))
|
|
client := &http.Client{
|
|
Timeout: 6 * time.Second,
|
|
// A redirect (e.g. to a login page) means the service is there.
|
|
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
|
}
|
|
var wg sync.WaitGroup
|
|
for i, svc := range services {
|
|
wg.Add(1)
|
|
go func(i int, svc core.Service) {
|
|
defer wg.Done()
|
|
c := serviceCheck{Name: svc.Name, URL: svc.URL}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 6*time.Second)
|
|
defer cancel()
|
|
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, svc.URL, nil)
|
|
res, err := client.Do(req)
|
|
switch {
|
|
case err != nil:
|
|
c.Status = "doesn't answer"
|
|
var dnsErr interface{ Timeout() bool }
|
|
if errors.As(err, &dnsErr) && dnsErr.Timeout() {
|
|
c.Status = "timed out"
|
|
}
|
|
case res.StatusCode >= 500:
|
|
c.Status = "error " + res.Status
|
|
res.Body.Close()
|
|
default:
|
|
c.OK = true
|
|
c.Status = "answers (" + res.Status + ")"
|
|
res.Body.Close()
|
|
}
|
|
checks[i] = c
|
|
}(i, svc)
|
|
}
|
|
wg.Wait()
|
|
s.fragment(w, "core", "checks", checks)
|
|
}
|
|
|
|
// --- AI servers CoreDesktop found ---
|
|
|
|
// AIServer is an LLM server from CoreDesktop's `configure ai-servers`, as
|
|
// install.sh found it in opencode's settings.
|
|
type AIServer struct {
|
|
Name string `json:"name"`
|
|
BaseURL string `json:"base_url"`
|
|
}
|
|
|
|
func (s *Server) aiServers() []AIServer {
|
|
raw, err := os.ReadFile(filepath.Join(s.DataDir, "ai-servers.json"))
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
var out []AIServer
|
|
if err := json.Unmarshal(raw, &out); err != nil {
|
|
s.Log.Warn("ai-servers.json", "err", err)
|
|
return nil
|
|
}
|
|
return out
|
|
}
|
|
|
|
// secretState says whether a secret is set, for forms that never show values.
|
|
func (s *Server) secretState(names ...string) map[string]bool {
|
|
m := map[string]bool{}
|
|
for _, n := range names {
|
|
m[n] = s.Secrets.Has(n)
|
|
}
|
|
return m
|
|
}
|