Skip to content
quarry Artifact [613a1ed51f]
Login

Artifact [613a1ed51f]

Artifact 613a1ed51f9286fbc2be1cd685613ee01a707cf2062d8e35073ad6b22d7bc31b:


package api

// highlights.go is the chat bell's "highlights" level and the names a
// person asks to be called. A highlighted channel tells its member two
// things: a message that names them (by account or by one of their
// "also call me" names) is mailed after a delay, unless they show up in
// the channel first, and everything else comes as one daily digest.
//
// The delay is notify's: the trigger carries a transactionId, and a visit
// cancels it (NotifyCanceller). The digest is built here, at send time,
// by the same tick that sweeps chat windows (ChatHighlightDigests):
// notify can batch events it was handed, but "leave out what the person
// has since read" needs this forge's own state at the moment of sending.

import (
	"context"
	"fmt"
	"log"
	"strings"
	"time"
	"unicode"
	"unicode/utf8"

	"craftdesign.group/quarry/internal/chat"
	"craftdesign.group/quarry/internal/index"
	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
)

// HighlightStore is the call_name, highlight_* tables, satisfied by
// *oltp.DB.
type HighlightStore interface {
	SetCallNames(account string, names []string) error
	CallNames(account string) []string
	CallNameIndex() (map[string][]string, error)
	SetHighlightPref(account string, p oltp.HighlightPref) error
	HighlightPref(account string) oltp.HighlightPref
	AddHighlightPending(repo, account, txn string, at time.Time) error
	HasHighlightPending(repo, account string) bool
	TakeHighlightPending(repo, account string) ([]string, error)
	ChatNotifyHighlights() ([]oltp.HighlightFollower, error)
	HighlightDigestAt(repo, account string) time.Time
	SetHighlightDigestAt(repo, account string, at time.Time) error
}

// NotifyCanceller is the half of the notify plane that stops a trigger
// still waiting out its delay. A plane that cannot cancel simply lets
// the send go.
type NotifyCanceller interface {
	Cancel(ctx context.Context, transactionID string) error
}

const (
	// highlightDelay is how long an addressed message waits before it is
	// mailed; it is the delay step in quarry-chat-highlight.
	highlightDelay = 10 * time.Minute
	// highlightConvoGap ends a conversation: a pause this long between
	// two lines of a channel starts the next one.
	highlightConvoGap = 30 * time.Minute
	// highlightConvoMax is how many conversations a digest names before
	// it links to the rest.
	highlightConvoMax = 12
	// highlightActivityMax bounds the check-in, forum and wiki lines.
	highlightActivityMax = 50
	// highlightDigestWindow is how long after the chosen hour a missed
	// tick may still send the day's digest.
	highlightDigestWindow = 6 * time.Hour
	// highlightHistory is how many channel lines a digest reads back.
	highlightHistory = 1000
)

// wordRune is what a name may not directly touch: "daniel" is in "Daniel,"
// and "@daniel" but not in "danielle".
func wordRune(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' }

// holdsName says text holds name (lower case) as a whole word, with or
// without a leading @.
func holdsName(lowerText, name string) bool {
	for from := 0; from < len(lowerText); {
		i := strings.Index(lowerText[from:], name)
		if i < 0 {
			return false
		}
		start, end := from+i, from+i+len(name)
		from = start + 1
		if r, _ := utf8.DecodeLastRuneInString(lowerText[:start]); start > 0 && wordRune(r) {
			continue
		}
		if r, _ := utf8.DecodeRuneInString(lowerText[end:]); end < len(lowerText) && wordRune(r) {
			continue
		}
		// An @ glued to a word is an address, not a mention (mentionRE's
		// rule): "[email protected]" names nobody.
		if start > 0 && lowerText[start-1] == '@' && start > 1 {
			if r, _ := utf8.DecodeLastRuneInString(lowerText[:start-1]); wordRune(r) || r == '.' || r == '-' {
				continue
			}
		}
		return true
	}
	return false
}

// callNamesIn is the accounts whose also-call-me names text holds.
func callNamesIn(text string, index map[string][]string) []string {
	if len(index) == 0 {
		return nil
	}
	// Whitespace runs read as one space, so "Dan  M" is "dan m".
	lower := strings.Join(strings.Fields(strings.ToLower(text)), " ")
	var out []string
	for name, accounts := range index {
		if holdsName(lower, name) {
			out = append(out, accounts...)
		}
	}
	return out
}

// namedIn is mentionsIn plus the accounts text names by an also-call-me
// name, filtered by the same known test. Every place that fires
// mentions (chat, team chat, forum) asks this, so a name works wherever
// an @handle does.
func (d Deps) namedIn(text string, known func(handle string) bool) []string {
	out := mentionsIn(text, known)
	if d.Highlights == nil {
		return out
	}
	callIdx, err := d.Highlights.CallNameIndex()
	if err != nil {
		log.Printf("call names: %v", err)
		return out
	}
	seen := make(map[string]bool, len(out))
	for _, who := range out {
		seen[who] = true
	}
	for _, who := range callNamesIn(text, callIdx) {
		if seen[who] || (known != nil && !known(who)) {
			continue
		}
		seen[who] = true
		out = append(out, who)
	}
	return out
}

// highlightSend is chatMentionAt's route for somebody on highlights who
// was named: a delayed mail, cancelled by their next visit. It sends
// nothing for their own line (as the account, as the same login
// upstream, or as a name linked to them), for the forge's robot, or for
// the upstream's timeline announcements.
func (d Deps) highlightSend(repo, text, from string, seq uint64, who string) {
	if from == "" || from == chatRobotUser || chat.IsTimelineLine(text) {
		return
	}
	if who == from || "fossil:"+who == from || d.chatPoster(repo, from) == who {
		return
	}
	if d.CapsFor != nil && !d.CapsFor(who, repo).HasAny("C") {
		return
	}
	txn := fmt.Sprintf("highlight:%s:%d:%s", repo, seq, who)
	e := NotifyEvent{
		Workflow: "quarry-chat-highlight", To: who,
		Payload: map[string]any{
			"repo": repo, "from": from, "text": text, "plain": chatPlain(text),
			"surface": "chat", "ref": fmt.Sprintf("message #%d", seq),
			"link": fmt.Sprintf("/r/%s/chat/%d", repo, seq),
		},
		TxnID: txn,
	}
	if !d.noticeDeliverable(e) || d.muted(who, repo) {
		return
	}
	if d.Highlights != nil {
		if err := d.Highlights.AddHighlightPending(repo, who, txn, d.now()); err != nil {
			log.Printf("highlight %s: pending %s: %v", repo, who, err)
		}
	}
	d.fireNotify(e)
}

// highlightVisit cancels account's highlight sends still waiting in
// repo's channel: they are in it now. It asks notify only when a send is
// pending, and not on the caller's time.
func (d Deps) highlightVisit(repo, account string) {
	if d.Highlights == nil || account == "" || !d.Highlights.HasHighlightPending(repo, account) {
		return
	}
	txns, err := d.Highlights.TakeHighlightPending(repo, account)
	if err != nil {
		log.Printf("highlight %s: pending %s: %v", repo, account, err)
		return
	}
	c, ok := d.Notify.(NotifyCanceller)
	if !ok || len(txns) == 0 {
		return
	}
	go func() {
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		for _, txn := range txns {
			if err := c.Cancel(ctx, txn); err != nil {
				log.Printf("highlight %s: cancel %s: %v", repo, txn, err)
			}
		}
	}()
}

// highlightPresence writes presence for a person on highlights who just
// posted: posting is being there, and chatSMSAt only records it for
// people with texting on.
func (d Deps) highlightPresence(repo, from string) {
	if from == "" || from == chatRobotUser {
		return
	}
	poster := d.chatPoster(repo, from)
	if d.chatNotifyMode(repo, poster) == oltp.ChatHighlights {
		d.chatSeen(repo, poster)
	}
}

// digestLine is one line of a daily digest.
type digestLine struct {
	Kind string `json:"kind"`
	Line string `json:"line"`
	Link string `json:"link"`
}

// convo is a run of channel lines with no pause between them long
// enough to end it.
type convo struct {
	first, last  chat.Message
	firstAt      time.Time
	lastAt       time.Time
	count        int
	posters      map[string]bool
	named        map[string]bool // accounts a line names
	bridgedFirst bool
}

func parseAt(s string) time.Time {
	for _, layout := range []string{time.RFC3339Nano, "2006-01-02T15:04:05.999999999", "2006-01-02 15:04:05.999999999"} {
		if t, err := time.Parse(layout, s); err == nil {
			return t
		}
	}
	return time.Time{}
}

// conversations folds a channel's lines into conversations, oldest
// first. Robot lines and the upstream's timeline announcements are not
// conversation.
func (d Deps) conversations(repo string, msgs []chat.Message, callIdx map[string][]string, known func(string) bool) []*convo {
	var out []*convo
	var cur *convo
	for _, m := range chat.Fold(msgs) {
		if m.Kind == chat.KindRobot || m.Origin == "robot" || m.User == chatRobotUser || chat.IsTimelineLine(m.Text) {
			continue
		}
		at := parseAt(m.At)
		if at.IsZero() {
			continue
		}
		if cur == nil || at.Sub(cur.lastAt) > highlightConvoGap {
			cur = &convo{first: m, firstAt: at, posters: map[string]bool{}, named: map[string]bool{}}
			out = append(out, cur)
		}
		cur.last, cur.lastAt = m, at
		cur.count++
		cur.posters[d.chatPoster(repo, m.User)] = true
		cur.posters[m.User] = true
		for _, who := range mentionsIn(m.Text, known) {
			cur.named[who] = true
		}
		for _, who := range callNamesIn(m.Text, callIdx) {
			cur.named[who] = true
		}
	}
	return out
}

// highlightDigest is the digest for account's view of repo's channel
// between since and now: the repository's check-ins, forum posts and
// wiki edits by other people, then the conversations they took no part
// in, did not read and were not named in, at most highlightConvoMax and
// a count of the rest. Empty when there is nothing to say.
func (d Deps) highlightDigest(repo, account string, since, now time.Time) (lines []digestLine, more int) {
	r, ok := d.Repos.Get(repo)
	if !ok {
		return nil, 0
	}
	lines = d.highlightActivity(repo, r, account, since)
	if d.Chat == nil || r.ChatKey() == "" {
		return lines, 0
	}
	msgs, _, err := d.Chat.History(r.ChatKey(), 0, highlightHistory)
	if err != nil {
		log.Printf("highlight digest %s: history: %v", repo, err)
		return lines, 0
	}
	var fresh []chat.Message
	for _, m := range msgs {
		if at := parseAt(m.At); at.After(since) || m.Kind == "edit" || m.Kind == "del" {
			fresh = append(fresh, m)
		}
	}
	var callIdx map[string][]string
	if d.Highlights != nil {
		callIdx, _ = d.Highlights.CallNameIndex()
	}
	var total []digestLine
	for _, c := range d.conversations(repo, fresh, callIdx, d.mentionKnown(repo)) {
		if c.firstAt.Before(since) || c.posters[account] || c.named[account] {
			continue
		}
		if d.ChatSMS != nil && d.ChatSMS.ChatSeenSince(repo, account, c.lastAt) {
			continue
		}
		who := d.chatPoster(repo, c.first.User)
		first := chatSummary(c.first.Text, c.first.User, 100, "...")
		noun := "messages"
		if c.count == 1 {
			noun = "message"
		}
		total = append(total, digestLine{
			Kind: "chat",
			Line: fmt.Sprintf("%s, %d %s: %s", who, c.count, noun, first),
			Link: d.link(fmt.Sprintf("/r/%s/chat/%d", repo, c.first.Seq)),
		})
	}
	if len(total) > highlightConvoMax {
		more = len(total) - highlightConvoMax
		total = total[:highlightConvoMax]
	}
	return append(lines, total...), more
}

// highlightActivity is the repository's check-ins, forum posts and wiki
// edits since, newest first, leaving out the person's own.
func (d Deps) highlightActivity(repo string, r *Repo, account string, since time.Time) []digestLine {
	if r.Index == nil {
		return nil
	}
	var out []digestLine
	before := ""
	for page := 0; page < 5 && len(out) < highlightActivityMax; page++ {
		entries, more, err := r.Index.Timeline(index.TimelineFilter{Limit: 100, Before: before})
		if err != nil {
			log.Printf("highlight digest %s: timeline: %v", repo, err)
			return out
		}
		for _, e := range entries {
			if at := parseAt(e.Date); at.IsZero() || !at.After(since) {
				return out
			}
			if e.User == account || e.User == "fossil:"+account {
				continue
			}
			var line digestLine
			comment := chatSummary(e.Comment, "", 100, "...")
			switch e.Kind {
			case "ci":
				line = digestLine{"checkin", fmt.Sprintf("%s checked in: %s", e.User, comment), d.link("/r/" + repo + "/checkin/" + e.Hash)}
			case "f":
				line = digestLine{"forum", fmt.Sprintf("%s posted in the forum: %s", e.User, comment), d.link("/r/" + repo + "/forum/" + e.Ref[:min(16, len(e.Ref))])}
			case "w":
				line = digestLine{"wiki", fmt.Sprintf("%s edited the wiki: %s", e.User, comment), d.link("/r/" + repo + "/wiki/" + e.Ref)}
			default:
				continue
			}
			if out = append(out, line); len(out) >= highlightActivityMax {
				return out
			}
		}
		if !more || len(entries) == 0 {
			break
		}
		last := entries[len(entries)-1]
		before = last.Date + "~" + last.Hash
	}
	return out
}

// ChatHighlightDigests sends every due daily digest once: for each
// channel a person has on highlights, at the first tick after their
// chosen hour in their own zone. Whether or not there was anything to
// say, the run is recorded, so a quiet day is not rebuilt every tick and
// a busy one is not sent twice. Called on cmd/quarry's sweep tick.
func (d Deps) ChatHighlightDigests() {
	if d.Highlights == nil || d.Repos == nil {
		return
	}
	followers, err := d.Highlights.ChatNotifyHighlights()
	if err != nil {
		log.Printf("highlight digest: followers: %v", err)
		return
	}
	now := d.now()
	for _, f := range followers {
		pref := d.Highlights.HighlightPref(f.Account)
		local := now.In(pref.Loc())
		slot := time.Date(local.Year(), local.Month(), local.Day(), pref.Hour, 0, 0, 0, pref.Loc())
		if slot.After(now) {
			slot = slot.AddDate(0, 0, -1)
		}
		last := d.Highlights.HighlightDigestAt(f.Repo, f.Account)
		if !last.Before(slot) || now.Sub(slot) > highlightDigestWindow {
			continue
		}
		since := last
		if since.IsZero() || now.Sub(since) > 48*time.Hour {
			since = slot.AddDate(0, 0, -1)
		}
		if err := d.Highlights.SetHighlightDigestAt(f.Repo, f.Account, now); err != nil {
			log.Printf("highlight digest %s: %s: %v", f.Repo, f.Account, err)
			continue
		}
		if d.CapsFor != nil && !d.CapsFor(f.Account, f.Repo).HasAny("C") {
			continue
		}
		lines, more := d.highlightDigest(f.Repo, f.Account, since, now)
		if len(lines) == 0 {
			continue
		}
		payload := map[string]any{
			"repo": f.Repo, "surface": "chat", "items": lines,
			"summary": fmt.Sprintf("%d things since yesterday", len(lines)+more),
			"link":    "/r/" + f.Repo + "/chat",
		}
		if more > 0 {
			payload["more"] = more
		}
		d.fireNotify(NotifyEvent{
			Workflow: "quarry-chat-highlights", To: f.Account, Payload: payload,
			TxnID: fmt.Sprintf("highlights-digest:%s:%s:%d", f.Repo, f.Account, slot.Unix()),
		})
	}
}

type highlightsOut struct {
	// Names are the other names the account answers to in chat and the
	// forum, lower case.
	Names []string `json:"names"`
	// DigestHour is the hour, 0 to 23 in TZ, the daily digest of a
	// channel on highlights goes out.
	DigestHour int    `json:"digestHour"`
	TZ         string `json:"tz"`
}

type highlightsSetIn struct {
	Names      []string `json:"names" validate:"max=64"`
	DigestHour int      `json:"digestHour" validate:"min=0,max=23"`
	// TZ is an IANA zone name; empty is the zone already chosen for texts, else UTC.
	TZ string `json:"tz" validate:"max=64"`
}

type highlightsIn struct{}

func registerHighlights(r *ops.Registry, d Deps) error {
	if err := ops.Register(r, ops.Op[highlightsIn, highlightsOut]{
		Name: "me.highlights",
		Doc: "The names the signed-in account answers to besides its own, and when its daily digest goes out. " +
			"A message that holds a name as a whole word or phrase (with or without a leading @, any case) counts as naming the account " +
			"in every chat channel and the forum. The digest, for a channel set to `highlights`, goes out at 07:00 in the account's zone until chosen.",
		Kind:  ops.Query,
		Auth:  ops.Token,
		Route: "GET /api/v1/me/highlights",
		Run: func(ctx context.Context, _ highlightsIn) (highlightsOut, error) {
			who := ops.User(ctx)
			if who == "" || d.Highlights == nil {
				return highlightsOut{Names: []string{}, DigestHour: oltp.DefaultDigestHour, TZ: "UTC"}, nil
			}
			return highlightsOf(d.Highlights, who), nil
		},
	}); err != nil {
		return err
	}
	return ops.Register(r, ops.Op[highlightsSetIn, highlightsOut]{
		Name: "me.highlights.set",
		Doc: "Set the signed-in account's other names and its digest hour. `names` replaces the list: at most 10, each a word or phrase " +
			"of at least 4 letters (spaces not counted), stored without a leading @ and in lower case. `digestHour` is 0 to 23 in `tz`, an IANA zone name.",
		Kind:  ops.Command,
		Auth:  ops.Token,
		Route: "POST /api/v1/me/highlights",
		Run: func(ctx context.Context, in highlightsSetIn) (highlightsOut, error) {
			who := ops.User(ctx)
			if who == "" {
				return highlightsOut{}, fmt.Errorf("sign in to choose the names you answer to: %w", ops.ErrForbidden)
			}
			if d.Highlights == nil {
				return highlightsOut{}, fmt.Errorf("this forge keeps no highlight settings: %w", ops.ErrUnavailable)
			}
			names, err := oltp.CleanCallNames(in.Names)
			if err != nil {
				return highlightsOut{}, refusalAsInvalid(err)
			}
			pref := oltp.HighlightPref{Hour: in.DigestHour, TZ: in.TZ}
			if pref.TZ == "" {
				pref.TZ = d.Highlights.HighlightPref(who).TZ
			}
			if err := pref.Check(); err != nil {
				return highlightsOut{}, refusalAsInvalid(err)
			}
			if err := d.Highlights.SetCallNames(who, names); err != nil {
				return highlightsOut{}, refusalAsInvalid(err)
			}
			if err := d.Highlights.SetHighlightPref(who, pref); err != nil {
				return highlightsOut{}, refusalAsInvalid(err)
			}
			return highlightsOf(d.Highlights, who), nil
		},
	})
}

func highlightsOf(s HighlightStore, who string) highlightsOut {
	p := s.HighlightPref(who)
	names := s.CallNames(who)
	if names == nil {
		names = []string{}
	}
	return highlightsOut{Names: names, DigestHour: p.Hour, TZ: p.TZ}
}