Skip to content
quarry Artifact [a998b0a370]
Login

Artifact [a998b0a370]

Artifact a998b0a37055dc289ff9a597725dafd36107e63af04588853c4f00494fbbd54c:


// chatsms.go stores a person's choice to be texted a channel's messages
// and the two small clocks that choice runs on: when they were last in
// the channel (so a text goes only to somebody who is away) and which
// channel last texted them (so their reply has somewhere to go). Like
// chat_notify they are forge-local, per-account social state, never part
// of a repository's history: wiping them turns every text off and drops
// pending reply routes, which loses convenience, not truth.
package oltp

import (
	"fmt"
	"sync"
	"time"
)

const chatSMSSchema = `
CREATE TABLE IF NOT EXISTS chat_sms (
	repo        TEXT NOT NULL,
	account     TEXT NOT NULL,
	enabled     INTEGER NOT NULL,
	quiet_start INTEGER NOT NULL, -- hour 0-23, in tz
	quiet_end   INTEGER NOT NULL, -- equal to quiet_start: no quiet hours
	tz          TEXT NOT NULL,
	at          TEXT NOT NULL,
	PRIMARY KEY (repo, account)
);
CREATE INDEX IF NOT EXISTS chat_sms_repo ON chat_sms (repo, enabled);
CREATE TABLE IF NOT EXISTS chat_seen (
	repo    TEXT NOT NULL,
	account TEXT NOT NULL,
	at      INTEGER NOT NULL, -- unix seconds
	PRIMARY KEY (repo, account)
);
CREATE TABLE IF NOT EXISTS chat_sms_sent (
	account TEXT NOT NULL,
	repo    TEXT NOT NULL,
	at      INTEGER NOT NULL, -- unix seconds
	PRIMARY KEY (account, repo)
);`

// chatSeenGrain is how finely presence is kept: a sighting within a
// minute of the last one is not written, because opening a channel and
// posting in it are the commonest acts on it and SQLite has one writer.
// The window it feeds is minutes wide.
const chatSeenGrain = time.Minute

// chatSMSRouteGrain is how stale a (account, repo) route row must be
// before another text rewrites it: a busy channel texts a person once
// per digest, and the reply route need not know the minute.
const chatSMSRouteGrain = time.Minute

// zones caches time.LoadLocation, which reads the zone database on every
// call and is asked once per follower per message.
var zones sync.Map // name -> *time.Location

func zone(name string) (*time.Location, error) {
	if l, ok := zones.Load(name); ok {
		return l.(*time.Location), nil
	}
	l, err := time.LoadLocation(name)
	if err != nil {
		return nil, err // not cached: names are user input
	}
	zones.Store(name, l)
	return l, nil
}

// ChatSMS is one person's text setting for one repository's channel.
type ChatSMS struct {
	On bool `json:"on"`
	// QuietStart and QuietEnd are hours 0-23 in TZ, and no text is sent
	// from the start hour up to the end hour; the window may wrap
	// midnight. Equal means there is no quiet window.
	QuietStart int    `json:"quietStart"`
	QuietEnd   int    `json:"quietEnd"`
	TZ         string `json:"tz"`
}

// ChatSMSFollower is a person with texting on for a channel.
type ChatSMSFollower struct {
	Account string
	ChatSMS
}

// Check refuses a setting that could not be honoured: an hour off the
// clock, or a zone the forge cannot read.
func (s ChatSMS) Check() error {
	if s.QuietStart < 0 || s.QuietStart > 23 || s.QuietEnd < 0 || s.QuietEnd > 23 {
		return Refusal{fmt.Sprintf("quiet hours are 0 to 23, not %d to %d", s.QuietStart, s.QuietEnd)}
	}
	// "Local" loads, as the forge's own zone, which is nobody's.
	if s.TZ == "Local" {
		return Refusal{`"Local" is not a time zone: give an IANA name such as America/Chicago`}
	}
	if _, err := zone(s.TZ); err != nil {
		return Refusal{fmt.Sprintf("%q is not a time zone: give an IANA name such as America/Chicago", s.TZ)}
	}
	return nil
}

// Quiet reports whether now falls in the setting's quiet hours. A zone
// the forge cannot read is not quiet: Check keeps one from being stored,
// and a text sent is a smaller harm than one silently never sent.
func (s ChatSMS) Quiet(now time.Time) bool {
	if s.QuietStart == s.QuietEnd {
		return false
	}
	loc, err := zone(s.TZ)
	if err != nil {
		return false
	}
	h := now.In(loc).Hour()
	if s.QuietStart < s.QuietEnd {
		return h >= s.QuietStart && h < s.QuietEnd
	}
	return h >= s.QuietStart || h < s.QuietEnd
}

// SetChatSMS records account's text setting for repo's channel. A zone
// left empty is UTC.
func (d *DB) SetChatSMS(repo, account string, s ChatSMS) error {
	if account == "" {
		return Refusal{"sign in to choose what is texted to you"}
	}
	if s.TZ == "" {
		s.TZ = "UTC"
	}
	if err := s.Check(); err != nil {
		return err
	}
	_, err := d.w.Exec(`INSERT INTO chat_sms (repo, account, enabled, quiet_start, quiet_end, tz, at) VALUES (?, ?, ?, ?, ?, ?, ?)
		ON CONFLICT (repo, account) DO UPDATE SET enabled = excluded.enabled, quiet_start = excluded.quiet_start,
			quiet_end = excluded.quiet_end, tz = excluded.tz, at = excluded.at`,
		repo, account, s.On, s.QuietStart, s.QuietEnd, s.TZ, time.Now().UTC().Format(time.RFC3339Nano))
	return err
}

// ChatSMS answers account's setting for repo's channel: off, UTC and no
// quiet hours when they never chose.
func (d *DB) ChatSMS(repo, account string) ChatSMS {
	s := ChatSMS{TZ: "UTC"}
	if account == "" {
		return s
	}
	_ = d.db.QueryRow(`SELECT enabled, quiet_start, quiet_end, tz FROM chat_sms WHERE repo = ? AND account = ?`,
		repo, account).Scan(&s.On, &s.QuietStart, &s.QuietEnd, &s.TZ)
	return s
}

// ChatSMSFollowers lists who has texting on for repo's channel.
func (d *DB) ChatSMSFollowers(repo string) ([]ChatSMSFollower, error) {
	rows, err := d.db.Query(`SELECT account, quiet_start, quiet_end, tz FROM chat_sms WHERE repo = ? AND enabled = 1 ORDER BY account`, repo)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []ChatSMSFollower
	for rows.Next() {
		f := ChatSMSFollower{ChatSMS: ChatSMS{On: true}}
		if err := rows.Scan(&f.Account, &f.QuietStart, &f.QuietEnd, &f.TZ); err != nil {
			return nil, err
		}
		out = append(out, f)
	}
	return out, rows.Err()
}

// TouchChatSeen records that account was in repo's channel at at: they
// posted there or marked it read. It only moves the clock forward.
func (d *DB) TouchChatSeen(repo, account string, at time.Time) error {
	if account == "" {
		return nil
	}
	_, err := d.w.Exec(`INSERT INTO chat_seen (repo, account, at) VALUES (?, ?, ?)
		ON CONFLICT (repo, account) DO UPDATE SET at = excluded.at
		WHERE chat_seen.at <= excluded.at - ?`,
		repo, account, at.Unix(), int64(chatSeenGrain/time.Second))
	return err
}

// ChatSeenSince answers whether account was in repo's channel at or
// after since.
func (d *DB) ChatSeenSince(repo, account string, since time.Time) bool {
	var n int
	_ = d.db.QueryRow(`SELECT count(*) FROM chat_seen WHERE repo = ? AND account = ? AND at >= ?`,
		repo, account, since.Unix()).Scan(&n)
	return n > 0
}

// RecordChatSMSSent notes that account was texted from repo's channel
// at at, which is where their reply to that text will go. A row under a
// minute old is left as it is.
func (d *DB) RecordChatSMSSent(account, repo string, at time.Time) error {
	_, err := d.w.Exec(`INSERT INTO chat_sms_sent (account, repo, at) VALUES (?, ?, ?)
		ON CONFLICT (account, repo) DO UPDATE SET at = excluded.at WHERE chat_sms_sent.at <= excluded.at - ?`,
		account, repo, at.Unix(), int64(chatSMSRouteGrain/time.Second))
	return err
}

// ChatSMSSent is one channel that texted an account, and when.
type ChatSMSSent struct {
	Repo string
	At   time.Time
}

// RecentChatSMSSent lists the channels that texted account at or after
// since, newest first.
func (d *DB) RecentChatSMSSent(account string, since time.Time) ([]ChatSMSSent, error) {
	rows, err := d.db.Query(`SELECT repo, at FROM chat_sms_sent WHERE account = ? AND at >= ? ORDER BY at DESC, repo`,
		account, since.Unix())
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []ChatSMSSent
	for rows.Next() {
		var c ChatSMSSent
		var at int64
		if err := rows.Scan(&c.Repo, &at); err != nil {
			return nil, err
		}
		c.At = time.Unix(at, 0)
		out = append(out, c)
	}
	return out, rows.Err()
}