package api
// chatsms.go texts a person a repository's chat channel while they are
// away from it, and takes their text back as a post (inboundreply.go).
// It rides on chatMentionAt like the channel's bell does, so a line
// posted here and a line a bridge imported are treated alike.
//
// A text is for somebody who is not already reading: it is skipped when
// the person was in the channel in the last twenty minutes, and inside
// their quiet hours. Delivery is notify's sms step, which sends only to
// a phone the person verified; the setting here is the opt-in.
import (
"context"
"fmt"
"log"
"net/http"
"regexp"
"strings"
"time"
"craftdesign.group/quarry/internal/chat"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// ChatSMSStore is the chat_sms, chat_seen and chat_sms_sent tables,
// satisfied by *oltp.DB.
type ChatSMSStore interface {
SetChatSMS(repo, account string, s oltp.ChatSMS) error
ChatSMS(repo, account string) oltp.ChatSMS
ChatSMSFollowers(repo string) ([]oltp.ChatSMSFollower, error)
TouchChatSeen(repo, account string, at time.Time) error
ChatSeenSince(repo, account string, since time.Time) bool
RecordChatSMSSent(account, repo string, at time.Time) error
RecentChatSMSSent(account string, since time.Time) ([]oltp.ChatSMSSent, error)
}
const (
// chatSMSAway is how long somebody must have been out of a channel
// before it texts them.
chatSMSAway = 20 * time.Minute
// chatSMSReplyWindow is how long after a text a reply to it still
// belongs to the channel that sent it.
chatSMSReplyWindow = 2 * time.Hour
// chatSMSSummaryRunes keeps the quoted line to about one text.
chatSMSSummaryRunes = 120
// chatSMSDigest is how long a text may wait in notify's digest, and
// then some: texts from channels fired this close together may reach
// the phone in either order, so a bare reply cannot say which it
// answers.
chatSMSDigest = 15 * time.Minute
// chatRobotUser is the author of the forge's own robot lines
// (chat.KindRobot). They are posted without passing chatMentionAt;
// the name is checked as well so a change there cannot start texts.
chatRobotUser = "robot"
)
// chatSeen notes that account was in repo's channel just now.
func (d Deps) chatSeen(repo, account string) {
if d.ChatSMS == nil || account == "" {
return
}
if err := d.ChatSMS.TouchChatSeen(repo, account, d.now()); err != nil {
log.Printf("chat sms %s: seen %s: %v", repo, account, err)
}
}
// chatPoster is the account a line counts as presence for: its author
// when it was posted here, the account an administrator linked a bridged
// name to, and for a bridged name nobody linked, the account of the same
// login, as the own-line skip reads it. The caller only writes presence
// for somebody who already follows the channel, so a stranger's name
// earns no row.
func (d Deps) chatPoster(repo, from string) string {
rest, bridged := strings.CutPrefix(from, "fossil:")
if !bridged {
return from
}
if d.ChatIdentities != nil {
if links, err := d.ChatIdentities.ChatIdentities(repo); err == nil {
for _, l := range links {
if l.Remote == from {
return l.Account
}
}
}
}
return rest
}
// chatSMSAt texts message seq to everybody who turned texting on for
// repo's channel and is away from it. Never a robot's line (the forge's
// own, or the upstream fossil's timeline announcement), never the
// author's own (as the account, as the same login upstream, or as a name
// linked to them), never somebody who has lost the chat letter.
func (d Deps) chatSMSAt(repo, text, from string, seq uint64) {
if d.ChatSMS == nil || from == "" || from == chatRobotUser || chat.IsTimelineLine(text) {
return
}
followers, err := d.ChatSMS.ChatSMSFollowers(repo)
if err != nil {
log.Printf("chat sms %s: followers: %v", repo, err)
return
}
if len(followers) == 0 {
return
}
now := d.now()
poster := d.chatPoster(repo, from)
for _, f := range followers {
if f.Account == poster {
// Posting is being there.
d.chatSeen(repo, poster)
break
}
}
summary := chatSummary(text, from, chatSMSSummaryRunes, "...")
for _, f := range followers {
if f.Account == from || "fossil:"+f.Account == from || f.Account == poster {
continue
}
if d.CapsFor != nil && !d.CapsFor(f.Account, repo).HasAny("C") {
continue
}
if f.Quiet(now) || d.ChatSMS.ChatSeenSince(repo, f.Account, now.Add(-chatSMSAway)) {
continue
}
e := NotifyEvent{
Workflow: "quarry-chat-sms", To: f.Account,
Payload: map[string]any{
"repo": repo, "actor": from, "summary": summary,
"surface": "chat", "ref": fmt.Sprintf("message #%d", seq),
"link": fmt.Sprintf("/r/%s/chat/%d", repo, seq),
},
TxnID: fmt.Sprintf("chat-sms:%s:%d:%s", repo, seq, f.Account),
}
// The route is kept only for a text that will leave: the checks
// fireNotify makes, made first.
if !d.noticeDeliverable(e) || d.muted(f.Account, repo) {
continue
}
if err := d.ChatSMS.RecordChatSMSSent(f.Account, repo, now); err != nil {
// Without the route a reply has nowhere to go; the text is
// still worth sending.
log.Printf("chat sms %s: record %s: %v", repo, f.Account, err)
}
d.fireNotify(e)
}
}
type chatSMSIn struct {
Repo string `json:"repo" validate:"required,max=64"`
}
type chatSMSSetIn struct {
Repo string `json:"repo" validate:"required,max=64"`
// On turns texting on for this channel.
On bool `json:"on"`
// QuietStart and QuietEnd are the hours, 0 to 23 in TZ, between which
// nothing is texted; equal hours mean no quiet hours.
QuietStart int `json:"quietStart" validate:"min=0,max=23"`
QuietEnd int `json:"quietEnd" validate:"min=0,max=23"`
// TZ is an IANA zone name; empty is UTC.
TZ string `json:"tz" validate:"max=64"`
}
type chatSMSOut struct {
Repo string `json:"repo"`
On bool `json:"on"`
QuietStart int `json:"quietStart"`
QuietEnd int `json:"quietEnd"`
TZ string `json:"tz"`
}
func smsOut(repo string, s oltp.ChatSMS) chatSMSOut {
return chatSMSOut{Repo: repo, On: s.On, QuietStart: s.QuietStart, QuietEnd: s.QuietEnd, TZ: s.TZ}
}
func registerChatSMS(r *ops.Registry, d Deps) error {
if err := ops.Register(r, ops.Op[chatSMSIn, chatSMSOut]{
Name: "chat.sms",
Caps: "C",
Doc: "Whether the signed-in account is texted a repository's chat channel, and its quiet hours. Off, UTC and no quiet hours until chosen.",
Kind: ops.Query,
Auth: ops.Token,
Route: "GET /api/v1/r/{repo}/chat/sms",
Run: func(ctx context.Context, in chatSMSIn) (chatSMSOut, error) {
if _, err := d.repoFor(ctx, in.Repo); err != nil {
return chatSMSOut{}, err
}
if d.ChatSMS == nil {
return smsOut(in.Repo, oltp.ChatSMS{TZ: "UTC"}), nil
}
return smsOut(in.Repo, d.ChatSMS.ChatSMS(in.Repo, author(ctx))), nil
},
}); err != nil {
return err
}
return ops.Register(r, ops.Op[chatSMSSetIn, chatSMSOut]{
Name: "chat.sms.set",
Caps: "C",
Doc: "Text the signed-in account a repository's chat channel while they are away from it, or stop. Nothing is texted between " +
"`quietStart` and `quietEnd` (hours 0 to 23 in `tz`, an IANA zone name; the window may wrap midnight, and equal hours mean none). " +
"A text goes only to a phone the account verified, and a text back is posted in the channel.",
Kind: ops.Command,
Auth: ops.Token,
Route: "POST /api/v1/r/{repo}/chat/sms",
Run: func(ctx context.Context, in chatSMSSetIn) (chatSMSOut, error) {
if _, err := d.repoFor(ctx, in.Repo); err != nil {
return chatSMSOut{}, err
}
who := ops.User(ctx)
if who == "" {
return chatSMSOut{}, fmt.Errorf("sign in to choose what is texted to you: %w", ops.ErrForbidden)
}
if d.ChatSMS == nil {
return chatSMSOut{}, fmt.Errorf("this forge keeps no text settings: %w", ops.ErrUnavailable)
}
s := oltp.ChatSMS{On: in.On, QuietStart: in.QuietStart, QuietEnd: in.QuietEnd, TZ: in.TZ}
if s.TZ == "" {
s.TZ = "UTC"
}
if err := s.Check(); err != nil {
return chatSMSOut{}, refusalAsInvalid(err)
}
if err := d.ChatSMS.SetChatSMS(in.Repo, who, s); err != nil {
return chatSMSOut{}, refusalAsInvalid(err)
}
return smsOut(in.Repo, s), nil
},
})
}
// chatTextMax is the longest line chat.post takes (chatPostIn.Text). A
// text longer than that is cut to it, not refused, so what fits is kept.
const chatTextMax = 4096
// smsKeywords are the words a carrier or notify answers itself: opting
// out or back in, and asking for help. They are never a line for the
// channel.
var smsKeywords = map[string]bool{
"STOP": true, "STOPALL": true, "UNSUBSCRIBE": true, "CANCEL": true, "END": true, "QUIT": true,
"START": true, "YES": true, "UNSTOP": true, "HELP": true, "INFO": true,
}
// applySMS turns a text from a person's phone into a line in the channel
// that last texted them. Anything that is not that is acknowledged and
// dropped (a 2xx, recorded): notify redelivering it would change
// nothing. The post goes through say, so the chat letter, a takedown,
// the bridge to an upstream fossil, mentions and every notification
// treat it as the line the account would have typed.
func (h *ReplyReceiver) applySMS(ctx context.Context, ev ReplyEvent) (string, int, error) {
if !ev.PhoneVerified {
return "ignored: the phone is not verified", http.StatusOK, nil
}
who := ev.SubscriberID
if who == "" || h.Open == nil {
return "ignored: no account", http.StatusOK, nil
}
if open, err := h.Open(who); err != nil {
return "", http.StatusInternalServerError, err
} else if !open {
return "ignored: not an open account on this forge", http.StatusOK, nil
}
text := strings.TrimSpace(ev.Body)
if text == "" {
return "ignored: empty", http.StatusOK, nil
}
if smsKeywords[strings.ToUpper(text)] {
return "ignored: a keyword notify answers", http.StatusOK, nil
}
if r := []rune(text); len(r) > chatTextMax {
text = string(r[:chatTextMax])
}
repo, text, candidates := h.smsRoute(who, text)
if repo == "" {
if h.SMSNotice != nil {
msg := "Nothing was posted: no chat channel has texted you in the last 2 hours, so there is nowhere to send your reply."
if len(candidates) > 0 {
msg = "Nothing was posted: more than one channel texted you lately (" + strings.Join(candidates, ", ") +
"). Start your reply with the channel, as #name, and send it again."
}
h.SMSNotice(who, ev.InboundMessageID, msg, candidates)
}
return "ignored: no channel to post the reply in", http.StatusOK, nil
}
return h.say(ctx, ReplyTarget{Kind: "chat", Room: repo, Who: who}, text)
}
// smsPrefix is a reply that names its channel: "#name text" or
// "#name: text".
var smsPrefix = regexp.MustCompile(`^#([^\s:]+)(?::\s*|\s+)(\S[\s\S]*)$`)
// smsRoute says which channel a text reply belongs in, and the line to
// post there. Texts leave after notify's digest, so the channel that
// texted last is not necessarily the one a reply answers: a reply names
// its channel with a leading #name, and one that does not is routed only
// when no other channel texted the same person close to it. repo is ""
// when there is nowhere safe to post, and candidates then lists the
// channels it could have meant.
func (h *ReplyReceiver) smsRoute(who, text string) (repo, line string, candidates []string) {
if h.SMSRecent == nil {
return "", text, nil
}
now := h.now()
recent, err := h.SMSRecent(who, now.Add(-chatSMSReplyWindow))
if err != nil {
log.Printf("inbound: sms routes for %s: %v", who, err)
return "", text, nil
}
label := func(repo string) string {
if h.RepoLabel != nil {
return h.RepoLabel(repo)
}
return repo
}
if m := smsPrefix.FindStringSubmatch(text); m != nil {
for _, c := range recent {
if strings.EqualFold(m[1], c.Repo) || strings.EqualFold(m[1], label(c.Repo)) {
return c.Repo, strings.TrimSpace(m[2]), nil
}
}
// A "#42 is merged" is words, not a channel: only a name the
// forge knows is a claim that cannot be honoured.
if h.KnownRepo == nil || h.KnownRepo(m[1]) {
return "", text, smsCandidates(recent, label)
}
}
if len(recent) == 0 {
return "", text, nil
}
for _, c := range recent[1:] {
if recent[0].At.Sub(c.At) < chatSMSDigest {
return "", text, smsCandidates(recent, label)
}
}
return recent[0].Repo, text, nil
}
func smsCandidates(recent []oltp.ChatSMSSent, label func(string) string) []string {
var out []string
for _, c := range recent {
out = append(out, "#"+label(c.Repo))
}
return out
}