internal/control/notifications.go

b81a25efa5dd60e3379bb1f0efaf6548f244e26c
gitbay/internal/control/notifications.go

432 lines · 15301 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"strconv"
  8	"strings"
  9
 10	"gitbay.org/gitbay/internal/autolink"
 11	"gitbay.org/gitbay/internal/policy"
 12	"gitbay.org/gitbay/internal/protocol"
 13	"gitbay.org/gitbay/internal/store"
 14)
 15
 16func init() {
 17	register(Command{Path: []string{"notifications", "list"},
 18		Summary:  "your notification inbox, newest first",
 19		Usage:    "notifications list [--all] [--limit <n>] [--cursor <c>]",
 20		ReadOnly: true, Run: runNotificationsList})
 21	register(Command{Path: []string{"notifications", "read"},
 22		Summary: "mark notifications read",
 23		Usage:   "notifications read <id>... | --all", Run: runNotificationsRead})
 24	register(Command{Path: []string{"notifications", "settings", "show"},
 25		Summary:  "your notification preferences",
 26		Usage:    "notifications settings show",
 27		ReadOnly: true, Run: runNotificationsSettingsShow})
 28	register(Command{Path: []string{"notifications", "settings", "mail"},
 29		Summary: "activity by mail as well as the inbox (login links are unaffected)",
 30		Usage:   "notifications settings mail on|off", Run: runNotificationsSettingsMail})
 31	register(Command{Path: []string{"notifications", "settings", "watch"},
 32		Summary: "every issue and merge request on repositories you can write to",
 33		Usage:   "notifications settings watch on|off", Run: runNotificationsSettingsWatch})
 34	register(Command{Path: []string{"notifications", "device", "add"},
 35		Summary: "register an Apple device for push, token on stdin",
 36		Usage:   "notifications device add [--label <name>] < token",
 37		// Mandatory: without it control.go swaps in an empty reader and
 38		// this command stores an empty token without erroring.
 39		ReadsStdin: true, Run: runNotificationsDeviceAdd})
 40	register(Command{Path: []string{"notifications", "device", "list"},
 41		Summary:  "your registered devices",
 42		Usage:    "notifications device list",
 43		ReadOnly: true, Run: runNotificationsDeviceList})
 44	register(Command{Path: []string{"notifications", "device", "remove"},
 45		Summary: "deregister a device",
 46		Usage:   "notifications device remove <id>", Run: runNotificationsDeviceRemove})
 47	register(Command{Path: []string{"notifications", "settings", "push"},
 48		Summary: "activity on your registered devices as well as the inbox",
 49		Usage:   "notifications settings push on|off", Run: runNotificationsSettingsPush})
 50	register(Command{Path: []string{"repo", "watch"},
 51		Summary: "hear about all activity on a repository",
 52		Usage:   "repo watch <owner/name>", Run: runRepoWatch})
 53	register(Command{Path: []string{"repo", "unwatch"},
 54		Summary: "back to the default: only work you are part of",
 55		Usage:   "repo unwatch <owner/name>", Run: runRepoUnwatch})
 56	register(Command{Path: []string{"repo", "mute"},
 57		Summary: "mute a repository, including work you are part of",
 58		Usage:   "repo mute <owner/name>", Run: runRepoMute})
 59}
 60
 61// notice is one thing that happened, in the shape both delivery routes
 62// need: a mail subject and body, and an inbox row. The inbox is filed
 63// whether or not the instance has SMTP; mail is the optional half.
 64type notice struct {
 65	repo    store.Repo
 66	kind    string // issue, mr, or build
 67	subject string // mail subject
 68	action  string // "opened issue #12" — also the inbox summary
 69	excerpt string // quoted into the mail, not the inbox
 70	path    string // web path, no leading slash
 71	// body replaces the composed mail body outright, for a notice whose
 72	// mail is not prose — a failed build's log tail is not an excerpt of
 73	// something someone wrote, and is not cut to an excerpt's length.
 74	body string
 75	// direct keeps the notice to the given accounts: watchers of the
 76	// repository are not added. A mention is addressed to someone.
 77	direct bool
 78}
 79
 80// notify delivers a notice to the given user ids widened by the
 81// repository's watchers (unless direct), minus anyone who muted it and
 82// minus the acting user. A best-effort side channel: failures are
 83// ignored, the action itself already succeeded.
 84func notify(c *Ctx, userIDs []int64, n notice) {
 85	recipients, err := c.Store.NotifyRecipients(n.repo.ID, c.User.ID, userIDs, !n.direct)
 86	if err != nil {
 87		return
 88	}
 89	sendMail := c.Cfg.Mail.SMTPHost != ""
 90	body := noticeBody(c, n)
 91	for _, id := range recipients {
 92		c.Store.AddNotice(id, n.repo.ID, n.kind, c.User.Username, n.action, n.path)
 93		c.Store.EnqueuePush(id, pushTitle(n), pushBody(c.User.Username, n), n.path)
 94		if !sendMail {
 95			continue
 96		}
 97		email, err := c.Store.ActivityMailAddress(id)
 98		if err != nil || email == "" {
 99			continue
100		}
101		c.Store.EnqueueMail(email, n.subject, body)
102	}
103}
104
105// notifyMentions files an inbox row for every account text mentions by
106// @name that can read the repository, and records them as participants
107// of the thread so they hear what follows (#202). Mute is honoured by
108// notify; the actor mentioning themselves is dropped there too.
109func notifyMentions(c *Ctx, repo store.Repo, t thread, itemID, number int64, title, text string) {
110	var ids []int64
111	for _, name := range autolink.Mentions(text) {
112		u, err := c.Store.UserByUsername(name)
113		if err != nil {
114			trimmed := strings.TrimRight(name, "._-")
115			if trimmed == "" || trimmed == name {
116				continue
117			}
118			if u, err = c.Store.UserByUsername(trimmed); err != nil {
119				continue
120			}
121		}
122		if u.ID == c.User.ID {
123			continue
124		}
125		grant, err := c.Store.AccessRole(repo.ID, u.ID)
126		if err != nil || !policy.CanRead(u, repo, grant) {
127			continue
128		}
129		ids = append(ids, u.ID)
130	}
131	if len(ids) == 0 {
132		return
133	}
134	c.Store.AddMentions(repo.ID, t.kind, itemID, ids)
135	notify(c, ids, notice{repo: repo, kind: t.kind, direct: true,
136		subject: fmt.Sprintf("[%s] %s%d: %s", repo.Path(), t.symbol, number, title),
137		action:  fmt.Sprintf("mentioned you in %s%d", t.symbol, number),
138		excerpt: text, path: fmt.Sprintf("%s/%s/%d", repo.Path(), t.segment, number)})
139}
140
141// noticeBody builds the standard mail body: who did what, an excerpt, and
142// the web link.
143func noticeBody(c *Ctx, n notice) string {
144	if n.body != "" {
145		return n.body
146	}
147	var b strings.Builder
148	fmt.Fprintf(&b, "%s %s\n", c.User.Username, n.action)
149	if e := strings.TrimSpace(n.excerpt); e != "" {
150		if len(e) > 500 {
151			e = e[:500] + "…"
152		}
153		fmt.Fprintf(&b, "\n%s\n", e)
154	}
155	fmt.Fprintf(&b, "\n%s/%s\n", strings.TrimSuffix(c.Cfg.Server.SiteURL, "/"), n.path)
156	return b.String()
157}
158
159// pushTitle and pushBody are the alert's two lines. The body is built
160// from the same two values AddNotice files, so the alert and the inbox
161// row cannot disagree about what happened. The title is the repository,
162// which also groups a repository's notices in Notification Center.
163func pushTitle(n notice) string { return n.repo.Path() }
164
165func pushBody(actor string, n notice) string { return actor + " " + n.action }
166
167func issueSubject(repo store.Repo, number int64, title string) string {
168	return fmt.Sprintf("[%s] #%d: %s", repo.Path(), number, title)
169}
170
171func mrSubject(repo store.Repo, number int64, title string) string {
172	return fmt.Sprintf("[%s] !%d: %s", repo.Path(), number, title)
173}
174
175func emitNotificationSettings(c *Ctx) int {
176	mail, err := c.Store.MailEnabled(c.User.ID)
177	if err != nil {
178		return c.fail(protocol.ExitFailure, "%v", err)
179	}
180	watch, err := c.Store.WatchEnabled(c.User.ID)
181	if err != nil {
182		return c.fail(protocol.ExitFailure, "%v", err)
183	}
184	push, err := c.Store.PushEnabled(c.User.ID)
185	if err != nil {
186		return c.fail(protocol.ExitFailure, "%v", err)
187	}
188	return c.emit(map[string]bool{"mail": mail, "watch": watch, "push": push}, func(w io.Writer) {
189		onOff := func(on bool) string {
190			if on {
191				return "on"
192			}
193			return "off"
194		}
195		fmt.Fprintf(w, "mail: %s\nwatch: %s\npush: %s\n", onOff(mail), onOff(watch), onOff(push))
196	})
197}
198
199func runNotificationsSettingsShow(c *Ctx, args []string) int {
200	if len(args) != 0 {
201		return c.usage()
202	}
203	return emitNotificationSettings(c)
204}
205
206// runNotificationsSettingsMail is the "inbox but no mail" switch: the
207// inbox is filed either way, the mail half consults it (#194).
208func runNotificationsSettingsMail(c *Ctx, args []string) int {
209	if len(args) != 1 || (args[0] != "on" && args[0] != "off") {
210		return c.usage()
211	}
212	if err := c.Store.SetMailEnabled(c.User.ID, args[0] == "on"); err != nil {
213		return c.fail(protocol.ExitFailure, "%v", err)
214	}
215	return emitNotificationSettings(c)
216}
217
218// runNotificationsSettingsWatch is the default watch state for
219// repositories the account can write to: consulted when a notice is
220// delivered, so a grant or a revoke needs no watch row of its own (#194).
221func runNotificationsSettingsWatch(c *Ctx, args []string) int {
222	if len(args) != 1 || (args[0] != "on" && args[0] != "off") {
223		return c.usage()
224	}
225	if err := c.Store.SetWatchEnabled(c.User.ID, args[0] == "on"); err != nil {
226		return c.fail(protocol.ExitFailure, "%v", err)
227	}
228	return emitNotificationSettings(c)
229}
230
231func runNotificationsSettingsPush(c *Ctx, args []string) int {
232	if len(args) != 1 || (args[0] != "on" && args[0] != "off") {
233		return c.usage()
234	}
235	if err := c.Store.SetPushEnabled(c.User.ID, args[0] == "on"); err != nil {
236		return c.fail(protocol.ExitFailure, "%v", err)
237	}
238	return emitNotificationSettings(c)
239}
240
241// maxDeviceTokenBytes is well past APNs' 32-byte token rendered as 64 hex
242// characters, and stops a stdin that is not a token from becoming a row.
243const maxDeviceTokenBytes = 512
244
245func runNotificationsDeviceAdd(c *Ctx, args []string) int {
246	f, err := parseFlags(args, flagSpec{Values: []string{"--label"}, Usage: c.Cmd.Usage})
247	if err != nil {
248		return c.fail(protocol.ExitUsage, "%v", err)
249	}
250	if len(f.Pos) != 0 {
251		return c.usage()
252	}
253	raw, err := io.ReadAll(io.LimitReader(c.Stdin, maxDeviceTokenBytes+1))
254	if err != nil {
255		return c.fail(protocol.ExitFailure, "reading stdin: %v", err)
256	}
257	token := strings.TrimSpace(string(raw))
258	if token == "" {
259		return c.usageWith("no device token on stdin")
260	}
261	if len(token) > maxDeviceTokenBytes {
262		return c.fail(protocol.ExitUsage, "device token is too long")
263	}
264	if _, err := c.Store.AddPushDevice(c.User.ID, token, f.Value("--label")); err != nil {
265		return c.fail(protocol.ExitFailure, "%v", err)
266	}
267	return c.emit(map[string]string{"status": "registered"}, func(w io.Writer) {
268		fmt.Fprintln(w, "device registered")
269	})
270}
271
272func runNotificationsDeviceList(c *Ctx, args []string) int {
273	if len(args) != 0 {
274		return c.usage()
275	}
276	devices, err := c.Store.PushDevices(c.User.ID)
277	if err != nil {
278		return c.fail(protocol.ExitFailure, "%v", err)
279	}
280	type row struct {
281		ID    int64  `json:"id"`
282		Label string `json:"label"`
283		Token string `json:"token"` // truncated; a token is not echoed in full
284		Added string `json:"added"`
285	}
286	rows := make([]row, 0, len(devices))
287	for _, d := range devices {
288		rows = append(rows, row{ID: d.ID, Label: d.Label,
289			Token: shortToken(d.Token), Added: d.CreatedAt})
290	}
291	return c.emit(rows, func(w io.Writer) {
292		for _, r := range rows {
293			fmt.Fprintf(w, "%d\t%s\t%s\t%s\n", r.ID, r.Label, r.Token, r.Added)
294		}
295	})
296}
297
298// shortToken renders a device token as its first eight characters. Enough
299// to tell two devices apart in a list, not enough to push to one. A real
300// APNs token is 64 hex characters, so anything at or under the cut length
301// is not a token worth showing part of — it is masked outright rather
302// than echoed whole, which "abc…" would imply is a truncation.
303func shortToken(t string) string {
304	if len(t) > 8 {
305		return t[:8] + "…"
306	}
307	return "(short token)"
308}
309
310func runNotificationsDeviceRemove(c *Ctx, args []string) int {
311	if len(args) != 1 {
312		return c.usage()
313	}
314	id, err := strconv.ParseInt(args[0], 10, 64)
315	if err != nil {
316		return c.usageWith("device id must be a number")
317	}
318	if err := c.Store.RemovePushDevice(c.User.ID, id); err != nil {
319		if errors.Is(err, store.ErrNotFound) {
320			return c.fail(protocol.ExitNotFound, "no such device; notifications device list shows yours")
321		}
322		return c.fail(protocol.ExitFailure, "%v", err)
323	}
324	return c.emit(map[string]string{"status": "removed"}, func(w io.Writer) {
325		fmt.Fprintln(w, "device removed")
326	})
327}
328
329// noticesDefaultLimit caps a bare list; pagination reaches further back.
330const noticesDefaultLimit = 50
331
332func runNotificationsList(c *Ctx, args []string) int {
333	rest, p, code := parsePageFlags(c, args, "notifications", true)
334	if code >= 0 {
335		return code
336	}
337	fl, err := parseFlags(rest, flagSpec{Bools: []string{"--all"}, Usage: c.Cmd.Usage})
338	if err != nil {
339		return c.fail(protocol.ExitUsage, "%v", err)
340	}
341	all := fl.Has("--all")
342	if p.limit == 0 {
343		p.limit = noticesDefaultLimit
344	}
345	notices, err := c.Store.Inbox(c.User.ID, !all, p.queryLimit(), p.keyInt())
346	if err != nil {
347		return c.fail(protocol.ExitFailure, "%v", err)
348	}
349	type out struct {
350		ID        int64  `json:"id"`
351		Repo      string `json:"repo"`
352		Kind      string `json:"kind"`
353		Actor     string `json:"actor"`
354		Summary   string `json:"summary"`
355		Path      string `json:"path"`
356		CreatedAt string `json:"created_at"`
357		ReadAt    string `json:"read_at,omitempty"`
358	}
359	notices, next := trimPage(p, notices, "notifications", func(n store.Notice) string {
360		return strconv.FormatInt(n.ID, 10)
361	})
362	ds := make([]out, 0, len(notices))
363	for _, n := range notices {
364		ds = append(ds, out{n.ID, n.RepoPath, n.Kind, n.Actor, n.Summary, n.Path, n.CreatedAt, n.ReadAt})
365	}
366	return c.emitPage(p, ds, next, func(w io.Writer) {
367		for _, d := range ds {
368			mark := "*"
369			if d.ReadAt != "" {
370				mark = " "
371			}
372			fmt.Fprintf(w, "%s %d\t%s\t%s\t%s %s\t%s\n",
373				mark, d.ID, d.CreatedAt, d.Repo, d.Actor, d.Summary, d.Path)
374		}
375	})
376}
377
378func runNotificationsRead(c *Ctx, args []string) int {
379	fl, err := parseFlags(args, flagSpec{Bools: []string{"--all"}, MaxPos: -1, Usage: c.Cmd.Usage})
380	if err != nil {
381		return c.fail(protocol.ExitUsage, "%v", err)
382	}
383	// --all and a list of ids are two ways of saying which rows: taking
384	// both would leave which one won unstated.
385	if fl.Has("--all") == (len(fl.Pos) > 0) {
386		return c.usage()
387	}
388	var ids []int64
389	for _, a := range fl.Pos {
390		n, err := strconv.ParseInt(a, 10, 64)
391		if err != nil {
392			return c.fail(protocol.ExitUsage, "bad notification id %q", a)
393		}
394		ids = append(ids, n)
395	}
396	n, err := c.Store.MarkNoticesRead(c.User.ID, ids)
397	if err != nil {
398		return c.fail(protocol.ExitFailure, "%v", err)
399	}
400	return c.emit(map[string]int64{"read": n}, func(w io.Writer) {
401		fmt.Fprintf(w, "marked %d read\n", n)
402	})
403}
404
405func runRepoWatch(c *Ctx, args []string) int   { return setWatch(c, args, "watch", "watching") }
406func runRepoMute(c *Ctx, args []string) int    { return setWatch(c, args, "mute", "muted") }
407func runRepoUnwatch(c *Ctx, args []string) int { return setWatch(c, args, "unwatch", "default") }
408
409// setWatch records the caller's state on a repository. "default" deletes
410// the row: watch then unwatch leaves no trace, and a mute is undone the
411// same way.
412func setWatch(c *Ctx, args []string, verb, state string) int {
413	if len(args) != 1 {
414		return c.usage()
415	}
416	repo, code := resolveRepo(c, args[0], policy.CanRead)
417	if code >= 0 {
418		return code
419	}
420	var err error
421	if state == "default" {
422		err = c.Store.ClearRepoWatch(repo.ID, c.User.ID)
423	} else {
424		err = c.Store.SetRepoWatch(repo.ID, c.User.ID, state)
425	}
426	if err != nil {
427		return c.fail(protocol.ExitFailure, "%v", err)
428	}
429	return c.emit(map[string]string{"repo": repo.Path(), "state": state}, func(w io.Writer) {
430		fmt.Fprintf(w, "%s %s\n", state, repo.Path())
431	})
432}