generated from mattermost/mattermost-plugin-starter-template
-
Notifications
You must be signed in to change notification settings - Fork 25
/
daily_summary.go
287 lines (241 loc) · 7.95 KB
/
daily_summary.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
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
// See License for license information.
package mscalendar
import (
"fmt"
"time"
"github.com/pkg/errors"
"github.com/mattermost/mattermost-plugin-mscalendar/server/mscalendar/views"
"github.com/mattermost/mattermost-plugin-mscalendar/server/remote"
"github.com/mattermost/mattermost-plugin-mscalendar/server/store"
"github.com/mattermost/mattermost-plugin-mscalendar/server/utils/bot"
"github.com/mattermost/mattermost-plugin-mscalendar/server/utils/tz"
)
const dailySummaryTimeWindow = time.Minute * 2
// Run daily summary job every 15 minutes
const DailySummaryJobInterval = 15 * time.Minute
type DailySummary interface {
GetDaySummaryForUser(now time.Time, user *User) (string, error)
GetDailySummarySettingsForUser(user *User) (*store.DailySummaryUserSettings, error)
SetDailySummaryPostTime(user *User, timeStr string) (*store.DailySummaryUserSettings, error)
SetDailySummaryEnabled(user *User, enable bool) (*store.DailySummaryUserSettings, error)
ProcessAllDailySummary(now time.Time) error
}
func (m *mscalendar) GetDailySummarySettingsForUser(user *User) (*store.DailySummaryUserSettings, error) {
err := m.Filter(withUserExpanded(user))
if err != nil {
return nil, err
}
return user.Settings.DailySummary, nil
}
func (m *mscalendar) SetDailySummaryPostTime(user *User, timeStr string) (*store.DailySummaryUserSettings, error) {
err := m.Filter(withUserExpanded(user))
if err != nil {
return nil, err
}
t, err := time.Parse(time.Kitchen, timeStr)
if err != nil {
return nil, errors.New("Invalid time value: " + timeStr)
}
if t.Minute()%int(DailySummaryJobInterval/time.Minute) != 0 {
return nil, fmt.Errorf("time must be a multiple of %d minutes", DailySummaryJobInterval/time.Minute)
}
timezone, err := m.GetTimezone(user)
if err != nil {
return nil, err
}
if user.Settings.DailySummary == nil {
user.Settings.DailySummary = store.DefaultDailySummaryUserSettings()
}
dsum := user.Settings.DailySummary
dsum.PostTime = timeStr
dsum.Timezone = timezone
err = m.Store.StoreUser(user.User)
if err != nil {
return nil, err
}
return dsum, nil
}
func (m *mscalendar) SetDailySummaryEnabled(user *User, enable bool) (*store.DailySummaryUserSettings, error) {
err := m.Filter(withUserExpanded(user))
if err != nil {
return nil, err
}
if user.Settings.DailySummary == nil {
user.Settings.DailySummary = store.DefaultDailySummaryUserSettings()
}
dsum := user.Settings.DailySummary
dsum.Enable = enable
err = m.Store.StoreUser(user.User)
if err != nil {
return nil, err
}
return dsum, nil
}
func (m *mscalendar) ProcessAllDailySummary(now time.Time) error {
userIndex, err := m.Store.LoadUserIndex()
if err != nil {
return err
}
if len(userIndex) == 0 {
return nil
}
err = m.Filter(withSuperuserClient)
if err != nil && !errors.Is(err, remote.ErrSuperUserClientNotSupported) {
return err
}
fetchIndividually := errors.Is(err, remote.ErrSuperUserClientNotSupported)
calendarViews := []*remote.ViewCalendarResponse{}
requests := []*remote.ViewCalendarParams{}
byRemoteID := map[string]*store.User{}
for _, user := range userIndex {
storeUser, storeErr := m.Store.LoadUser(user.MattermostUserID)
if storeErr != nil {
m.Logger.Warnf("Error loading user %s for daily summary. err=%v", storeUser.MattermostUserID, storeErr)
continue
}
byRemoteID[storeUser.Remote.ID] = storeUser
dsum := storeUser.Settings.DailySummary
if dsum == nil {
continue
}
shouldPost, shouldPostErr := shouldPostDailySummary(dsum, now)
if shouldPostErr != nil {
m.Logger.Warnf("Error posting daily summary for user %s. err=%v", storeUser.MattermostUserID, shouldPostErr)
continue
}
if !shouldPost {
continue
}
if fetchIndividually {
u := NewUser(storeUser.MattermostUserID)
if err := m.ExpandUser(u); err != nil {
m.Logger.With(bot.LogContext{
"mattermost_id": storeUser.MattermostUserID,
"remote_id": storeUser.Remote.ID,
"err": err,
}).Errorf("error getting user information")
continue
}
engine, err := m.FilterCopy(withActingUser(storeUser.MattermostUserID))
if err != nil {
m.Logger.Errorf("Error creating user engine %s. err=%v", storeUser.MattermostUserID, err)
continue
}
tz, err := engine.GetTimezone(u)
if err != nil {
m.Logger.Errorf("Error posting daily summary for user %s. err=%v", storeUser.MattermostUserID, err)
continue
}
events, err := engine.getTodayCalendarEvents(u, now, tz)
if err != nil {
m.Logger.Errorf("Error posting daily summary for user %s. err=%v", storeUser.MattermostUserID, err)
continue
}
calendarViews = append(calendarViews, &remote.ViewCalendarResponse{
Error: nil,
RemoteUserID: storeUser.Remote.ID,
Events: events,
})
} else {
start, end := getTodayHoursForTimezone(now, dsum.Timezone)
req := &remote.ViewCalendarParams{
RemoteUserID: storeUser.Remote.ID,
StartTime: start,
EndTime: end,
}
requests = append(requests, req)
}
}
if !fetchIndividually {
var err error
calendarViews, err = m.client.DoBatchViewCalendarRequests(requests)
if err != nil {
return err
}
}
for _, res := range calendarViews {
user := byRemoteID[res.RemoteUserID]
if res.Error != nil {
m.Logger.Warnf("Error rendering user %s calendar. err=%s %s", user.MattermostUserID, res.Error.Code, res.Error.Message)
}
dsum := user.Settings.DailySummary
if dsum == nil {
// Should never reach this point
continue
}
postStr, err := views.RenderCalendarView(res.Events, dsum.Timezone)
if err != nil {
m.Logger.Warnf("Error rendering user %s calendar. err=%v", user.MattermostUserID, err)
}
m.Poster.DM(user.MattermostUserID, postStr)
// REVIEW: Seems kind of pointless to track a passive event like this
m.Dependencies.Tracker.TrackDailySummarySent(user.MattermostUserID)
dsum.LastPostTime = time.Now().Format(time.RFC3339)
err = m.Store.StoreUser(user)
if err != nil {
m.Logger.Warnf("Error storing daily summary LastPostTime for user %s. err=%v", user.MattermostUserID, err)
}
}
m.Logger.Infof("Processed daily summary for %d users", len(calendarViews))
return nil
}
func (m *mscalendar) GetDaySummaryForUser(day time.Time, user *User) (string, error) {
tz, err := m.GetTimezone(user)
if err != nil {
return "", err
}
calendarData, err := m.getTodayCalendarEvents(user, day, tz)
if err != nil {
return "Failed to get calendar events", err
}
messageString, err := views.RenderCalendarView(calendarData, tz)
if err != nil {
return "", errors.Wrap(err, "failed to render daily summary")
}
return messageString, nil
}
func shouldPostDailySummary(dsum *store.DailySummaryUserSettings, now time.Time) (bool, error) {
if dsum == nil || !dsum.Enable {
return false, nil
}
lastPostStr := dsum.LastPostTime
if lastPostStr != "" {
lastPost, err := time.Parse(time.RFC3339, lastPostStr)
if err != nil {
return false, errors.New("Failed to parse last post time: " + lastPostStr)
}
since := now.Sub(lastPost)
if since < dailySummaryTimeWindow {
return false, nil
}
}
timezone := tz.Go(dsum.Timezone)
if timezone == "" {
return false, errors.New("invalid timezone")
}
loc, err := time.LoadLocation(timezone)
if err != nil {
return false, err
}
t, err := time.ParseInLocation(time.Kitchen, dsum.PostTime, loc)
if err != nil {
return false, err
}
now = now.In(loc)
if now.Weekday() == time.Saturday || now.Weekday() == time.Sunday {
return false, nil
}
t = time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), 0, 0, loc)
diff := now.Sub((t))
if diff >= 0 {
return diff < dailySummaryTimeWindow, nil
}
return -diff < dailySummaryTimeWindow, nil
}
func getTodayHoursForTimezone(now time.Time, timezone string) (start, end time.Time) {
t := remote.NewDateTime(now.UTC(), "UTC").In(timezone).Time()
start = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
end = start.Add(24 * time.Hour)
return start, end
}