-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdb.go
242 lines (203 loc) · 5.8 KB
/
db.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
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
package main
import (
"os"
"path/filepath"
log "github.com/Sirupsen/logrus"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"gopkg.in/qml.v1"
)
var (
db *sqlx.DB
dbDir string
dbFile string
sessionsSchema = "CREATE TABLE IF NOT EXISTS sessions (id INTEGER PRIMARY KEY, name text, tel text, isgroup boolean, last string, timestamp integer, ctype integer, unread integer default 0)"
sessionsInsert = "INSERT OR REPLACE INTO sessions (name, tel, isgroup, last, ctype, timestamp) VALUES (:name, :tel, :isgroup, :last, :ctype, :timestamp)"
sessionsSelect = "SELECT * FROM sessions ORDER BY timestamp DESC"
messagesSchema = "CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, sid integer, source text, message text, outgoing boolean, sentat integer, receivedat integer, ctype integer, attachment string, issent boolean, isread boolean, flags integer default 0)"
messagesInsert = "INSERT INTO messages (sid, source, message, outgoing, sentat, receivedat, ctype, attachment, issent, isread, flags) VALUES (:sid, :source, :message, :outgoing, :sentat, :receivedat, :ctype, :attachment, :issent, :isread, :flags)"
messagesSelectWhere = "SELECT * FROM messages WHERE sid = ?"
groupsSchema = "CREATE TABLE IF NOT EXISTS groups (id INTEGER PRIMARY KEY, groupid TEXT, name TEXT, members TEXT, avatar BLOB, avatarid INTEGER, avatar_key BLOB, avatar_content_type TEXT, relay TEXT, active INTEGER DEFAULT 1)"
groupsInsert = "INSERT OR REPLACE INTO groups (groupid, name, members, avatar) VALUES (:groupid, :name, :members, :avatar)"
groupsUpdate = "UPDATE groups SET members = :members, name = :name, avatar = :avatar, active = :active WHERE groupid = :groupid"
groupsSelect = "SELECT groupid, name, members, avatar, active FROM groups"
groupsDelete = "DELETE FROM groups WHERE groupid = ?"
)
func setupDB() error {
var err error
dbDir = filepath.Join(dataDir, "db")
dbFile = filepath.Join(dbDir, "db.sql")
err = os.MkdirAll(dbDir, 0700)
if err != nil {
return err
}
db, err = sqlx.Open("sqlite3", dbFile)
if err != nil {
return err
}
_, err = db.Exec(messagesSchema)
if err != nil {
return err
}
_, err = db.Exec(sessionsSchema)
if err != nil {
return err
}
_, err = db.Exec(groupsSchema)
if err != nil {
return err
}
migrations()
return loadMessagesFromDB()
}
func saveSession(s *Session) error {
res, err := db.NamedExec(sessionsInsert, s)
if err != nil {
return err
}
id, err := res.LastInsertId()
if err != nil {
return err
}
s.ID = id
return err
}
func saveGroup(g *GroupRecord) error {
res, err := db.NamedExec(groupsInsert, g)
if err != nil {
return err
}
id, err := res.LastInsertId()
if err != nil {
return err
}
g.ID = id
return nil
}
func saveMessage(m *Message) error {
res, err := db.NamedExec(messagesInsert, m)
if err != nil {
return err
}
id, err := res.LastInsertId()
if err != nil {
return err
}
m.ID = id
return nil
}
func updateMessageSent(m *Message) error {
_, err := db.NamedExec("UPDATE messages SET issent = :issent, sentat = :sentat WHERE id = :id", m)
if err != nil {
return err
}
return err
}
func updateMessageRead(m *Message) error {
_, err := db.NamedExec("UPDATE messages SET isread = :isread WHERE id = :id", m)
if err != nil {
return err
}
return err
}
func updateSession(s *Session) error {
_, err := db.NamedExec("UPDATE sessions SET name = :name, timestamp = :timestamp, ctype = :ctype, last = :last, unread = :unread WHERE id = :id", s)
if err != nil {
return err
}
return err
}
func updateGroup(g *GroupRecord) error {
_, err := db.NamedExec(groupsUpdate, g)
if err != nil {
return err
}
return err
}
func deleteGroup(hexid string) error {
_, err := db.Exec(groupsDelete, hexid)
return err
}
var allSessions []*Session
var allGroups []*GroupRecord
func loadMessagesFromDB() error {
err := db.Select(&allGroups, groupsSelect)
if err != nil {
return err
}
for _, g := range allGroups {
groups[g.GroupID] = g
}
err = db.Select(&allSessions, sessionsSelect)
if err != nil {
return err
}
for _, s := range allSessions {
s.When = humanizeTimestamp(s.Timestamp)
s.Active = !s.IsGroup || (groups[s.Tel] != nil && groups[s.Tel].Active)
sessionsModel.sessions = append(sessionsModel.sessions, s)
sessionsModel.Len++
err = db.Select(&s.messages, messagesSelectWhere, s.ID)
s.Len = len(s.messages)
if err != nil {
return err
}
for _, m := range s.messages {
m.HTime = humanizeTimestamp(m.SentAt)
}
}
return nil
}
func deleteSession(tel string) error {
s := sessionsModel.Get(tel)
_, err := db.Exec("DELETE FROM messages WHERE sid = ?", s.ID)
if err != nil {
return err
}
_, err = db.Exec("DELETE FROM sessions WHERE id = ?", s.ID)
if err != nil {
return err
}
index := sessionsModel.GetIndex(s.Tel)
sessionsModel.sessions = append(sessionsModel.sessions[:index], sessionsModel.sessions[index+1:]...)
sessionsModel.Len--
qml.Changed(sessionsModel, &sessionsModel.Len)
return nil
}
func deleteMessage(id int64) error {
_, err := db.Exec("DELETE FROM messages WHERE id = ?", id)
return err
}
func addFlagsColumnToMessages() error {
_, err := db.Exec("ALTER TABLE messages ADD COLUMN flags INTEGER DEFAULT 0")
return err
}
func addUnreadColumnToSessions() error {
_, err := db.Exec("ALTER TABLE sessions ADD COLUMN unread INTEGER DEFAULT 0")
return err
}
func migrateOnce(name string, f func()) error {
path := filepath.Join(dbDir, "migrated_to_"+name)
if !exists(path) {
f()
}
_, err := os.Create(path)
return err
}
// Columns messages.flags and sessions.unread were introduced in 0.3.7
func migrate_to_0_3_7() {
err := addFlagsColumnToMessages()
if err != nil {
log.Println(err)
}
err = addUnreadColumnToSessions()
if err != nil {
log.Println(err)
}
}
func migrations() {
err := migrateOnce("0_3_7", migrate_to_0_3_7)
if err != nil {
log.Println(err)
}
}