-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotifications.go
More file actions
300 lines (258 loc) · 7.63 KB
/
notifications.go
File metadata and controls
300 lines (258 loc) · 7.63 KB
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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"maps"
"net/http"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
func getNotifications(c *gin.Context) {
user := c.MustGet("user").(*User)
timePeriod := 1
if timePeriodStr := c.Query("after"); timePeriodStr != "" {
if parsed, err := strconv.Atoi(timePeriodStr); err == nil && parsed >= 1 {
timePeriod = parsed
} else {
c.JSON(400, gin.H{"error": "Invalid time period"})
return
}
}
userId := user.GetId()
currentTime := time.Now().UnixMilli()
cutoffTime := currentTime - int64(timePeriod*24*60*60*1000)
notifications := make([]map[string]any, 0)
eventsHistoryMutex.RLock()
userEvents, exists := eventsHistory[userId]
eventsHistoryMutex.RUnlock()
if exists {
for _, event := range userEvents {
if event.Timestamp >= cutoffTime {
notification := map[string]any{
"type": event.Type,
"id": event.ID,
"timestamp": event.Timestamp,
}
maps.Copy(notification, event.Data)
notifications = append(notifications, notification)
}
}
}
sort.Slice(notifications, func(i, j int) bool {
return notifications[i]["timestamp"].(int64) > notifications[j]["timestamp"].(int64)
})
c.JSON(200, notifications)
}
func makeHTTPRequest(method, url string, payload any, timeout time.Duration, logPrefix string, expectedStatusCode int) bool {
jsonData, err := json.Marshal(payload)
if err != nil {
log.Printf("[%s] Error marshaling payload: %v", logPrefix, err)
return false
}
isRetryableNetErr := func(e error) bool {
if e == nil {
return false
}
s := strings.ToLower(e.Error())
return strings.Contains(s, "connection reset") ||
strings.Contains(s, "connection refused") ||
strings.Contains(s, "server closed idle connection") ||
strings.Contains(s, "broken pipe") ||
strings.Contains(s, "eof")
}
maxAttempts := 4 // initial try + 3 retries
for attempt := 1; attempt <= maxAttempts; attempt++ {
client := &http.Client{Timeout: timeout}
var resp *http.Response
switch method {
case "POST":
resp, err = client.Post(url, "application/json", bytes.NewBuffer(jsonData))
case "PATCH":
req, reqErr := http.NewRequest("PATCH", url, bytes.NewBuffer(jsonData))
if reqErr != nil {
log.Printf("[%s] Error creating %s request: %v", logPrefix, method, reqErr)
return false
}
req.Header.Set("Content-Type", "application/json")
resp, err = client.Do(req)
default:
log.Printf("[%s] Unsupported HTTP method: %s", logPrefix, method)
return false
}
if err != nil {
if attempt < maxAttempts && isRetryableNetErr(err) {
// Backoff: 200ms, 400ms, 800ms
backoff := time.Duration(200*(1<<(attempt-1))) * time.Millisecond
time.Sleep(backoff)
continue
}
log.Printf("[%s] Error sending %s request after %d attempt(s): %v", logPrefix, method, attempt, err)
return false
}
defer resp.Body.Close()
if resp.StatusCode == expectedStatusCode {
return true
}
// Status-code failures generally aren't transient; don't spam retries.
log.Printf("[%s] Request failed with status: %d", logPrefix, resp.StatusCode)
return false
}
return false
}
func createEventPayload(eventType string, data any) map[string]any {
return map[string]any{
"event_type": eventType,
"data": data,
"from": "rotur",
}
}
func broadcastClawEvent(eventType string, data any) bool {
payload := createEventPayload(eventType, data)
return makeHTTPRequest("POST", WEBSOCKET_SERVER_URL, payload, 2*time.Second, "WebSocket", 200)
}
func sendPostToDiscord(postData NetPost) {
username := postData.User
if username == "" {
username = "Unknown User"
}
webhookData := map[string]any{
"username": username,
"avatar_url": fmt.Sprintf("https://avatars.rotur.dev/%s", username),
"content": postData.Content,
}
success := makeHTTPRequest("POST", DISCORD_WEBHOOK_URL, webhookData, 5*time.Second, "Discord", 204)
if success {
log.Printf("[Discord] Post %s sent to Discord successfully", postData.ID)
}
}
func sendReportToDiscord(reportData string) {
webhookData := map[string]any{
"username": "Rotur",
"avatar_url": "https://avatars.rotur.dev/rotur",
"content": "<@603952506330021898> Reported: " + reportData,
}
success := makeHTTPRequest("POST", DISCORD_WEBHOOK_URL, webhookData, 5*time.Second, "Discord", 204)
if success {
log.Printf("[Discord] Report sent to Discord successfully")
}
}
func notify(eventType string, data any) bool {
payload := createEventPayload(eventType, data)
success := makeHTTPRequest("POST", EVENT_SERVER_URL, payload, 5*time.Second, "Event", 200)
if success {
log.Printf("[Event] Event %s sent to Event server successfully", eventType)
}
return success
}
// patchUserUpdate makes a PATCH request to /users endpoint for user updates
func patchUserUpdate(username Username, key string, value any) bool {
// Find the user's auth key
usersMutex.RLock()
var authKey string
for _, user := range users {
if user.GetUsername().ToLower() == username {
authKey = user.GetKey()
break
}
}
usersMutex.RUnlock()
if authKey == "" {
log.Printf("[PatchUpdate] User %s not found or has no auth key", username)
return false
}
payload := map[string]any{
"auth": authKey,
"key": key,
"value": value,
}
envOnce.Do(loadEnvFile)
ADMIN_TOKEN := os.Getenv("ADMIN_TOKEN")
// Avatar/banner uploads may take several seconds; allow up to 15s
success := makeHTTPRequest("PATCH", "http://localhost:5602/users?token="+ADMIN_TOKEN, payload, 15*time.Second, "PatchUpdate", 200)
if success {
log.Printf("[PatchUpdate] User %s key %s updated successfully via PATCH", username, key)
return broadcastUserUpdate(username, key, value)
}
return false
}
func broadcastUserUpdate(username Username, key string, value any) bool {
mu := getUserMutex(username)
mu.Lock()
defer mu.Unlock()
payload := createEventPayload("user_account_update", map[string]any{
"username": username,
"key": key,
"value": value,
"rotur": username,
})
success := makeHTTPRequest("POST", EVENT_SERVER_URL, payload, 2*time.Second, "UserUpdate", 200)
return success
}
func getPostRepliesSnapshot(postID string) []Reply {
postsMutex.RLock()
defer postsMutex.RUnlock()
for i := range posts {
if posts[i].ID == postID {
if posts[i].Replies == nil {
return nil
}
out := make([]Reply, len(posts[i].Replies))
copy(out, posts[i].Replies)
return out
}
}
return nil
}
func addUserEvent(userId UserId, eventType string, data map[string]any) Event {
switch eventType {
case "follow":
followersCount := 0
switch v := data["followers"].(type) {
case []string:
followersCount = len(v)
case []any:
followersCount = len(v)
}
go broadcastClawEvent("followers", map[string]any{
"username": userId.User().GetUsername(),
"followers": followersCount,
})
case "reply":
postID, _ := data["post_id"].(string)
if postID != "" {
replies := getPostRepliesSnapshot(postID)
netReplies := make([]NetReply, 0)
for _, reply := range replies {
netReplies = append(netReplies, reply.ToNet())
}
go broadcastClawEvent("update_post", map[string]any{
"id": postID,
"key": "replies",
"data": netReplies,
})
}
}
eventsHistoryMutex.Lock()
defer eventsHistoryMutex.Unlock()
if eventsHistory[userId] == nil {
eventsHistory[userId] = make([]Event, 0)
}
newEvent := Event{
Type: eventType,
Data: data,
Timestamp: time.Now().UnixMilli(),
ID: generateShortToken(),
}
eventsHistory[userId] = append(eventsHistory[userId], newEvent)
if len(eventsHistory[userId]) > 100 {
eventsHistory[userId] = eventsHistory[userId][len(eventsHistory[userId])-100:]
}
go saveEventsHistory()
return newEvent
}