-
Notifications
You must be signed in to change notification settings - Fork 2
/
create_post.go
394 lines (356 loc) · 13 KB
/
create_post.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package main
import (
"fmt"
"strings"
"time"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"maunium.net/go/mautrix"
mevent "maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
mid "maunium.net/go/mautrix/id"
)
const CHECKMARK = "✅"
const RED_X = "❌"
// Previous Post
var StatePreviousPost = mevent.Type{Type: "com.nevarro.standupbot.previous_post", Class: mevent.StateEventType}
type PreviousPostEventContent struct {
EditEventID mid.EventID
FlowID uuid.UUID
Day time.Weekday
TodayItems []StandupItem
}
func sendMessageWithCheckmarkReaction(roomID mid.RoomID, message *mevent.MessageEventContent) (*mautrix.RespSendEvent, error) {
resp, err := SendMessage(roomID, message)
if err != nil {
return nil, err
}
SendReaction(roomID, resp.EventID, CHECKMARK)
return resp, nil
}
func sendThreadRootMessage(roomID mid.RoomID, header string) (*mautrix.RespSendEvent, error) {
content := format.RenderMarkdown(fmt.Sprintf("**%s** *(thread)*", header), true, false)
return SendMessage(roomID, &content)
}
func GoToStateAndNotify(roomID mid.RoomID, userID mid.UserID, state StandupFlowState) {
var question string
switch state {
case Friday:
question = "What did you do Friday?"
break
case Weekend:
question = "What did you do over the weekend?"
break
case Yesterday:
question = "What did you do yesterday?"
break
case Today:
question = "What are you planning to do today?"
break
case Blockers:
question = "Do you have any blockers?"
break
case Notes:
question = "Do you have any other notes?"
break
}
var resp *mautrix.RespSendEvent
var err error
if state == Threads || state == ThreadsFriday {
content := format.RenderMarkdown("**Fill out the standup post by replying in each thread.** *Enter one item per message.*", true, false)
resp, err = SendMessage(roomID, &content)
} else {
content := format.RenderMarkdown(fmt.Sprintf("%s *Enter one item per message. React with ✅ when done.*", question), true, false)
resp, err = sendMessageWithCheckmarkReaction(roomID, &content)
}
if err != nil {
log.Errorf("Failed to send notice asking '%s'!", question)
return
}
if _, found := currentStandupFlows[userID]; !found {
currentStandupFlows[userID] = BlankStandupFlow()
}
currentStandupFlows[userID].State = state
currentStandupFlows[userID].ReactableEvents = append(currentStandupFlows[userID].ReactableEvents, resp.EventID)
if state == Threads || state == ThreadsFriday {
if state == ThreadsFriday {
resp, err := sendThreadRootMessage(roomID, "Friday")
if err != nil {
log.Error("Unable to send thread root for Friday")
return
}
currentStandupFlows[userID].FridayThreadEvents = []mid.EventID{resp.EventID}
resp, err = sendThreadRootMessage(roomID, "Weekend")
if err != nil {
log.Error("Unable to send thread root for Weekend")
return
}
currentStandupFlows[userID].WeekendThreadEvents = []mid.EventID{resp.EventID}
} else {
resp, err = sendThreadRootMessage(roomID, "Yesterday")
if err != nil {
log.Error("Unable to send thread root for Yesterday")
return
}
currentStandupFlows[userID].YesterdayThreadEvents = []mid.EventID{resp.EventID}
}
resp, err = sendThreadRootMessage(roomID, "Today")
if err != nil {
log.Error("Unable to send thread root for Today")
return
}
currentStandupFlows[userID].TodayThreadEvents = []mid.EventID{resp.EventID}
resp, err = sendThreadRootMessage(roomID, "Blockers")
if err != nil {
log.Error("Unable to send thread root for Blockers")
return
}
currentStandupFlows[userID].BlockersThreadEvents = []mid.EventID{resp.EventID}
resp, err = sendThreadRootMessage(roomID, "Notes")
if err != nil {
log.Error("Unable to send thread root for Notes")
return
}
currentStandupFlows[userID].NotesThreadEvents = []mid.EventID{resp.EventID}
// Show the preview
ShowMessagePreview(roomID, userID, currentStandupFlows[userID], false)
}
}
func CreatePost(roomID mid.RoomID, userID mid.UserID) {
stateKey := strings.TrimPrefix(userID.String(), "@")
var previousPostEventContent PreviousPostEventContent
err := client.StateEvent(roomID, StatePreviousPost, stateKey, &previousPostEventContent)
if err != nil {
log.Debug("Couldn't find previous post info.")
} else {
log.Debug("Found previous post info ", previousPostEventContent)
}
useThreads, _ := stateStore.GetUseThreads(userID)
var nextState StandupFlowState
if useThreads {
nextState = Threads
if stateStore.GetCurrentWeekdayInUserTimezone(userID) == time.Monday {
nextState = ThreadsFriday
}
} else {
nextState = Yesterday
if stateStore.GetCurrentWeekdayInUserTimezone(userID) == time.Monday {
nextState = Friday
}
}
GoToStateAndNotify(roomID, userID, nextState)
}
func formatList(items []StandupItem) (string, string) {
plain := make([]string, 0)
html := make([]string, 0)
for _, item := range items {
plain = append(plain, fmt.Sprintf("- %s", item.Body))
if item.FormattedBody == "" {
item.FormattedBody = item.Body
}
html = append(html, fmt.Sprintf("<li>%s</li>", item.FormattedBody))
}
return strings.Join(plain, "\n"), strings.Join(html, "")
}
func FormatPost(userID mid.UserID, standupFlow *StandupFlow, preview bool, sendConfirmation bool, isEditOfExisting bool) *mevent.MessageEventContent {
postText := fmt.Sprintf(`%s's standup post:\n\n`, userID)
postHtml := fmt.Sprintf(`<a href="https://matrix.to/#/%s">%s</a>'s standup post:<br><br>`, userID, userID)
if len(standupFlow.Yesterday) > 0 {
plain, html := formatList(standupFlow.Yesterday)
postText += "**Yesterday**\n" + plain
postHtml += "<b>Yesterday</b><br><ul>" + html + "</ul>"
}
if len(standupFlow.Friday) > 0 {
plain, html := formatList(standupFlow.Friday)
postText += "\n**Friday**\n" + plain
postHtml += "<b>Friday</b><br><ul>" + html + "</ul>"
}
if len(standupFlow.Weekend) > 0 {
plain, html := formatList(standupFlow.Weekend)
postText += "\n**Weekend**\n" + plain
postHtml += "<b>Weekend</b><br><ul>" + html + "</ul>"
}
if len(standupFlow.Today) > 0 {
plain, html := formatList(standupFlow.Today)
postText += "\n**Today**\n" + plain
postHtml += "<b>Today</b><br><ul>" + html + "</ul>"
}
if len(standupFlow.Blockers) > 0 {
plain, html := formatList(standupFlow.Blockers)
postText += "\n**Blockers**\n" + plain
postHtml += "<b>Blockers</b><br><ul>" + html + "</ul>"
}
if len(standupFlow.Notes) > 0 {
plain, html := formatList(standupFlow.Notes)
postText += "\n**Notes**\n" + plain
postHtml += "<b>Notes</b><br><ul>" + html + "</ul>"
}
if preview {
postText = fmt.Sprintf("Standup post preview:\n----------------------------------------\n" + postText)
postHtml = fmt.Sprintf("<i>Standup post preview:</i><hr>" + postHtml)
}
if sendConfirmation {
if isEditOfExisting {
postText = fmt.Sprintf("%s\n----------------------------------------\nSend Edit (%s) or Cancel (%s)?", postText, CHECKMARK, RED_X)
postHtml = fmt.Sprintf("%s<hr><b>Send Edit (%s) or Cancel (%s)?</b>", postHtml, CHECKMARK, RED_X)
} else {
postText = fmt.Sprintf("%s\n----------------------------------------\nSend (%s) or Cancel (%s)?", postText, CHECKMARK, RED_X)
postHtml = fmt.Sprintf("%s<hr><b>Send (%s) or Cancel (%s)?</b>", postHtml, CHECKMARK, RED_X)
}
}
return &mevent.MessageEventContent{
MsgType: mevent.MsgText,
Body: postText,
Format: mevent.FormatHTML,
FormattedBody: postHtml,
}
}
func ShowMessagePreview(roomID mid.RoomID, userID mid.UserID, currentFlow *StandupFlow, isEditOfExisting bool) {
resp, err := SendMessage(roomID, FormatPost(userID, currentFlow, true, true, isEditOfExisting))
if err == nil {
SendReaction(roomID, resp.EventID, CHECKMARK)
SendReaction(roomID, resp.EventID, RED_X)
}
currentFlow.PreviewEventId = resp.EventID
currentStandupFlows[userID].ReactableEvents = append(currentStandupFlows[userID].ReactableEvents, resp.EventID)
}
func SendMessageToSendRoom(event *mevent.Event, currentFlow *StandupFlow, editEventID *mid.EventID) {
sendRoomID, err := stateStore.GetSendRoomId(event.Sender)
if err != nil {
content := format.RenderMarkdown("No send room set! Set one using `!standupbot room [room ID or alias]`.", true, false)
SendMessage(event.RoomID, &content)
return
}
found := false
for _, userID := range stateStore.GetRoomMembers(sendRoomID) {
if event.Sender == userID {
found = true
}
}
if !found {
content := format.RenderMarkdown(fmt.Sprintf("**You are not a member of the configured send room!** Refusing to send a message to the room. Set a new one using `!standupbot room [room ID or alias]`."), true, false)
SendMessage(event.RoomID, &content)
return
}
newPost := FormatPost(event.Sender, currentFlow, false, false, false)
var futureEditId mid.EventID
var sent *mautrix.RespSendEvent
editStr := ""
if editEventID != nil {
_, err = SendMessageOnBehalfOf(&event.Sender, sendRoomID, &mevent.MessageEventContent{
MsgType: mevent.MsgText,
Body: " * " + newPost.Body,
Format: mevent.FormatHTML,
FormattedBody: " * " + newPost.FormattedBody,
RelatesTo: &mevent.RelatesTo{
Type: mevent.RelReplace,
EventID: *editEventID,
},
NewContent: newPost,
})
editStr = " edit"
futureEditId = *editEventID
} else {
sent, err = SendMessageOnBehalfOf(&event.Sender, sendRoomID, newPost)
if err == nil {
futureEditId = sent.EventID
}
}
if err != nil {
content := format.RenderMarkdown(fmt.Sprintf("Failed to send standup post%s to [%s](https://matrix.to/#/%s)", editStr, sendRoomID.String(), sendRoomID.String()), true, false)
SendMessage(event.RoomID, &content)
} else {
content := format.RenderMarkdown(fmt.Sprintf("Sent standup post%s to [%s](https://matrix.to/#/%s)", editStr, sendRoomID.String(), sendRoomID.String()), true, false)
content.MsgType = mevent.MsgNotice
SendMessage(event.RoomID, &content)
currentFlow.ResendEventId = nil
currentFlow.State = Sent
stateKey := strings.TrimPrefix(event.Sender.String(), "@")
_, err = client.SendStateEvent(event.RoomID, StatePreviousPost, stateKey, PreviousPostEventContent{
EditEventID: futureEditId,
FlowID: currentFlow.FlowID,
Day: stateStore.GetCurrentWeekdayInUserTimezone(event.Sender),
TodayItems: currentFlow.Today,
})
}
}
func HandleReaction(_ mautrix.EventSource, event *mevent.Event) {
reactionEventContent := event.Content.AsReaction()
currentFlow, found := currentStandupFlows[event.Sender]
if !found || currentFlow.State == FlowNotStarted {
return
}
found = false
for _, eventId := range currentFlow.ReactableEvents {
if reactionEventContent.RelatesTo.EventID == eventId {
found = true
break
}
}
if !found {
return
}
// Mark the reaction as read after we've handled it.
defer client.MarkRead(event.RoomID, event.ID)
if reactionEventContent.RelatesTo.Key == CHECKMARK {
currentFlow.ReactableEvents = make([]mid.EventID, 0)
stateKey := strings.TrimPrefix(event.Sender.String(), "@")
var previousPostEventContent PreviousPostEventContent
stateEventErr := client.StateEvent(event.RoomID, StatePreviousPost, stateKey, &previousPostEventContent)
if stateEventErr == nil && currentFlow.FlowID == previousPostEventContent.FlowID {
if currentFlow.State != Sent {
// this means that we have already gone through the flow, sent the message, then went back to edit.
client.RedactEvent(event.RoomID, currentFlow.PreviewEventId)
ShowMessagePreview(event.RoomID, event.Sender, currentFlow, false)
currentFlow.State = Sent
return
}
} else if currentFlow.PreviewEventId.String() != "" {
if currentFlow.State != Confirm && currentFlow.State != Sent && currentFlow.State != Threads && currentFlow.State != ThreadsFriday {
// this means we have already gone through the flow, and we went back to edit.
client.RedactEvent(event.RoomID, currentFlow.PreviewEventId)
currentFlow.State = Notes
}
}
switch currentFlow.State {
case Yesterday:
GoToStateAndNotify(event.RoomID, event.Sender, Today)
break
case Friday:
GoToStateAndNotify(event.RoomID, event.Sender, Weekend)
break
case Weekend:
GoToStateAndNotify(event.RoomID, event.Sender, Today)
break
case Today:
GoToStateAndNotify(event.RoomID, event.Sender, Blockers)
break
case Blockers:
GoToStateAndNotify(event.RoomID, event.Sender, Notes)
break
case Notes:
ShowMessagePreview(event.RoomID, event.Sender, currentFlow, false)
currentFlow.State = Confirm
return
case Threads, ThreadsFriday, Confirm:
SendMessageToSendRoom(event, currentFlow, nil)
return
case Sent:
if stateEventErr != nil {
SendMessage(event.RoomID, &mevent.MessageEventContent{
MsgType: mevent.MsgText,
Body: "No previous post info found!",
})
currentFlow = BlankStandupFlow()
return
}
SendMessageToSendRoom(event, currentFlow, &previousPostEventContent.EditEventID)
return
}
} else if reactionEventContent.RelatesTo.Key == RED_X {
if currentFlow.State == Confirm || currentFlow.State == Sent {
currentStandupFlows[event.Sender] = BlankStandupFlow()
SendMessage(event.RoomID, &mevent.MessageEventContent{MsgType: mevent.MsgNotice, Body: "Standup post cancelled"})
}
}
}