Skip to content
quarry Artifact [797f825489]
Login

Artifact [797f825489]

Artifact 797f825489947854cb53b177f3b76b0291690d2c317105df69b06e291d7362b0:


// highlights.go stores what the chat bell's "highlights" level runs on:
// the other names a person answers to, the hour their daily digest
// goes out, the highlight sends still waiting out their delay (so a
// visit can cancel them), and when each channel's digest last went.
// Like chat_notify it is forge-local, per-account social state, never
// part of a repository's history.
package oltp

import (
	"database/sql"
	"fmt"
	"strings"
	"time"
	"unicode"
	"unicode/utf8"
)

const highlightSchema = `
CREATE TABLE IF NOT EXISTS call_name (
	account TEXT NOT NULL,
	name    TEXT NOT NULL, -- lower case, no leading @
	PRIMARY KEY (account, name)
);
CREATE INDEX IF NOT EXISTS call_name_by_name ON call_name (name);
CREATE TABLE IF NOT EXISTS highlight_pref (
	account TEXT PRIMARY KEY,
	hour    INTEGER NOT NULL, -- 0-23, in tz
	tz      TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS highlight_pending (
	repo    TEXT NOT NULL,
	account TEXT NOT NULL,
	txn     TEXT NOT NULL,
	at      INTEGER NOT NULL, -- unix seconds
	PRIMARY KEY (repo, account, txn)
);
CREATE TABLE IF NOT EXISTS highlight_sent (
	repo    TEXT NOT NULL,
	account TEXT NOT NULL,
	at      INTEGER NOT NULL, -- unix seconds of the last digest run
	PRIMARY KEY (repo, account)
);`

const (
	// CallNameMin is the shortest name somebody may ask to be called:
	// shorter ones are ordinary words.
	CallNameMin = 4
	// CallNameRunes is the longest a name may be.
	CallNameRunes = 64
	// CallNameMax is how many names an account may hold.
	CallNameMax = 10
	// DefaultDigestHour is when a digest goes out until the person says.
	DefaultDigestHour = 7
)

// CleanCallNames is names as stored: trimmed, without a leading @, lower
// case, inner runs of whitespace collapsed to one space, no repeats. A
// name may be several words ("dan m"). It refuses a name of under
// CallNameMin letters (spaces not counted), one with characters other
// than letters, digits, _ - and spaces, and a list over CallNameMax.
func CleanCallNames(names []string) ([]string, error) {
	var out []string
	seen := map[string]bool{}
	for _, n := range names {
		n = strings.ToLower(strings.Join(strings.Fields(strings.TrimPrefix(strings.TrimSpace(n), "@")), " "))
		if n == "" {
			continue
		}
		if utf8.RuneCountInString(strings.ReplaceAll(n, " ", "")) < CallNameMin {
			return nil, Refusal{fmt.Sprintf("%q is too short: a name needs at least %d letters", n, CallNameMin)}
		}
		if utf8.RuneCountInString(n) > CallNameRunes {
			return nil, Refusal{fmt.Sprintf("%q is too long: a name holds at most %d characters", string([]rune(n)[:20])+"...", CallNameRunes)}
		}
		letters := 0
		for _, r := range n {
			if unicode.IsLetter(r) {
				letters++
			} else if !unicode.IsDigit(r) && r != '_' && r != '-' && r != ' ' {
				return nil, Refusal{fmt.Sprintf("%q has a character a name cannot hold: use letters, digits, _ and -", n)}
			}
		}
		if letters == 0 {
			return nil, Refusal{fmt.Sprintf("%q has no letters: a name needs at least one", n)}
		}
		if !seen[n] {
			seen[n] = true
			out = append(out, n)
		}
	}
	if len(out) > CallNameMax {
		return nil, Refusal{fmt.Sprintf("at most %d names, not %d", CallNameMax, len(out))}
	}
	return out, nil
}

// SetCallNames replaces account's names. Callers pass them through
// CleanCallNames first; this checks again, so no path stores a bad one.
func (d *DB) SetCallNames(account string, names []string) error {
	if account == "" {
		return Refusal{"sign in to choose the names you answer to"}
	}
	clean, err := CleanCallNames(names)
	if err != nil {
		return err
	}
	return d.guarded(func(tx *sql.Tx) error {
		if _, err := tx.Exec(`DELETE FROM call_name WHERE account = ?`, account); err != nil {
			return err
		}
		for _, n := range clean {
			if _, err := tx.Exec(`INSERT INTO call_name (account, name) VALUES (?, ?)`, account, n); err != nil {
				return err
			}
		}
		return nil
	})
}

// CallNames lists account's names, in the order they sort.
func (d *DB) CallNames(account string) []string {
	rows, err := d.db.Query(`SELECT name FROM call_name WHERE account = ? ORDER BY name`, account)
	if err != nil {
		return nil
	}
	defer rows.Close()
	var out []string
	for rows.Next() {
		var n string
		if rows.Scan(&n) == nil {
			out = append(out, n)
		}
	}
	return out
}

// CallNameIndex maps each name somebody asked to be called to the
// accounts that asked.
func (d *DB) CallNameIndex() (map[string][]string, error) {
	rows, err := d.db.Query(`SELECT name, account FROM call_name ORDER BY name, account`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	out := map[string][]string{}
	for rows.Next() {
		var n, a string
		if err := rows.Scan(&n, &a); err != nil {
			return nil, err
		}
		out[n] = append(out[n], a)
	}
	return out, rows.Err()
}

// HighlightPref is when one person's daily digest goes out.
type HighlightPref struct {
	Hour int    `json:"digestHour"`
	TZ   string `json:"tz"`
}

// Check refuses an hour off the clock or a zone the forge cannot read.
func (p HighlightPref) Check() error {
	if p.Hour < 0 || p.Hour > 23 {
		return Refusal{fmt.Sprintf("the digest hour is 0 to 23, not %d", p.Hour)}
	}
	return ChatSMS{TZ: p.TZ}.Check()
}

// Loc is the person's zone; UTC when it cannot be read.
func (p HighlightPref) Loc() *time.Location {
	if l, err := zone(p.TZ); err == nil {
		return l
	}
	return time.UTC
}

// SetHighlightPref records account's digest hour and zone. An empty
// zone is UTC.
func (d *DB) SetHighlightPref(account string, p HighlightPref) error {
	if account == "" {
		return Refusal{"sign in to choose when your digest goes out"}
	}
	if p.TZ == "" {
		p.TZ = "UTC"
	}
	if err := p.Check(); err != nil {
		return err
	}
	_, err := d.w.Exec(`INSERT INTO highlight_pref (account, hour, tz) VALUES (?, ?, ?)
		ON CONFLICT (account) DO UPDATE SET hour = excluded.hour, tz = excluded.tz`, account, p.Hour, p.TZ)
	return err
}

// HighlightPref answers account's digest hour and zone: 07:00, and the
// zone the person already gave their text settings (the newest), else
// UTC, until they choose.
func (d *DB) HighlightPref(account string) HighlightPref {
	p := HighlightPref{Hour: DefaultDigestHour, TZ: "UTC"}
	if account == "" {
		return p
	}
	if d.db.QueryRow(`SELECT hour, tz FROM highlight_pref WHERE account = ?`, account).Scan(&p.Hour, &p.TZ) == nil {
		return p
	}
	var tz string
	if d.db.QueryRow(`SELECT tz FROM chat_sms WHERE account = ? ORDER BY at DESC LIMIT 1`, account).Scan(&tz) == nil && tz != "" {
		p.TZ = tz
	}
	return p
}

// HighlightPendingGrace is how long a pending row outlives the delay it
// tracks; after that the send has gone and the row is only clutter.
const HighlightPendingGrace = time.Hour

// AddHighlightPending notes that a delayed highlight send, keyed by
// txn, is waiting for account in repo's channel. Rows older than the
// grace are dropped as it goes.
func (d *DB) AddHighlightPending(repo, account, txn string, at time.Time) error {
	if _, err := d.w.Exec(`DELETE FROM highlight_pending WHERE at < ?`, at.Add(-HighlightPendingGrace).Unix()); err != nil {
		return err
	}
	_, err := d.w.Exec(`INSERT OR REPLACE INTO highlight_pending (repo, account, txn, at) VALUES (?, ?, ?, ?)`,
		repo, account, txn, at.Unix())
	return err
}

// StillHighlightPending says the send keyed txn is still waiting: no
// visit has taken it.
func (d *DB) StillHighlightPending(repo, account, txn string) bool {
	var n int
	_ = d.db.QueryRow(`SELECT count(*) FROM highlight_pending WHERE repo = ? AND account = ? AND txn = ?`, repo, account, txn).Scan(&n)
	return n > 0
}

// HasHighlightPending says account has a send waiting in repo's channel:
// the cheap read that keeps a visit from calling notify for nothing.
func (d *DB) HasHighlightPending(repo, account string) bool {
	var n int
	_ = d.db.QueryRow(`SELECT count(*) FROM highlight_pending WHERE repo = ? AND account = ?`, repo, account).Scan(&n)
	return n > 0
}

// TakeHighlightPending removes and returns the transaction ids of
// account's waiting sends in repo's channel.
func (d *DB) TakeHighlightPending(repo, account string) ([]string, error) {
	var out []string
	err := d.guarded(func(tx *sql.Tx) error {
		rows, err := tx.Query(`SELECT txn FROM highlight_pending WHERE repo = ? AND account = ? ORDER BY at`, repo, account)
		if err != nil {
			return err
		}
		for rows.Next() {
			var t string
			if err := rows.Scan(&t); err != nil {
				rows.Close()
				return err
			}
			out = append(out, t)
		}
		rows.Close()
		_, err = tx.Exec(`DELETE FROM highlight_pending WHERE repo = ? AND account = ?`, repo, account)
		return err
	})
	return out, err
}

// HighlightFollower is one person with a channel on highlights.
type HighlightFollower struct{ Repo, Account string }

// ChatNotifyHighlights lists every (channel, person) on highlights.
func (d *DB) ChatNotifyHighlights() ([]HighlightFollower, error) {
	rows, err := d.db.Query(`SELECT repo, account FROM chat_notify WHERE mode = ? ORDER BY repo, account`, ChatHighlights)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []HighlightFollower
	for rows.Next() {
		var f HighlightFollower
		if err := rows.Scan(&f.Repo, &f.Account); err != nil {
			return nil, err
		}
		out = append(out, f)
	}
	return out, rows.Err()
}

// HighlightDigestAt is when account's digest for repo last ran; zero
// when it never has.
func (d *DB) HighlightDigestAt(repo, account string) time.Time {
	var at int64
	if d.db.QueryRow(`SELECT at FROM highlight_sent WHERE repo = ? AND account = ?`, repo, account).Scan(&at) != nil {
		return time.Time{}
	}
	return time.Unix(at, 0)
}

// SetHighlightDigestAt records that the digest ran at at, whether or not
// it had anything to say.
func (d *DB) SetHighlightDigestAt(repo, account string, at time.Time) error {
	_, err := d.w.Exec(`INSERT INTO highlight_sent (repo, account, at) VALUES (?, ?, ?)
		ON CONFLICT (repo, account) DO UPDATE SET at = excluded.at`, repo, account, at.Unix())
	return err
}