-
Notifications
You must be signed in to change notification settings - Fork 1
/
recents.go
64 lines (56 loc) · 1.54 KB
/
recents.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
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"github.com/spf13/viper"
)
var recentsLock = &sync.Mutex{}
var cachedRecents interface{}
func addToRecents(data interface{}) {
currentData, err := getRecents()
if err != nil {
log.Printf("failed to getRecents: %v", err)
currentData = []interface{}{}
}
recentsLock.Lock()
defer recentsLock.Unlock()
recentsPath := filepath.Join(viper.GetString("upload.dataDir"), "./recents.json")
truncData := (currentData.([]interface{}))
if len(truncData) > viper.GetInt("upload.recentsSize") {
truncData = truncData[:viper.GetInt("upload.recentsSize")]
}
currentData = append([]interface{}{data}, truncData...)
cachedRecents = currentData
marshaled, err := json.Marshal(currentData)
if err != nil {
log.Printf("failed to marshal recents.json: %v", err)
return
}
err = os.WriteFile(recentsPath, marshaled, 0777)
if err != nil {
log.Printf("failed to write recents.json: %v", err)
return
}
notifyFileListeners("/recents.json")
}
func getRecents() (interface{}, error) {
recentsLock.Lock()
defer recentsLock.Unlock()
if cachedRecents == nil {
recentsPath := filepath.Join(viper.GetString("upload.dataDir"), "./recents.json")
data, err := os.ReadFile(recentsPath)
if err != nil {
return nil, fmt.Errorf("failed to open %v: %w", recentsPath, err)
}
var output interface{}
if err := json.Unmarshal(data, &output); err != nil {
return nil, fmt.Errorf("failed to parse %v: %w", recentsPath, err)
}
cachedRecents = output
}
return cachedRecents, nil
}