/
models.go
100 lines (82 loc) · 1.71 KB
/
models.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
)
var fileEntries = FileEntryDb{}
type (
FileEntryDb map[int64]FileEntry
)
// FileEntry represents a single uploaded file
type FileEntry struct {
Id int64
Name string
Size int64 // in bytes
UploadDate time.Time
}
func GetEntryById(id int64) FileEntry {
return fileEntries[id]
}
func GetFileEntries() []FileEntry {
var ret []FileEntry
for _, v := range fileEntries {
ret = append(ret, v)
}
return ret
}
func getNextId() int64 {
i := int64(0)
for j := range fileEntries {
i = max(i, j)
}
return i + 1
}
func HasFileEntry(id int64) bool {
_, ok := fileEntries[id]
return ok
}
func CreateFileEntry(filename string, filesize int64) FileEntry {
id := getNextId()
entry := FileEntry{
getNextId(),
filename,
filesize,
time.Now(),
}
fileEntries[id] = entry
return entry
}
func RemoveFileEntry(id int64) {
delete(fileEntries, id)
}
func (f *FileEntry) GetFilepath() string {
return filepath.Join(Config.FilesPath, i64ToStr(f.Id))
}
type View struct {
viewid int
files []FileEntry
token string
}
func loadFileEntries(path string) FileEntryDb {
file := panicOnErr(os.OpenFile(path, os.O_CREATE|os.O_RDONLY, 0644))
defer closeOrPanic(file)
var js []FileEntry
content := panicOnErr(ioutil.ReadAll(file))
checkErr(json.Unmarshal(content, &js))
ret := FileEntryDb{}
for _, v := range js {
ret[v.Id] = v
}
return ret
}
func writeFileEntries(path string) {
fmt.Println("Writing: ", fileEntries)
file := panicOnErr(os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644))
defer closeOrPanic(file)
out := panicOnErr(json.Marshal(GetFileEntries()))
_ = panicOnErr(file.Write(out))
}