-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Database.go
350 lines (308 loc) · 8.37 KB
/
Database.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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package legacydb
import (
"bytes"
"encoding/binary"
"encoding/gob"
"fmt"
"git.mills.io/prologic/bitcask"
"github.com/forceu/gokapi/internal/helper"
"github.com/forceu/gokapi/internal/models"
"log"
"strings"
"time"
)
const prefixApiKey = "apikey:id:"
const prefixFile = "file:id:"
const prefixHotlink = "hotlink:id:"
const prefixSessions = "session:id:"
const prefixUploadStatus = "fstatus:id:"
const idLastUploadConfig = "default:lastupload"
const idEnd2EndInfo = "e2e:info"
const maxKeySize = 96
var bitcaskDb *bitcask.Bitcask
// Init creates the database files and connects to it
// Deprecated: Package will be removed with 1.9
func Init(dbPath string) {
if bitcaskDb == nil {
db, err := bitcask.Open(dbPath, bitcask.WithMaxKeySize(maxKeySize))
if err != nil {
log.Fatal(err)
}
bitcaskDb = db
}
}
// GetLengthAvailable returns the maximum length for a key name
func GetLengthAvailable() int {
maxLength := 0
for _, key := range []string{prefixApiKey, prefixFile, prefixHotlink, prefixSessions} {
length := len(key)
if length > maxLength {
maxLength = length
}
}
return maxKeySize - maxLength
}
// Close syncs the database to the filesystem and closes it
func Close() {
if bitcaskDb != nil {
err := bitcaskDb.Sync()
if err != nil {
fmt.Println(err)
}
err = bitcaskDb.Close()
if err != nil {
fmt.Println(err)
}
}
bitcaskDb = nil
}
// ## File Metadata ##
// GetAllMetadata returns a map of all available files
func GetAllMetadata() map[string]models.File {
if bitcaskDb == nil {
panic("Database not loaded!")
}
result := make(map[string]models.File)
keys := GetAllMetaDataIds()
for _, key := range keys {
file, ok := GetMetaDataById(key)
if ok {
result[file.Id] = file
}
}
return result
}
// GetAllMetaDataIds returns all Ids that contain metadata
func GetAllMetaDataIds() []string {
if bitcaskDb == nil {
panic("Database not loaded!")
}
var keys []string
err := bitcaskDb.Scan([]byte(prefixFile), func(key []byte) error {
fileId := strings.Replace(string(key), prefixFile, "", 1)
keys = append(keys, fileId)
return nil
})
helper.Check(err)
return keys
}
// GetMetaDataById returns a models.File from the ID passed or false if the id is not valid
func GetMetaDataById(id string) (models.File, bool) {
result := models.File{}
value, ok := getValue(prefixFile + id)
if !ok {
return result, false
}
buf := bytes.NewBuffer(value)
dec := gob.NewDecoder(buf)
err := dec.Decode(&result)
helper.Check(err)
return result, true
}
// SaveMetaData stores the metadata of a file to the disk
func SaveMetaData(file models.File) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(file)
helper.Check(err)
err = bitcaskDb.Put([]byte(prefixFile+file.Id), buf.Bytes())
helper.Check(err)
err = bitcaskDb.Sync()
helper.Check(err)
}
// DeleteMetaData deletes information about a file
func DeleteMetaData(id string) {
deleteKey(prefixFile + id)
}
// ## Hotlinks ##
// GetHotlink returns the id of the file associated or false if not found
func GetHotlink(id string) (string, bool) {
value, ok := getValue(prefixHotlink + id)
if !ok {
return "", false
}
return string(value), true
}
// SaveHotlink stores the hotlink associated with the file in the bitcaskDb
func SaveHotlink(file models.File) {
var err error
if file.UnlimitedTime {
err = bitcaskDb.Put([]byte(prefixHotlink+file.HotlinkId), []byte(file.Id))
} else {
err = bitcaskDb.PutWithTTL([]byte(prefixHotlink+file.HotlinkId), []byte(file.Id), expiryToDuration(file))
}
helper.Check(err)
err = bitcaskDb.Sync()
helper.Check(err)
}
// DeleteHotlink deletes a hotlink with the given ID
func DeleteHotlink(id string) {
deleteKey(prefixHotlink + id)
}
// ## API Keys ##
// GetAllApiKeys returns a map with all API keys
func GetAllApiKeys() map[string]models.ApiKey {
result := make(map[string]models.ApiKey)
var keys []string
err := bitcaskDb.Scan([]byte(prefixApiKey), func(key []byte) error {
apikeyID := strings.Replace(string(key), prefixApiKey, "", 1)
keys = append(keys, apikeyID)
return nil
})
helper.Check(err)
for _, key := range keys {
apiKey, ok := GetApiKey(key)
if ok {
result[apiKey.Id] = apiKey
}
}
return result
}
// GetApiKey returns a models.ApiKey if valid or false if the ID is not valid
func GetApiKey(id string) (models.ApiKey, bool) {
result := models.ApiKey{}
value, ok := getValue(prefixApiKey + id)
if !ok {
return result, false
}
buf := bytes.NewBuffer(value)
dec := gob.NewDecoder(buf)
err := dec.Decode(&result)
helper.Check(err)
return result, true
}
// SaveApiKey saves the API key to the database. If updateTimeOnly is true, the database might not be synced afterwards
func SaveApiKey(apikey models.ApiKey, updateTimeOnly bool) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(apikey)
helper.Check(err)
err = bitcaskDb.Put([]byte(prefixApiKey+apikey.Id), buf.Bytes())
helper.Check(err)
if !updateTimeOnly {
err = bitcaskDb.Sync()
helper.Check(err)
}
}
// DeleteApiKey deletes an API key with the given ID
func DeleteApiKey(id string) {
deleteKey(prefixApiKey + id)
}
// ## Sessions ##
// GetSession returns the session with the given ID or false if not a valid ID
func GetSession(id string) (models.Session, bool) {
result := models.Session{}
value, ok := getValue(prefixSessions + id)
if !ok {
return result, false
}
buf := bytes.NewBuffer(value)
dec := gob.NewDecoder(buf)
err := dec.Decode(&result)
helper.Check(err)
return result, true
}
// DeleteSession deletes a session with the given ID
func DeleteSession(id string) {
deleteKey(prefixSessions + id)
}
// DeleteAllSessions logs all users out
func DeleteAllSessions() {
err := bitcaskDb.SiftScan([]byte(prefixSessions), func(key []byte) (bool, error) {
return true, nil
})
helper.Check(err)
}
// SaveSession stores the given session. After the expiry passed, it will be deleted automatically
func SaveSession(id string, session models.Session, expiry time.Duration) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(session)
helper.Check(err)
err = bitcaskDb.PutWithTTL([]byte(prefixSessions+id), buf.Bytes(), expiry)
helper.Check(err)
err = bitcaskDb.Sync()
helper.Check(err)
}
// ## Upload Defaults ##
// GetUploadDefaults returns the last used setting for amount of downloads allowed, last expiry in days and
// a password for the file
func GetUploadDefaults() models.LastUploadValues {
defaultValues := models.LastUploadValues{
Downloads: 1,
TimeExpiry: 14,
Password: "",
UnlimitedDownload: false,
UnlimitedTime: false,
}
result := models.LastUploadValues{}
if bitcaskDb.Has([]byte(idLastUploadConfig)) {
value, err := bitcaskDb.Get([]byte(idLastUploadConfig))
helper.Check(err)
buf := bytes.NewBuffer(value)
dec := gob.NewDecoder(buf)
err = dec.Decode(&result)
helper.Check(err)
return result
}
return defaultValues
}
// SaveUploadDefaults saves the last used setting for an upload
func SaveUploadDefaults(values models.LastUploadValues) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(values)
helper.Check(err)
err = bitcaskDb.Put([]byte(idLastUploadConfig), buf.Bytes())
helper.Check(err)
}
// GetEnd2EndInfo retrieves the encrypted e2e info
func GetEnd2EndInfo() models.E2EInfoEncrypted {
result := models.E2EInfoEncrypted{}
value, ok := getValue(idEnd2EndInfo)
if !ok {
return result
}
buf := bytes.NewBuffer(value)
dec := gob.NewDecoder(buf)
err := dec.Decode(&result)
helper.Check(err)
result.AvailableFiles = GetAllMetaDataIds()
return result
}
// RunGarbageCollection runs the databases GC
func RunGarbageCollection() {
err := bitcaskDb.RunGC()
helper.Check(err)
}
func intToByte(integer int) []byte {
buf := make([]byte, binary.MaxVarintLen32)
n := binary.PutVarint(buf, int64(integer))
return buf[:n]
}
func byteToInt(intByte []byte) int {
integer, _ := binary.Varint(intByte)
return int(integer)
}
func deleteKey(id string) {
if !bitcaskDb.Has([]byte(id)) {
return
}
err := bitcaskDb.Delete([]byte(id))
helper.Check(err)
err = bitcaskDb.Sync()
helper.Check(err)
}
func getValue(id string) ([]byte, bool) {
value, err := bitcaskDb.Get([]byte(id))
if err == nil {
return value, true
}
if err == bitcask.ErrEmptyKey || err == bitcask.ErrKeyExpired || err == bitcask.ErrKeyNotFound {
return nil, false
}
panic(err)
}
func expiryToDuration(file models.File) time.Duration {
return time.Until(time.Unix(file.ExpireAt, 0))
}