forked from OpenBazaar/openbazaar-go
-
Notifications
You must be signed in to change notification settings - Fork 3
/
notifications.go
110 lines (99 loc) · 2.33 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
package db
import (
"database/sql"
"encoding/json"
"fmt"
notif "github.com/OpenBazaar/openbazaar-go/api/notifications"
"strconv"
"sync"
"time"
)
type NotficationsDB struct {
db *sql.DB
lock sync.RWMutex
}
func (n *NotficationsDB) Put(notification notif.Data, timestamp time.Time) error {
ser, err := json.Marshal(notification)
if err != nil {
return err
}
n.lock.Lock()
defer n.lock.Unlock()
tx, _ := n.db.Begin()
stmt, _ := tx.Prepare("insert into notifications(serializedNotification, timestamp, read) values(?,?,?)")
defer stmt.Close()
_, err = stmt.Exec(string(ser), int(timestamp.Unix()), 0)
if err != nil {
tx.Rollback()
return err
}
tx.Commit()
return nil
}
func (n *NotficationsDB) GetAll(offsetId int, limit int) []notif.Notification {
var ret []notif.Notification
n.lock.RLock()
defer n.lock.RUnlock()
var stm string
if offsetId > 0 {
stm = "select rowid, serializedNotification, timestamp, read from notifications where rowid<" + strconv.Itoa(offsetId) + " order by rowid desc limit " + strconv.Itoa(limit) + " ;"
} else {
stm = "select rowid, serializedNotification, timestamp, read from notifications order by timestamp desc limit " + strconv.Itoa(limit) + ";"
}
rows, err := n.db.Query(stm)
if err != nil {
return ret
}
for rows.Next() {
var notifId int
var data []byte
var timestampInt int
var readInt int
if err := rows.Scan(¬ifId, &data, ×tampInt, &readInt); err != nil {
fmt.Println(err)
continue
}
var read bool
if readInt == 1 {
read = true
}
timestamp := time.Unix(int64(timestampInt), 0)
var ni interface{}
err := json.Unmarshal(data, &ni)
if err != nil {
fmt.Println(err)
continue
}
n := notif.Notification{
ID: notifId,
Data: ni,
Timestamp: timestamp,
Read: read,
}
ret = append(ret, n)
}
return ret
}
func (n *NotficationsDB) MarkAsRead(notifID int) error {
n.lock.Lock()
defer n.lock.Unlock()
tx, err := n.db.Begin()
if err != nil {
return err
}
stmt, _ := tx.Prepare("update notifications set read=1 where rowid=?")
defer stmt.Close()
_, err = stmt.Exec(notifID)
if err != nil {
tx.Rollback()
return err
}
tx.Commit()
return nil
}
func (n *NotficationsDB) Delete(notifID int) error {
n.lock.Lock()
defer n.lock.Unlock()
n.db.Exec("delete from notifications where rowid=?", notifID)
return nil
}