internal/control/notifications.go
195 lines · 6390 bytes
1package control
2
3import (
4 "fmt"
5 "io"
6 "strconv"
7 "strings"
8
9 "gitbay.org/gitbay/internal/policy"
10 "gitbay.org/gitbay/internal/protocol"
11 "gitbay.org/gitbay/internal/store"
12)
13
14func init() {
15 register(Command{Path: []string{"notifications", "list"},
16 Summary: "your notification inbox, newest first",
17 Usage: "notifications list [--all] [--limit <n>] [--cursor <c>]",
18 ReadOnly: true, Run: runNotificationsList})
19 register(Command{Path: []string{"notifications", "read"},
20 Summary: "mark notifications read",
21 Usage: "notifications read <id>... | --all", Run: runNotificationsRead})
22 register(Command{Path: []string{"repo", "watch"},
23 Summary: "hear about all activity on a repository",
24 Usage: "repo watch <owner/name>", Run: runRepoWatch})
25 register(Command{Path: []string{"repo", "unwatch"},
26 Summary: "mute a repository, including work you are part of",
27 Usage: "repo unwatch <owner/name>", Run: runRepoUnwatch})
28}
29
30// notice is one thing that happened, in the shape both delivery routes
31// need: a mail subject and body, and an inbox row. The inbox is filed
32// whether or not the instance has SMTP; mail is the optional half.
33type notice struct {
34 repo store.Repo
35 kind string // issue, mr, or build
36 subject string // mail subject
37 action string // "opened issue #12" — also the inbox summary
38 excerpt string // quoted into the mail, not the inbox
39 path string // web path, no leading slash
40 // body replaces the composed mail body outright, for a notice whose
41 // mail is not prose — a failed build's log tail is not an excerpt of
42 // something someone wrote, and is not cut to an excerpt's length.
43 body string
44}
45
46// notify delivers a notice to the given user ids widened by the
47// repository's watchers, minus anyone who muted it and minus the acting
48// user. A best-effort side channel: failures are ignored, the action
49// itself already succeeded.
50func notify(c *Ctx, userIDs []int64, n notice) {
51 recipients, err := c.Store.NotifyRecipients(n.repo.ID, c.User.ID, userIDs)
52 if err != nil {
53 return
54 }
55 sendMail := c.Cfg.Mail.SMTPHost != ""
56 body := noticeBody(c, n)
57 for _, id := range recipients {
58 c.Store.AddNotice(id, n.repo.ID, n.kind, c.User.Username, n.action, n.path)
59 if !sendMail {
60 continue
61 }
62 email, err := c.Store.PrimaryVerifiedEmail(id)
63 if err != nil || email == "" {
64 continue
65 }
66 c.Store.EnqueueMail(email, n.subject, body)
67 }
68}
69
70// noticeBody builds the standard mail body: who did what, an excerpt, and
71// the web link.
72func noticeBody(c *Ctx, n notice) string {
73 if n.body != "" {
74 return n.body
75 }
76 var b strings.Builder
77 fmt.Fprintf(&b, "%s %s\n", c.User.Username, n.action)
78 if e := strings.TrimSpace(n.excerpt); e != "" {
79 if len(e) > 500 {
80 e = e[:500] + "…"
81 }
82 fmt.Fprintf(&b, "\n%s\n", e)
83 }
84 fmt.Fprintf(&b, "\n%s/%s\n", strings.TrimSuffix(c.Cfg.Server.SiteURL, "/"), n.path)
85 return b.String()
86}
87
88func issueSubject(repo store.Repo, number int64, title string) string {
89 return fmt.Sprintf("[%s] #%d: %s", repo.Path(), number, title)
90}
91
92func mrSubject(repo store.Repo, number int64, title string) string {
93 return fmt.Sprintf("[%s] !%d: %s", repo.Path(), number, title)
94}
95
96// noticesDefaultLimit caps a bare list; pagination reaches further back.
97const noticesDefaultLimit = 50
98
99func runNotificationsList(c *Ctx, args []string) int {
100 const usage = "notifications list [--all] [--limit <n>] [--cursor <c>]"
101 rest, p, code := parsePageFlags(c, args, "notifications", true)
102 if code >= 0 {
103 return code
104 }
105 fl, err := parseFlags(rest, flagSpec{Bools: []string{"--all"}, Usage: usage})
106 if err != nil {
107 return c.fail(protocol.ExitUsage, "%v", err)
108 }
109 all := fl.Has("--all")
110 if p.limit == 0 {
111 p.limit = noticesDefaultLimit
112 }
113 notices, err := c.Store.Inbox(c.User.ID, !all, p.queryLimit(), p.keyInt())
114 if err != nil {
115 return c.fail(protocol.ExitFailure, "%v", err)
116 }
117 type out struct {
118 ID int64 `json:"id"`
119 Repo string `json:"repo"`
120 Kind string `json:"kind"`
121 Actor string `json:"actor"`
122 Summary string `json:"summary"`
123 Path string `json:"path"`
124 CreatedAt string `json:"created_at"`
125 ReadAt string `json:"read_at,omitempty"`
126 }
127 notices, next := trimPage(p, notices, "notifications", func(n store.Notice) string {
128 return strconv.FormatInt(n.ID, 10)
129 })
130 ds := make([]out, 0, len(notices))
131 for _, n := range notices {
132 ds = append(ds, out{n.ID, n.RepoPath, n.Kind, n.Actor, n.Summary, n.Path, n.CreatedAt, n.ReadAt})
133 }
134 return c.emitPage(p, ds, next, func(w io.Writer) {
135 for _, d := range ds {
136 mark := "*"
137 if d.ReadAt != "" {
138 mark = " "
139 }
140 fmt.Fprintf(w, "%s %d\t%s\t%s\t%s %s\t%s\n",
141 mark, d.ID, d.CreatedAt, d.Repo, d.Actor, d.Summary, d.Path)
142 }
143 })
144}
145
146func runNotificationsRead(c *Ctx, args []string) int {
147 const usage = "notifications read <id>... | --all"
148 fl, err := parseFlags(args, flagSpec{Bools: []string{"--all"}, MaxPos: -1, Usage: usage})
149 if err != nil {
150 return c.fail(protocol.ExitUsage, "%v", err)
151 }
152 // --all and a list of ids are two ways of saying which rows: taking
153 // both would leave which one won unstated.
154 if fl.Has("--all") == (len(fl.Pos) > 0) {
155 return c.fail(protocol.ExitUsage, "usage: %s", usage)
156 }
157 var ids []int64
158 for _, a := range fl.Pos {
159 n, err := strconv.ParseInt(a, 10, 64)
160 if err != nil {
161 return c.fail(protocol.ExitUsage, "bad notification id %q", a)
162 }
163 ids = append(ids, n)
164 }
165 n, err := c.Store.MarkNoticesRead(c.User.ID, ids)
166 if err != nil {
167 return c.fail(protocol.ExitFailure, "%v", err)
168 }
169 return c.emit(map[string]int64{"read": n}, func(w io.Writer) {
170 fmt.Fprintf(w, "marked %d read\n", n)
171 })
172}
173
174func runRepoWatch(c *Ctx, args []string) int { return setWatch(c, args, "watching") }
175func runRepoUnwatch(c *Ctx, args []string) int { return setWatch(c, args, "muted") }
176
177func setWatch(c *Ctx, args []string, state string) int {
178 verb := "watch"
179 if state == "muted" {
180 verb = "unwatch"
181 }
182 if len(args) != 1 {
183 return c.fail(protocol.ExitUsage, "usage: repo %s <owner/name>", verb)
184 }
185 repo, code := resolveRepo(c, args[0], policy.CanRead)
186 if code >= 0 {
187 return code
188 }
189 if err := c.Store.SetRepoWatch(repo.ID, c.User.ID, state); err != nil {
190 return c.fail(protocol.ExitFailure, "%v", err)
191 }
192 return c.emit(map[string]string{"repo": repo.Path(), "state": state}, func(w io.Writer) {
193 fmt.Fprintf(w, "%s %s\n", state, repo.Path())
194 })
195}