This repository has been archived by the owner on Sep 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
331 lines (268 loc) · 6.62 KB
/
client.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package mox
import (
"archive/zip"
"context"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"regexp"
"strings"
"sync"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/publicsuffix"
)
const (
taskChBufferSize = 1024
maxRetry = 5
)
var (
moxBaseURL = "https://mox.moe"
)
type Comics struct {
Title string
Authors []string
Books []*Book
}
type Book struct {
ID string
Name string
MobiVIPPath string
MobiVIP2Path string
EpubVIPPath string
EpubVIP2Path string
}
func WatchTask(ctx context.Context) {
taskCh := ctx.Value("taskCh").(chan func())
for {
select {
case <-ctx.Done():
return
default:
}
for f := range taskCh {
f()
}
}
}
func NewClient() (client *http.Client, err error) {
var jar *cookiejar.Jar
jar, err = cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
return
}
client = &http.Client{
Jar: jar,
}
return
}
type MoxClient struct {
*http.Client
Ctx context.Context
}
func NewMoxClient(ctx context.Context) (c *MoxClient, err error) {
var client *http.Client
client, err = NewClient()
if err != nil {
return
}
c = &MoxClient{Ctx: ctx, Client: client}
return
}
func (c *MoxClient) Login() (err error) {
var u string
var form url.Values
var req *http.Request
var resp *http.Response
config := c.Ctx.Value("config").(*Config)
u = fmt.Sprintf("%s/%s", moxBaseURL, "login_do.php")
form = url.Values{}
form.Add("email", config.Mox.Email)
form.Add("passwd", config.Mox.Password)
req, err = http.NewRequest("POST", u, strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err = c.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
return
}
func (c *MoxClient) Logout() (err error) {
var u string
var resp *http.Response
u = fmt.Sprintf("%s/%s", moxBaseURL, "logout.php")
resp, err = c.Get(u)
if err != nil {
return
}
defer resp.Body.Close()
return
}
func (c *MoxClient) GetComics(id int) (comics *Comics, err error) {
var u string
var resp *http.Response
var doc *goquery.Document
var sel *goquery.Selection
u = fmt.Sprintf("%s/c/%d.htm", moxBaseURL, id)
resp, err = c.Get(u)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNotFound {
var patBookData *regexp.Regexp
var patVolInfo *regexp.Regexp
var html, bookDataPath string
var mVolInfo [][]string
var bodyBytes []byte
doc, err = goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return
}
patBookData = regexp.MustCompile(`book_data.php\?h=\w+`)
patVolInfo = regexp.MustCompile(`"volinfo=(.+?)"`)
comics = new(Comics)
comics.Title = doc.Find(".font_big").Text()
sel = doc.Find("font.status").Eq(0)
sel = sel.Find("a")
for i := 0; i < len(sel.Nodes); i++ {
node := sel.Eq(i)
if node.Text() != "" {
comics.Authors = append(comics.Authors, node.Text())
}
}
html, err = doc.Html()
if err != nil {
return
}
bookDataPath = patBookData.FindString(html)
if bookDataPath == "" {
err = fmt.Errorf("book data is not found")
return
}
u = fmt.Sprintf("%s/%s", moxBaseURL, bookDataPath)
resp, err = c.Get(u)
if err != nil {
return
}
defer resp.Body.Close()
bodyBytes, err = io.ReadAll(resp.Body)
if err != nil {
return
}
mVolInfo = patVolInfo.FindAllStringSubmatch(string(bodyBytes), -1)
if mVolInfo == nil {
err = fmt.Errorf("volinfo is not found")
return
}
for _, m := range mVolInfo {
volInfo := strings.Split(m[1], ",")
bookID := volInfo[0]
bookName := volInfo[5]
book := &Book{
ID: bookID,
Name: bookName,
MobiVIPPath: fmt.Sprintf("down/%d/%s/0/1/1-0/", id, bookID),
MobiVIP2Path: fmt.Sprintf("down/%d/%s/1/1/1-0/", id, bookID),
EpubVIPPath: fmt.Sprintf("down/%d/%s/0/2/1-0/", id, bookID),
EpubVIP2Path: fmt.Sprintf("down/%d/%s/1/2/1-0/", id, bookID),
}
comics.Books = append(comics.Books, book)
}
} else {
err = fmt.Errorf("%d", resp.StatusCode)
}
return
}
func (c *MoxClient) DownloadComics(id int) (err error) {
var comics *Comics
var cancel context.CancelFunc
config := c.Ctx.Value("config").(*Config)
wg := new(sync.WaitGroup)
c.Ctx, cancel = context.WithCancel(c.Ctx)
defer cancel()
taskCh := make(chan func(), taskChBufferSize)
c.Ctx = context.WithValue(c.Ctx, "taskCh", taskCh)
for i := 0; i < config.Mox.Transfers; i++ {
go WatchTask(c.Ctx)
}
comics, err = c.GetComics(id)
if err != nil {
return
}
for i := 0; i < len(comics.Books); i++ {
book := comics.Books[i]
wg.Add(1)
taskCh <- func() {
defer wg.Done()
var f *os.File
var u string
var resp *http.Response
fileName := fmt.Sprintf(
"%s/[Mox][%s]%s.kepub.epub",
config.Mox.DownloadPath,
comics.Title,
book.Name,
)
u = fmt.Sprintf("%s/%s", moxBaseURL, book.EpubVIPPath)
fmt.Println(fmt.Sprintf("[INFO] Download book from %s to %s...", u, fileName))
f, err = os.Create(fileName)
if err != nil {
return
}
defer f.Close()
retry := 0
DownloadFile:
resp, err = c.Get(u)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK && strings.Contains(resp.Header.Get("Content-Type"), "application/octet-stream") {
_, err = io.Copy(f, resp.Body)
if err != nil {
retry++
if retry > maxRetry {
fmt.Println(fmt.Sprintf("[ERROR] Download book failed: %s. Ignored this book. [err=%s] [retry=%d]", fileName, err.Error(), retry))
return
} else {
fmt.Println(fmt.Sprintf("[ERROR] Download book failed: %s. Retry. [err=%s] [retry=%d]", fileName, err.Error(), retry))
goto DownloadFile
}
}
_, err = zip.OpenReader(fileName)
if err != nil {
retry++
if retry > maxRetry {
fmt.Println(fmt.Sprintf("[ERROR] Download book failed: %s. Ignored this book. [err=%s] [retry=%d]", fileName, err.Error(), retry))
} else {
fmt.Println(fmt.Sprintf("[ERROR] Download book failed: %s. Retry. [err=%s] [retry=%d]", fileName, err.Error(), retry))
goto DownloadFile
}
}
} else {
if resp.StatusCode == http.StatusForbidden {
var body []byte
body, err = io.ReadAll(resp.Body)
if err != nil {
return
}
fmt.Println(string(body))
} else {
retry++
if retry > maxRetry {
fmt.Println(fmt.Sprintf("[ERROR] Download book failed: %s. Ignored this book. [retry=%d]", fileName, retry))
} else {
fmt.Println(fmt.Sprintf("[ERROR] Download book failed: %s. Retry. [retry=%d]", fileName, retry))
goto DownloadFile
}
}
}
}
}
wg.Wait()
return
}