This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 283
/
offinemessages.go
92 lines (81 loc) · 1.86 KB
/
offinemessages.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
package db
import (
"database/sql"
"sync"
"time"
"github.com/OpenBazaar/openbazaar-go/repo"
)
type OfflineMessagesDB struct {
modelStore
}
func NewOfflineMessageStore(db *sql.DB, lock *sync.Mutex) repo.OfflineMessageStore {
return &OfflineMessagesDB{modelStore{db, lock}}
}
func (o *OfflineMessagesDB) Put(url string) error {
o.lock.Lock()
defer o.lock.Unlock()
tx, err := o.db.Begin()
if err != nil {
return err
}
stmt, err := tx.Prepare("insert into offlinemessages(url, timestamp) values(?,?)")
if err != nil {
return err
}
defer stmt.Close()
_, err = stmt.Exec(url, int(time.Now().Unix()))
if err != nil {
tx.Rollback()
return err
}
tx.Commit()
return nil
}
func (o *OfflineMessagesDB) Has(url string) bool {
o.lock.Lock()
defer o.lock.Unlock()
stmt, err := o.db.Prepare("select url from offlinemessages where url=?")
if err != nil {
return false
}
defer stmt.Close()
var ret string
err = stmt.QueryRow(url).Scan(&ret)
return err == nil
}
func (o *OfflineMessagesDB) SetMessage(url string, message []byte) error {
o.lock.Lock()
defer o.lock.Unlock()
_, err := o.db.Exec("update offlinemessages set message=? where url=?", message, url)
if err != nil {
return err
}
return nil
}
func (o *OfflineMessagesDB) GetMessages() (map[string][]byte, error) {
o.lock.Lock()
defer o.lock.Unlock()
stm := "select url, message from offlinemessages where message is not null"
ret := make(map[string][]byte)
rows, err := o.db.Query(stm)
if err != nil {
return ret, err
}
defer rows.Close()
for rows.Next() {
var url string
var message []byte
rows.Scan(&url, &message)
ret[url] = message
}
return ret, nil
}
func (o *OfflineMessagesDB) DeleteMessage(url string) error {
o.lock.Lock()
defer o.lock.Unlock()
_, err := o.db.Exec("update offlinemessages set message=null where url=?", url)
if err != nil {
return err
}
return nil
}