package web import ( "context" "errors" "fmt" "net/http" "strconv" "strings" "sync" "time" "supermarket/internal/api/linkedin" "supermarket/internal/api/twitter" "supermarket/internal/appmail" "supermarket/internal/content" "supermarket/internal/oauth" "supermarket/internal/posting" "supermarket/internal/secrets" "supermarket/internal/users" ) // Posting accounts: the social accounts posts go out from, several per // network: the company's, and people's own. Admins may post to every one, // and say who else may (Settings → Posting accounts); a person's own // account is theirs. var adoptMu sync.Mutex // adoptLegacy turns the single sign-ins from before posting accounts into // the company's accounts, the first time they're seen. func (s *Server) adoptLegacy() { if !s.Secrets.Has(secrets.XAccessToken) && !s.Secrets.Has(secrets.LinkedInAccessToken) && !s.Secrets.Has(secrets.LinkedInPageAccessToken) { return } adoptMu.Lock() defer adoptMu.Unlock() conns := s.connections() expiry := func(c Connection) time.Time { if !c.Expires.IsZero() || c.At.IsZero() { return c.Expires } return c.At.Add(linkedInTokenLife) } n, err := posting.Adopt(s.DB, s.Secrets, func(network string) (string, string, time.Time) { switch network { case posting.X: a := conns["x"].Account if a == "" { return "the company's account", "", time.Time{} } return "@" + a, a, time.Time{} case posting.LinkedIn: return "the company's member", s.Secrets.Get(secrets.LinkedInAuthorURN), expiry(conns["linkedin"]) case posting.LinkedInPage: if o := s.liPage(); o != nil { return o.Name, o.URN, expiry(conns[liPageProvider]) } return "the company page", "", expiry(conns[liPageProvider]) } return "", "", time.Time{} }, time.Now()) if err != nil { s.Log.Error("posting accounts: adopting the old sign-ins", "err", err) } else if n > 0 { s.Log.Info("posting accounts: the old sign-ins are now the company's accounts", "count", n) } } // postingAccounts are every account. func (s *Server) postingAccounts() []*posting.Account { s.adoptLegacy() list, err := posting.List(s.DB) if err != nil { s.Log.Error("posting accounts: listing", "err", err) } return list } // mayPostAs says whether a viewer may post to an account: admins to all, // people to their own and to those they were given. func (s *Server) mayPostAs(v *viewer, a *posting.Account) bool { if v.Member.Admin() { return true } if v.User == nil || !v.Member.Can("content", true) { return false } if a.Owner == v.User.ID { return true } ok, err := posting.Granted(s.DB, a.ID, v.User.ID) return err == nil && ok } // viewerFor is a user as a viewer: for work done for them later, such as a // scheduled post. On the local edition, the owner. func (s *Server) viewerFor(user int64) *viewer { if !s.signsIn() { return localOwner } u, err := users.ByID(s.DB, user) if err != nil || u.Status != users.Active { return &viewer{} } m, err := users.MembershipOf(s.DB, s.team(), u.ID) if err != nil { return &viewer{} } return &viewer{User: u, Member: m} } // working says whether an account can post now: signed in, not expired, // and (a LinkedIn page) with its page chosen. func (s *Server) working(a *posting.Account) bool { return s.Secrets.Has(posting.AccessName(a.ID)) && !a.Expired(time.Now()) && (a.Network != posting.LinkedInPage || a.External != "") } // usableAccounts are the accounts a viewer may post a channel's drafts to // now, by channel. func (s *Server) usableAccounts(v *viewer) map[string][]*posting.Account { out := map[string][]*posting.Account{} for _, a := range s.postingAccounts() { // Reddit accounts signed in before are left unused: Reddit is // posted to by hand. if a.Network != posting.Reddit && s.working(a) && s.mayPostAs(v, a) { ch := posting.Channel(a.Network) out[ch] = append(out[ch], a) } } return out } // draftAccount is the account a draft goes out from: its own, or the // company's for its channel (LinkedIn: as the draft said, member or page, // else whichever there is). nil if there's none. func (s *Server) draftAccount(dr *content.Draft) (*posting.Account, error) { s.adoptLegacy() if dr.AccountID != 0 { a, err := posting.Get(s.DB, dr.AccountID) if errors.Is(err, posting.ErrNotFound) { return nil, errors.New("the account this draft was to go out from was signed out: choose another") } return a, err } nets := []string{dr.Channel} if dr.Channel == content.ChannelLinkedIn { nets = []string{posting.LinkedIn, posting.LinkedInPage} if dr.LinkedInAs == content.AsPage { nets = []string{posting.LinkedInPage, posting.LinkedIn} } } for _, n := range nets { a, err := posting.Company(s.DB, n) if err != nil || a != nil { return a, err } } return nil, nil } // accountPublishers find each draft's account and post as it. type accountPublishers struct{ s *Server } func (s *Server) publishers() content.Publishers { return accountPublishers{s} } func (p accountPublishers) For(dr *content.Draft) (content.Publisher, string, error) { a, err := p.s.draftAccount(dr) if err != nil { return nil, "", err } if a == nil { return nil, "", fmt.Errorf("%s isn't connected: sign in under Settings → Social accounts", dr.ChannelName()) } if posting.Channel(a.Network) != dr.Channel { return nil, "", fmt.Errorf("%s can't post %s drafts", a.Label(), dr.ChannelName()) } if a.Expired(time.Now()) { return nil, "", expiredPublisher{Expiry{Network: a.Label(), At: a.Expires}}.err() } pub, err := p.s.publisherFor(a) if err != nil { return nil, "", err } return pub, a.Label(), nil } // asPublisher posts to LinkedIn as a member or as a page, whatever the // draft says: the account decides. type asPublisher struct { p content.Publisher page bool } func (a asPublisher) Publish(ctx context.Context, post content.Post) (string, error) { post.AsPage = a.page return a.p.Publish(ctx, post) } // publisherFor posts as one account. func (s *Server) publisherFor(a *posting.Account) (content.Publisher, error) { if s.testPublisher != nil { return s.testPublisher(a), nil } tok := s.Secrets.Get(posting.AccessName(a.ID)) if tok == "" { return nil, fmt.Errorf("%s isn't signed in: sign in again under Settings → Social accounts", a.Label()) } switch a.Network { case posting.X: c := twitter.New("", tok, 0) // X access tokens last two hours; refresh tokens are single-use, so // each new one is saved before the old is gone. if s.Secrets.Has(posting.RefreshName(a.ID)) && s.Secrets.Has(secrets.XClientID) { id := a.ID c.SetTokenRefresher(func(ctx context.Context) (string, string, error) { res, err := oauth.RefreshX(ctx, s.Secrets.Get(secrets.XClientID), s.Secrets.Get(secrets.XClientSecret), s.Secrets.Get(posting.RefreshName(id))) if err != nil { return "", "", err } if err := posting.SaveTokens(s.Secrets, id, res.AccessToken, res.RefreshToken); err != nil { s.Log.Error("x: couldn't save the refreshed token; sign in to X again later", "account", id, "err", err) } return res.AccessToken, res.RefreshToken, nil }) } return xPublisher{c}, nil case posting.LinkedIn: return asPublisher{linkedInPublisher{me: linkedin.New(tok, a.External)}, false}, nil case posting.LinkedInPage: if a.External == "" { return nil, errors.New("choose which company page " + a.Label() + " posts as, under Settings → Social accounts") } return asPublisher{linkedInPublisher{page: linkedin.New(tok, a.External)}, true}, nil } return nil, fmt.Errorf("no network %q", a.Network) } // removeAccount signs an account out: scheduled posts to it go back to // Posts, and their writers are told. func (s *Server) removeAccount(a *posting.Account, why string) error { held, err := content.HoldForAccount(s.DB, a.ID, "Not published: "+a.Label()+" "+why+". Choose another account, then publish or schedule it again.") if err != nil { return err } if err := posting.Remove(s.DB, s.Secrets, a.ID); err != nil { return err } s.Log.Info("posting accounts: removed", "account", a.Label(), "why", why, "held", len(held)) s.tellWriters(held, a.Label()+" "+why) return nil } // tellWriters emails the people who scheduled posts that were held. func (s *Server) tellWriters(held []content.Draft, what string) { if !s.signsIn() || len(held) == 0 { return } per := map[int64]int{} for _, d := range held { who := d.PostedBy if who == 0 { who = d.WrittenBy } if who != 0 { per[who]++ } } for id, n := range per { u, err := users.ByID(s.DB, id) if err != nil || u.Status != users.Active { continue } posts := "a scheduled post" if n > 1 { posts = strconv.Itoa(n) + " scheduled posts" } s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Supermarket: " + posts + " held back", Body: "Hello" + nameSuffix(u.Name) + ",\n\n" + what + ", so " + posts + " you scheduled for it won't go out. " + "They're back in Posts: choose another account, then publish or schedule them again.\n\n" + s.PublicURL + "/posts\n"}) } } // Settings → Posting accounts: who may post to which. type postingGrid struct { Accounts []*posting.Account People []users.TeamUser Grants map[int64]map[int64]bool Working map[int64]bool Owners map[int64]string } func (s *Server) postingPage(w http.ResponseWriter, r *http.Request) { if s.admin(w, r) == nil { return } g := postingGrid{Accounts: s.postingAccounts(), Working: map[int64]bool{}, Owners: map[int64]string{}} var err error if g.Grants, err = posting.Grants(s.DB); err != nil { s.serverError(w, err) return } members, err := users.Members(s.DB, s.team()) if err != nil { s.serverError(w, err) return } for _, m := range members { if m.Status != users.Disabled { // people and agents: an agent posts only where it's allowed g.People = append(g.People, m) } g.Owners[m.ID] = m.Name } for _, a := range g.Accounts { g.Working[a.ID] = s.working(a) } s.render(w, r, "posting", page{Title: "Posting accounts", Nav: "settings/posting", Data: g}) } func (s *Server) postingSave(w http.ResponseWriter, r *http.Request) { if s.admin(w, r) == nil { return } if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } accounts := s.postingAccounts() known := map[int64]*posting.Account{} for _, a := range accounts { known[a.ID] = a } grants := map[int64][]int64{} for _, v := range r.PostForm["grant"] { // : var a, u int64 if _, err := fmt.Sscanf(v, "%d:%d", &a, &u); err != nil || known[a] == nil || known[a].Owner == u { continue } grants[a] = append(grants[a], u) } if err := posting.SetGrants(s.DB, grants); err != nil { s.serverError(w, err) return } s.Log.Info("posting accounts: who may post changed") s.audit(r, "posting-grants", "", "") redirect(w, r, "/settings/posting", "saved") } // postingRemove signs an account out: an admin any, a person their own. func (s *Server) postingRemove(w http.ResponseWriter, r *http.Request) { v := viewerOf(r) id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64) a, err := posting.Get(s.DB, id) if errors.Is(err, posting.ErrNotFound) { http.NotFound(w, r) return } if err != nil { s.serverError(w, err) return } mine := v.User != nil && a.Owner == v.User.ID if !mine && !v.Member.Admin() { s.forbidden(w, r) return } why := "was signed out" if mine { why = "was signed out by its owner" } if err := s.removeAccount(a, why); err != nil { s.serverError(w, err) return } s.audit(r, "account-signed-out", a.Label(), "") back := "/settings/accounts" if strings.HasPrefix(r.URL.Path, "/settings/account/") { back = "/settings/account#posting" } redirect(w, r, back, "account-removed") }