forked from cert-lv/graphoscope
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notifications.go
87 lines (72 loc) · 1.86 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
package main
import (
"time"
)
/*
* Structure of one Web UI notification
*/
type Notification struct {
// Type of notification.
// Currently possible values: "err", "info"
Type string `bson:"type" json:"type"`
// Message text
Message string `bson:"message" json:"message"`
// Timestamp of the creation time
Ts string `bson:"ts" json:"ts"`
}
/*
* Add new notification to the user.
*
* If user is online - notification will be received in a browser,
* If offline - it will be stored in a database.
*
* Receives its type and message text
*/
func (a *Account) addNotification(typ, message string) {
n := &Notification{
Type: typ,
Message: message,
Ts: time.Now().Format("2 Jan 2006 15:04:05"),
}
// Check whether user is online first
if a.Session != nil {
a.send("notification", message, typ)
return
}
// Store the notification in a database otherwise
a.Notifications = append(a.Notifications, n)
// Leave the last 5 notifications only
if len(a.Notifications) > 5 {
a.Notifications = a.Notifications[len(a.Notifications)-5:]
}
err := a.update("notifications", a.Notifications)
if err != nil {
log.Error().
Str("username", a.Username).
Msg("Can't add a notification to the user: " + err.Error())
}
log.Info().
Str("ip", a.Session.IP).
Str("username", a.Username).
Msg("Notification added")
}
/*
* Handle 'notifications' websocket command
* to clean user's notifications
*/
func (a *Account) notificationsHandler() {
a.Notifications = []*Notification{}
err := a.update("notifications", a.Notifications)
if err != nil {
log.Error().
Str("ip", a.Session.IP).
Str("username", a.Username).
Msg("Can't clean notifications: " + err.Error())
a.send("error", err.Error(), "Can't clean notifications!")
return
}
log.Info().
Str("ip", a.Session.IP).
Str("username", a.Username).
Msg("Notifications cleaned")
}