Social accounts become posting accounts: several per network, the company's and each person's own, with their tokens kept per account. The old sign-ins are adopted as the company's. Admins say who may post to which (Settings → Posting accounts); a draft can go out from one account or a copy to several, each recording who posted it and as what. Signing an account out, or removing its owner, holds the posts scheduled to it and tells whoever scheduled them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
385 lines
10 KiB
Go
385 lines
10 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/crm"
|
|
"supermarket/internal/inventory"
|
|
"supermarket/internal/posting"
|
|
"supermarket/internal/profile"
|
|
)
|
|
|
|
// 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 { return s.companyExpiry(posting.LinkedIn) }
|
|
|
|
// companyExpiry is when the company's account on a network runs out, or
|
|
// nil if it's renewed by itself (or there's none).
|
|
func (s *Server) companyExpiry(network string) *Expiry {
|
|
s.adoptLegacy()
|
|
a, err := posting.Company(s.DB, network)
|
|
if err != nil || a == nil || a.Expires.IsZero() {
|
|
return nil
|
|
}
|
|
return &Expiry{Network: a.Label(), At: a.Expires}
|
|
}
|
|
|
|
// reminders are the sign-ins running out soon, or already, for the
|
|
// Overview and Posts: every account's.
|
|
func (s *Server) reminders() []Expiry {
|
|
var out []Expiry
|
|
for _, a := range s.postingAccounts() {
|
|
if a.Expires.IsZero() {
|
|
continue
|
|
}
|
|
if e := (Expiry{Network: a.Label(), At: a.Expires}); e.Soon() {
|
|
out = append(out, e)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
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: "Market", Done: len(entries) > 0, Link: "/market",
|
|
Detail: inventorySummary(counts)},
|
|
{Label: "Social accounts", Done: len(s.postingAccounts()) > 0,
|
|
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")},
|
|
}
|
|
if actions, err := crm.List(s.DB, 50); err == nil && len(actions) > 0 {
|
|
broken := crmBroken(actions)
|
|
steps = append(steps, step{Label: "CRM through Hermes", Done: !broken, Link: "/crm",
|
|
Detail: ifElse(broken, "Hermes couldn't reach EspoCRM: see the CRM queue for what to send your Core's admin",
|
|
"Hermes reaches EspoCRM")})
|
|
}
|
|
|
|
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": visibleModules(viewerOf(r)),
|
|
"Admin": viewerOf(r).Member.Admin(),
|
|
"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(map[string]Connection) string {
|
|
var parts []string
|
|
for _, a := range s.postingAccounts() {
|
|
label := a.Label()
|
|
if a.Expired(time.Now()) {
|
|
label += " (expired)"
|
|
}
|
|
parts = append(parts, label)
|
|
}
|
|
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
|
|
}
|
|
|
|
// probeClient checks whether a service answers. A redirect (e.g. to a
|
|
// login page) means the service is there.
|
|
var probeClient = &http.Client{
|
|
Timeout: 6 * time.Second,
|
|
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
|
}
|
|
|
|
// probe asks one service whether it answers, from this computer.
|
|
func probe(ctx context.Context, svc core.Service) serviceCheck {
|
|
c := serviceCheck{Name: svc.Name, URL: svc.URL}
|
|
ctx, cancel := context.WithTimeout(ctx, 6*time.Second)
|
|
defer cancel()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, svc.URL, nil)
|
|
if err != nil {
|
|
c.Status = "isn't a valid address"
|
|
return c
|
|
}
|
|
res, err := probeClient.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()
|
|
}
|
|
return c
|
|
}
|
|
|
|
// 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, r, "core", "checks", nil)
|
|
return
|
|
}
|
|
services := s.Core.Services()
|
|
checks := make([]serviceCheck, len(services))
|
|
var wg sync.WaitGroup
|
|
for i, svc := range services {
|
|
wg.Add(1)
|
|
go func(i int, svc core.Service) {
|
|
defer wg.Done()
|
|
checks[i] = probe(r.Context(), svc)
|
|
}(i, svc)
|
|
}
|
|
wg.Wait()
|
|
s.fragment(w, r, "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
|
|
}
|