-
Notifications
You must be signed in to change notification settings - Fork 1
/
notifications.go
217 lines (191 loc) · 7.19 KB
/
notifications.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
package main
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/vocdoni/vote-frame/imageframe"
"github.com/vocdoni/vote-frame/mongo"
"go.vocdoni.io/dvote/httprouter"
"go.vocdoni.io/dvote/httprouter/apirest"
"go.vocdoni.io/dvote/log"
"go.vocdoni.io/dvote/types"
"go.vocdoni.io/dvote/vochain/transaction/proofs/farcasterproof"
)
func (v *vocdoniHandler) notificationsHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
png := imageframe.NotificationsImage()
response := strings.ReplaceAll(frame(frameNotifications), "{image}", imageLink(png))
ctx.SetResponseContentType("text/html; charset=utf-8")
return ctx.Send([]byte(response), http.StatusOK)
}
func (v *vocdoniHandler) notificationsResponseHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
packet := &FrameSignaturePacket{}
if err := json.Unmarshal(msg.Data, packet); err != nil {
return fmt.Errorf("failed to unmarshal frame signature packet: %w", err)
}
messageBytes, err := hex.DecodeString(packet.TrustedData.MessageBytes)
if err != nil {
return fmt.Errorf("failed to decode message bytes: %w", err)
}
actionMessage, _, fid, err := farcasterproof.VerifyFrameSignature(messageBytes)
if err != nil {
return fmt.Errorf("failed to verify frame signature: %w", err)
}
if actionMessage.ButtonIndex == 3 {
// User has clicked the "filter by user" button
png := imageframe.NotificationsManageImage()
response := strings.ReplaceAll(frame(frameNotificationsManager), "{image}", imageLink(png))
ctx.SetResponseContentType("text/html; charset=utf-8")
return ctx.Send([]byte(response), http.StatusOK)
}
allowNotifications := actionMessage.ButtonIndex == 1
var png string
if err := v.db.SetNotificationsAcceptedForUser(fid, allowNotifications); err != nil {
return fmt.Errorf("failed to update notifications: %w", err)
}
log.Infow("notifications updated", "fid", fid, "allow", allowNotifications)
if allowNotifications {
png = imageframe.NotificationsAcceptedImage()
} else {
png = imageframe.NotificationsDeniedImage()
}
response := strings.ReplaceAll(frame(frameNotificationsResponse), "{image}", imageLink(png))
ctx.SetResponseContentType("text/html; charset=utf-8")
return ctx.Send([]byte(response), http.StatusOK)
}
func (v *vocdoniHandler) notificationsFilterByUserHandler(msg *apirest.APIdata, ctx *httprouter.HTTPContext) error {
packet := &FrameSignaturePacket{}
if err := json.Unmarshal(msg.Data, packet); err != nil {
return fmt.Errorf("failed to unmarshal frame signature packet: %w", err)
}
messageBytes, err := hex.DecodeString(packet.TrustedData.MessageBytes)
if err != nil {
return fmt.Errorf("failed to decode message bytes: %w", err)
}
actionMessage, _, fid, err := farcasterproof.VerifyFrameSignature(messageBytes)
if err != nil {
return fmt.Errorf("failed to verify frame signature: %w", err)
}
setErrorResponse := func(err error) []byte {
log.Warnw("failed to filter by user", "error", err)
png := imageframe.NotificationsErrorImage()
response := strings.ReplaceAll(frame(frameNotificationsResponse), "{image}", imageLink(png))
ctx.SetResponseContentType("text/html; charset=utf-8")
return []byte(response)
}
if len(actionMessage.InputText) == 0 {
return ctx.Send(setErrorResponse(fmt.Errorf("missing input text")), http.StatusOK)
}
// Get the filtered user by username from the database
user, err := v.db.UserByUsername(string(actionMessage.InputText))
if err != nil {
return ctx.Send(setErrorResponse(err), http.StatusOK)
}
allowNotifications := actionMessage.ButtonIndex == 1
if !allowNotifications {
if err := v.db.AddNotificationMutedUser(fid, user.UserID); err != nil {
return ctx.Send(setErrorResponse(err), http.StatusOK)
}
} else {
if err := v.db.DelNotificationMutedUser(fid, user.UserID); err != nil {
return ctx.Send(setErrorResponse(err), http.StatusOK)
}
}
var png string
log.Infow("notifications updated by user", "fid", fid, "filtered user", user.Username, "allow", allowNotifications)
if allowNotifications {
png = imageframe.NotificationsAcceptedImage()
} else {
png = imageframe.NotificationsDeniedImage()
}
response := strings.ReplaceAll(frame(frameNotificationsResponse), "{image}", imageLink(png))
ctx.SetResponseContentType("text/html; charset=utf-8")
return ctx.Send([]byte(response), http.StatusOK)
}
// notificationsForceSendHandler enqueue the notifications for the given election and its users.
// The election should be already created and the census stored in the database.
// Returns the list of usernames that will receive the notifications.
func (v *vocdoniHandler) notificationsSendHandler(_ *apirest.APIdata, ctx *httprouter.HTTPContext) error {
electionID, err := hex.DecodeString(ctx.URLParam("electionID"))
if err != nil {
return fmt.Errorf("failed to decode election ID: %w", err)
}
election, err := v.cli.Election(electionID)
if err != nil {
return fmt.Errorf("failed to get election: %w", err)
}
census, err := v.db.CensusFromElection(electionID)
if err != nil {
return fmt.Errorf("failed to get census: %w", err)
}
userProfile, err := v.db.User(census.CreatedBy)
if err != nil {
return fmt.Errorf("failed to get user profile: %w", err)
}
expiration := election.EndDate
if time.Until(expiration) < time.Hour*3 {
expiration = expiration.Add(-time.Minute * 10)
} else {
expiration = expiration.Add(-time.Hour * 3)
}
usernames := []string{}
for participant := range census.Participants {
usernames = append(usernames, participant)
}
if err := v.createNotifications(
electionID,
census.CreatedBy,
userProfile.Username,
usernames,
fmt.Sprintf("%s/%x", serverURL, electionID),
"",
expiration,
); err != nil {
return fmt.Errorf("failed to create notifications: %w", err)
}
data, err := json.Marshal(usernames)
if err != nil {
return fmt.Errorf("failed to marshal usernames: %w", err)
}
return ctx.Send(data, http.StatusOK)
}
// createNotifications creates a notification for each user in the census.
func (v *vocdoniHandler) createNotifications(electionID types.HexBytes, ownerFID uint64,
ownerName string, usernames []string, frameURL, customText string, deadline time.Time,
) error {
log.Infow("enqueue notifications",
"owner", ownerName,
"electionID", electionID.String(),
"userCount", len(usernames),
"frameURL", frameURL,
)
// Get the election from the database to get the community ID and name
election, err := v.db.Election(electionID)
if err != nil {
return fmt.Errorf("failed to get election: %w", err)
}
if election.Community == nil {
return fmt.Errorf("election has no community")
}
// Add a notification for each user in the census to the database
for _, username := range usernames {
user, err := v.db.UserByUsername(username)
if err != nil {
if errors.Is(err, mongo.ErrUserUnknown) {
log.Warnw("user not found", "username", username)
continue
}
return fmt.Errorf("failed to get user: %w", err)
}
if _, err := v.db.AddNotifications(mongo.NotificationTypeNewElection, electionID.String(),
user.UserID, ownerFID, election.Community.ID, username, ownerName, election.Community.Name,
frameURL, customText, deadline,
); err != nil {
return fmt.Errorf("failed to add notification: %w", err)
}
}
return nil
}