Skip to content

Commit 96ba6bc

Browse files
author
李聪
committed
optimize code
1 parent ade9a39 commit 96ba6bc

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

talebook.go

+13-3
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ func (tale *TaleBook) Next() (*Book, error) {
158158
return &book, nil
159159
}
160160

161-
func (tale *TaleBook) Download(b *Book, dir string) error {
161+
func (tale *TaleBook) tryDownload(b *Book, dir string, count int) error {
162162
for _, file := range b.Book.Files {
163163
var downloadURL string
164164
if strings.HasPrefix(file.Href, "https://") || strings.HasPrefix(file.Href, "http://") {
@@ -169,7 +169,7 @@ func (tale *TaleBook) Download(b *Book, dir string) error {
169169
if tale.verbose {
170170
log.Printf("download %s", downloadURL)
171171
}
172-
172+
173173
req, err := http.NewRequest(http.MethodGet, downloadURL, nil)
174174
if err != nil {
175175
return err
@@ -212,12 +212,22 @@ func (tale *TaleBook) Download(b *Book, dir string) error {
212212
if err != nil {
213213
fh.Close()
214214
os.Remove(filepath)
215-
return wrapperTimeOutError(err)
215+
if IsTimeOutError(err) {
216+
if tale.retry == count {
217+
return err
218+
}
219+
log.Printf("timeout , retry %s://%s%s [%d/%d]", req.URL.Scheme, req.Host, req.URL.Path, count+1, tale.retry)
220+
return tale.tryDownload(b, dir, count+1)
221+
}
222+
return err
216223
}
217224
fh.Close()
218225
}
219226
return nil
220227
}
228+
func (tale *TaleBook) Download(b *Book, dir string) error {
229+
return tale.tryDownload(b, dir, 0)
230+
}
221231

222232
func NewTableBook(site string, opstions ...func(*TaleBook)) (*TaleBook, error) {
223233
var client http.Client = http.Client{

talebook_log.go

+8-1
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@ import (
66
"log"
77
"net/url"
88
"os"
9+
"path/filepath"
910
)
1011

1112
const (
12-
logfile = `~/.dl-download.json`
13+
name = `.dl-tabebook.json`
1314
)
1415

1516
func saveDownloadHistory(tb TaleBook) {
17+
home, _ := os.UserHomeDir()
18+
logfile := filepath.Join(home, name)
1619
u, _ := url.Parse(tb.api)
1720

1821
data, err := readjsonMap(logfile)
@@ -31,6 +34,8 @@ func saveDownloadHistory(tb TaleBook) {
3134
}
3235

3336
func readjsonMap(filename string) (map[string]int, error) {
37+
home, _ := os.UserHomeDir()
38+
logfile := filepath.Join(home, name)
3439
content, err := os.ReadFile(logfile)
3540
if err != nil {
3641
return nil, err
@@ -40,6 +45,8 @@ func readjsonMap(filename string) (map[string]int, error) {
4045
return data, err
4146
}
4247
func tryReadHistoryIndex(api string) (int, error) {
48+
home, _ := os.UserHomeDir()
49+
logfile := filepath.Join(home, name)
4350
data, err := readjsonMap(logfile)
4451
if err != nil {
4552
return 0, err

0 commit comments

Comments
 (0)