-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
116 lines (109 loc) · 2.51 KB
/
main.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"flag"
"fmt"
"github.com/tbxark-arc/novelspider/loader"
"log"
"os"
"path/filepath"
"strings"
"time"
)
const (
Retry = 3
)
type Config struct {
link string
dir string
startIndex int
interval int
}
func main() {
var conf Config
flag.StringVar(&conf.link, "link", "", "link of the books")
flag.StringVar(&conf.dir, "dir", "./", "directory to save the books")
flag.IntVar(&conf.startIndex, "start", -1, "start index of the books")
flag.IntVar(&conf.interval, "interval", 1, "seconds between each download")
parser := flag.String("parser", "", "parser of the books, support: shuba69, sksw")
help := flag.Bool("help", false, "show help")
flag.Parse()
if *help {
flag.Usage()
return
}
if conf.link == "" {
log.Panic("Please provide the link of the books")
}
load, err := createParser(*parser)
if err != nil {
log.Panic(err)
}
err = startDownload(load, &conf)
if err != nil {
log.Panic(err)
}
}
func createParser(name string) (loader.Parser, error) {
switch name {
case "shuba69":
return loader.NewShuBa69(), nil
case "sksw":
return loader.NewSksw(), nil
default:
return nil, fmt.Errorf("unknown parser %s", name)
}
}
func startDownload(parser loader.Parser, conf *Config) error {
title, category, err := parser.Category(conf.link)
if err != nil {
return err
}
fileName, err := filepath.Abs(filepath.Join(conf.dir, title+".txt"))
if err != nil {
return err
}
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
log.Printf("Create file %s", fileName)
log.Printf("Start download %s", title)
defer file.Close()
DOWNLOAD:
for idx, book := range category {
if idx < conf.startIndex {
continue
}
if !strings.HasPrefix(book, "http") {
continue
}
for i := 0; i < Retry; i++ {
if loadAndWriteCategory(parser, book, file) == nil {
time.Sleep(time.Duration(conf.interval) * time.Second)
continue DOWNLOAD
}
log.Printf("Retry %d times for %s", i+1, book)
time.Sleep(time.Second)
}
log.Panicf("Failed to download %s", book)
}
log.Println("Downloaded all books")
return nil
}
func loadAndWriteCategory(parser loader.Parser, book string, save *os.File) error {
log.Printf("Downloading %s", book)
cateTitle, content, err := parser.Book(book)
log.Printf("Downloaded %s", cateTitle)
if err != nil {
return err
}
_, err = save.WriteString(cateTitle + "\n")
if err != nil {
return err
}
_, err = save.WriteString(content + "\n")
if err != nil {
return err
}
return save.Sync()
}