internal/store/push.go

b81a25efa5dd60e3379bb1f0efaf6548f244e26c
gitbay/internal/store/push.go

170 lines · 5273 bytes

  1package store
  2
  3import (
  4	"database/sql"
  5	"errors"
  6	"time"
  7)
  8
  9// PushDevice is one Apple device an account has registered. Token is the
 10// APNs device token: an address, not a credential, but device-identifying
 11// and never logged or echoed in full.
 12type PushDevice struct {
 13	ID         int64
 14	UserID     int64
 15	Token      string
 16	Label      string
 17	CreatedAt  string
 18	LastSeenAt string
 19}
 20
 21// AddPushDevice registers a token to an account. A token already present
 22// changes hands rather than erroring: Apple reuses tokens, and a reinstall
 23// hands the same one to whichever account signs in next. The id is read
 24// back by token rather than taken from LastInsertId, which SQLite leaves
 25// unchanged when the DO UPDATE arm fires instead of the INSERT.
 26func (s *Store) AddPushDevice(userID int64, token, label string) (int64, error) {
 27	_, err := s.DB.Exec(`
 28		INSERT INTO push_devices (user_id, token, label) VALUES (?, ?, ?)
 29		ON CONFLICT(token) DO UPDATE SET user_id = excluded.user_id, label = excluded.label`,
 30		userID, token, label)
 31	if err != nil {
 32		return 0, err
 33	}
 34	var id int64
 35	err = s.DB.QueryRow("SELECT id FROM push_devices WHERE token = ?", token).Scan(&id)
 36	return id, err
 37}
 38
 39func (s *Store) PushDevices(userID int64) ([]PushDevice, error) {
 40	rows, err := s.DB.Query(`
 41		SELECT id, user_id, token, label, created_at, COALESCE(last_seen_at, '')
 42		FROM push_devices WHERE user_id = ? ORDER BY id`, userID)
 43	if err != nil {
 44		return nil, err
 45	}
 46	defer rows.Close()
 47	var out []PushDevice
 48	for rows.Next() {
 49		var d PushDevice
 50		if err := rows.Scan(&d.ID, &d.UserID, &d.Token, &d.Label, &d.CreatedAt, &d.LastSeenAt); err != nil {
 51			return nil, err
 52		}
 53		out = append(out, d)
 54	}
 55	return out, rows.Err()
 56}
 57
 58// RemovePushDevice deletes one of the account's own devices. Scoping the
 59// delete by user_id rather than checking ownership first means another
 60// account's id is ErrNotFound, which is the same answer as an id that
 61// never existed — a caller learns nothing about other accounts' devices.
 62func (s *Store) RemovePushDevice(userID, id int64) error {
 63	res, err := s.DB.Exec("DELETE FROM push_devices WHERE id = ? AND user_id = ?", id, userID)
 64	if err != nil {
 65		return err
 66	}
 67	n, err := res.RowsAffected()
 68	if err != nil {
 69		return err
 70	}
 71	if n == 0 {
 72		return ErrNotFound
 73	}
 74	return nil
 75}
 76
 77func (s *Store) PushEnabled(userID int64) (bool, error) {
 78	var on int
 79	err := s.DB.QueryRow("SELECT notify_push FROM users WHERE id = ?", userID).Scan(&on)
 80	if errors.Is(err, sql.ErrNoRows) {
 81		return false, ErrNotFound
 82	}
 83	return on != 0, err
 84}
 85
 86func (s *Store) SetPushEnabled(userID int64, on bool) error {
 87	v := 0
 88	if on {
 89		v = 1
 90	}
 91	_, err := s.DB.Exec("UPDATE users SET notify_push = ? WHERE id = ?", v, userID)
 92	return err
 93}
 94
 95// QueuedPush is one pending push, joined to the token it is bound for so
 96// the drainer needs one query rather than two.
 97type QueuedPush struct {
 98	ID       int64
 99	DeviceID int64
100	Token    string
101	Title    string
102	Body     string
103	Path     string
104	Attempts int
105}
106
107// EnqueuePush writes one row per registered device, and nothing when the
108// account has push off or no devices — the same shape as
109// ActivityMailAddress returning "" when notify_mail is off. Mute, watch
110// and actor-exclusion are already settled by NotifyRecipients before a
111// caller reaches here.
112func (s *Store) EnqueuePush(userID int64, title, body, path string) error {
113	on, err := s.PushEnabled(userID)
114	if err != nil || !on {
115		return err
116	}
117	_, err = s.DB.Exec(`
118		INSERT INTO push_queue (device_id, title, body, path)
119		SELECT id, ?, ?, ? FROM push_devices WHERE user_id = ?`,
120		title, body, path, userID)
121	return err
122}
123
124func (s *Store) DuePush(limit int) ([]QueuedPush, error) {
125	rows, err := s.DB.Query(`
126		SELECT q.id, q.device_id, d.token, q.title, q.body, q.path, q.attempts
127		FROM push_queue q JOIN push_devices d ON d.id = q.device_id
128		WHERE q.sent_at IS NULL AND q.failed_at IS NULL
129		  AND (q.next_attempt_at IS NULL OR q.next_attempt_at <= ?)
130		ORDER BY q.id LIMIT ?`, fmtTime(time.Now()), limit)
131	if err != nil {
132		return nil, err
133	}
134	defer rows.Close()
135	var out []QueuedPush
136	for rows.Next() {
137		var p QueuedPush
138		if err := rows.Scan(&p.ID, &p.DeviceID, &p.Token, &p.Title, &p.Body, &p.Path, &p.Attempts); err != nil {
139			return nil, err
140		}
141		out = append(out, p)
142	}
143	return out, rows.Err()
144}
145
146func (s *Store) MarkPushSent(id int64) error {
147	_, err := s.DB.Exec(
148		"UPDATE push_queue SET sent_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), attempts = attempts + 1 WHERE id = ?", id)
149	return err
150}
151
152func (s *Store) MarkPushFailed(id int64, errMsg string, nextAt *time.Time) error {
153	if nextAt == nil {
154		_, err := s.DB.Exec(
155			"UPDATE push_queue SET failed_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), attempts = attempts + 1, last_error = ? WHERE id = ?",
156			errMsg, id)
157		return err
158	}
159	_, err := s.DB.Exec(
160		"UPDATE push_queue SET attempts = attempts + 1, last_error = ?, next_attempt_at = ? WHERE id = ?",
161		errMsg, fmtTime(*nextAt), id)
162	return err
163}
164
165// DeletePushDeviceByToken drops a device Apple has told us is gone. The
166// queue rows cascade, so nothing is left retrying at a dead token.
167func (s *Store) DeletePushDeviceByToken(token string) error {
168	_, err := s.DB.Exec("DELETE FROM push_devices WHERE token = ?", token)
169	return err
170}