-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathviewed.go
96 lines (88 loc) · 1.82 KB
/
viewed.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
package settings
import (
"encoding/json"
"server/log"
)
type Viewed struct {
Hash string `json:"hash"`
FileIndex int `json:"file_index"`
}
func SetViewed(vv *Viewed) {
var indexes map[int]struct{}
var err error
buf := tdb.Get("Viewed", vv.Hash)
if len(buf) == 0 {
indexes = make(map[int]struct{})
indexes[vv.FileIndex] = struct{}{}
buf, err = json.Marshal(indexes)
if err == nil {
tdb.Set("Viewed", vv.Hash, buf)
}
} else {
err = json.Unmarshal(buf, &indexes)
if err == nil {
indexes[vv.FileIndex] = struct{}{}
buf, err = json.Marshal(indexes)
if err == nil {
tdb.Set("Viewed", vv.Hash, buf)
}
}
}
if err != nil {
log.TLogln("Error set viewed:", err)
}
}
func RemViewed(vv *Viewed) {
buf := tdb.Get("Viewed", vv.Hash)
var indeces map[int]struct{}
err := json.Unmarshal(buf, &indeces)
if err == nil {
delete(indeces, vv.FileIndex)
buf, err = json.Marshal(indeces)
if err == nil {
tdb.Set("Viewed", vv.Hash, buf)
}
}
if err != nil {
log.TLogln("Error rem viewed:", err)
}
}
func ListViewed(hash string) []*Viewed {
var err error
if hash != "" {
buf := tdb.Get("Viewed", hash)
if len(buf) == 0 {
return []*Viewed{}
}
var indeces map[int]struct{}
err = json.Unmarshal(buf, &indeces)
if err == nil {
var ret []*Viewed
for i, _ := range indeces {
ret = append(ret, &Viewed{hash, i})
}
return ret
}
} else {
var ret []*Viewed
keys := tdb.List("Viewed")
for _, key := range keys {
buf := tdb.Get("Viewed", key)
if len(buf) == 0 {
return []*Viewed{}
}
var indeces map[int]struct{}
err = json.Unmarshal(buf, &indeces)
if err == nil {
for i, _ := range indeces {
ret = append(ret, &Viewed{key, i})
}
}
}
return ret
}
if err != nil {
log.TLogln("Error list viewed:", err)
}
return []*Viewed{}
}