-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlog.go
63 lines (57 loc) · 1.33 KB
/
log.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"path/filepath"
)
const (
name = `.dl-tabebook.json`
)
func saveDownloadHistory(tb TaleBook) {
home, _ := os.UserHomeDir()
logfile := filepath.Join(home, name)
u, _ := url.Parse(tb.api)
data, err := readjsonMap(logfile)
if err != nil {
log.Printf("history not foud,create new history now")
data = make(map[string]int)
}
data[u.Host] = tb.index - 1
content, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Printf("warn gen history json failed")
}
if err = os.WriteFile(logfile, content, 0644); err != nil {
log.Printf("warning: can not write dl-download infromat to .dl-download.log %s", err)
}
}
func readjsonMap(filename string) (map[string]int, error) {
home, _ := os.UserHomeDir()
logfile := filepath.Join(home, name)
content, err := os.ReadFile(logfile)
if err != nil {
return nil, err
}
var data = make(map[string]int)
err = json.Unmarshal(content, &data)
return data, err
}
func tryReadHistoryIndex(api string) (int, error) {
home, _ := os.UserHomeDir()
logfile := filepath.Join(home, name)
data, err := readjsonMap(logfile)
if err != nil {
return 0, err
}
u, err := url.Parse(api)
if err != nil {
return 0, nil
}
if index, ok := data[u.Host]; ok {
return index, nil
}
return 0, fmt.Errorf("download history not found")
}