-
Notifications
You must be signed in to change notification settings - Fork 0
/
ptt.go
377 lines (329 loc) · 9.54 KB
/
ptt.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package photomgr
import (
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"github.com/PuerkitoBio/goquery"
)
type PTT struct {
//Inherit
baseCrawler
//Handle base folder address to store images
BaseDir string
SearchAddress string
}
func NewPTT() *PTT {
p := new(PTT)
p.baseAddress = "https://www.ptt.cc"
p.entryAddress = "https://www.ptt.cc/bbs/Beauty/index.html"
p.SearchAddress = "https://www.ptt.cc/bbs/Beauty/search?q="
return p
}
// GetAllFromURL: return all post images, like and dis in current page
func (p *PTT) GetAllFromURL(url string) (title string, allImages []string, like, dis int) {
// Get https response with setting cookie over18=1
resp := getResponseWithCookie(url)
doc, err := goquery.NewDocumentFromResponse(resp)
if err != nil {
log.Println(err)
return title, allImages, like, dis
}
//Title and folder
doc.Find(".article-metaline").Each(func(i int, s *goquery.Selection) {
if strings.Contains(s.Find(".article-meta-tag").Text(), "標題") {
title = s.Find(".article-meta-value").Text()
}
})
//all images
foundImage := false
doc.Find("a").Each(func(i int, s *goquery.Selection) {
imgLink, _ := s.Attr("href")
if isImageLink(imgLink) {
if strings.Contains(imgLink, "https://imgur.com/") {
imgLink = imgLink + ".jpg"
}
allImages = append(allImages, imgLink)
foundImage = true
}
})
if !foundImage {
log.Println("Don't have any image in this article. url:", url)
}
//Like and Dislike
doc.Find(".push-tag").Each(func(i int, s *goquery.Selection) {
if strings.Contains(s.Text(), "推") {
like++
} else if strings.Contains(s.Text(), "噓") {
dis++
}
})
return title, allImages, like, dis
}
// GetUrlTitle: return title and url of post
func (p *PTT) GetUrlTitle(target string) string {
// Get https response with setting cookie over18=1
resp := getResponseWithCookie(target)
doc, err := goquery.NewDocumentFromResponse(resp)
if err != nil {
log.Println(err)
return ""
}
//Title
articleTitle := ""
doc.Find(".article-metaline").Each(func(i int, s *goquery.Selection) {
if strings.Contains(s.Find(".article-meta-tag").Text(), "標題") {
articleTitle = s.Find(".article-meta-value").Text()
}
})
return articleTitle
}
// Crawler: parse ptt board page by index
func (p *PTT) Crawler(target string, workerNum int) {
// Get https response with setting cookie over18=1
resp := getResponseWithCookie(target)
doc, err := goquery.NewDocumentFromResponse(resp)
if err != nil {
log.Println(err)
return
}
//Title and folder
articleTitle := ""
doc.Find(".article-metaline").Each(func(i int, s *goquery.Selection) {
if strings.Contains(s.Find(".article-meta-tag").Text(), "標題") {
articleTitle = s.Find(".article-meta-value").Text()
}
})
dir := fmt.Sprintf("%v/%v - %v", p.BaseDir, "PTT", articleTitle)
if exist, _ := exists(dir); exist {
//fmt.Println("Already download")
return
}
os.MkdirAll(filepath.FromSlash(dir), 0755)
//Concurrecny
linkChan := make(chan string)
wg := new(sync.WaitGroup)
for i := 0; i < workerNum; i++ {
wg.Add(1)
go p.worker(filepath.FromSlash(dir), linkChan, wg)
}
//Parse Image, currently support <IMG SRC> only
foundImage := false
doc.Find("a").Each(func(i int, s *goquery.Selection) {
imgLink, _ := s.Attr("href")
if isImageLink(imgLink) {
if strings.Contains(imgLink, "https://imgur.com/") {
imgLink = imgLink + ".jpg"
}
linkChan <- imgLink
foundImage = true
}
})
if !foundImage {
log.Println("Don't have any image in this article. url:", target)
}
close(linkChan)
wg.Wait()
}
// GetAllImageAddress: return all image address in current page.
func (p *PTT) GetAllImageAddress(target string) []string {
var ret []string
// Get https response with setting cookie over18=1
resp := getResponseWithCookie(target)
doc, err := goquery.NewDocumentFromResponse(resp)
if err != nil {
log.Println(err)
return nil
}
//Parse Image, currently support <IMG SRC> only
foundImage := false
doc.Find("a").Each(func(i int, s *goquery.Selection) {
imgLink, _ := s.Attr("href")
if isImageLink(imgLink) {
if strings.Contains(imgLink, "https://imgur.com/") {
imgLink = imgLink + ".jpg"
}
ret = append(ret, imgLink)
foundImage = true
}
})
if !foundImage {
log.Println("Don't have any image in this article. url:", target)
}
return ret
}
// Return parse page result count, it will be 0 if you still not parse any page
func (p *PTT) GetCurrentPageResultCount() int {
return len(p.storedPost)
}
// Get post title by index in current parsed page
func (p *PTT) GetPostTitleByIndex(postIndex int) string {
if postIndex >= len(p.storedPost) {
return ""
}
return p.storedPost[postIndex].ArticleTitle
}
// Get post URL by index in current parsed page
func (p *PTT) GetPostUrlByIndex(postIndex int) string {
if postIndex >= len(p.storedPost) {
return ""
}
return p.storedPost[postIndex].URL
}
// Get post like count by index in current parsed page
func (p *PTT) GetPostStarByIndex(postIndex int) int {
if postIndex >= len(p.storedPost) {
return 0
}
return p.storedPost[postIndex].Likeint
}
// Set Ptt board psot number, fetch assigned (at least) number of posts. Return real number.
func (p *PTT) ParsePttByNumber(num int, page int) int {
count := p.ParsePttPageByIndex(page, true)
if count > num {
return count
}
page++
for count < num {
count = p.ParsePttPageByIndex(page, false)
page++
}
return count
}
// Set Ptt board page index, fetch all post and return article count back
func (p *PTT) ParsePttPageByIndex(page int, replace bool) int {
// Get https response with setting cookie over18=1
resp := getResponseWithCookie(p.entryAddress)
doc, err := goquery.NewDocumentFromResponse(resp)
if err != nil {
log.Fatal(err)
}
posts := make([]PostDoc, 0)
maxPageNumberString := ""
var PageWebSide string
if page > 0 {
// Find page result
doc.Find(".btn-group a").Each(func(i int, s *goquery.Selection) {
if strings.Contains(s.Text(), "上頁") {
href, exist := s.Attr("href")
if exist {
targetString := strings.Split(href, "index")[1]
targetString = strings.Split(targetString, ".html")[0]
maxPageNumberString = targetString
}
}
})
pageNum, _ := strconv.Atoi(maxPageNumberString)
pageNum = pageNum - page + 1
PageWebSide = fmt.Sprintf("https://www.ptt.cc/bbs/Beauty/index%d.html", pageNum)
} else {
PageWebSide = p.entryAddress
}
// Get https response with setting cookie over18=1
resp = getResponseWithCookie(PageWebSide)
doc, err = goquery.NewDocumentFromResponse(resp)
if err != nil {
log.Fatal(err)
}
doc.Find(".r-ent").Each(func(i int, s *goquery.Selection) {
title := strings.TrimSpace(s.Find(".title").Text())
if CheckTitleWithBeauty(title) {
likeCount, _ := strconv.Atoi(s.Find(".nrec span").Text())
href, _ := s.Find(".title a").Attr("href")
link := p.baseAddress + href
newPost := PostDoc{
ArticleID: "",
ArticleTitle: title,
URL: link,
Likeint: likeCount,
}
posts = append(posts, newPost)
}
})
if replace {
p.storedPost = posts
} else {
p.storedPost = append(p.storedPost, posts...)
}
return len(p.storedPost)
}
func getResponseWithCookie(url string) *http.Response {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal("http failed:", err)
}
req.AddCookie(&http.Cookie{Name: "over18", Value: "1"})
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal("client failed:", err)
}
return resp
}
func (p *PTT) GetPostLikeDis(target string) (int, int) {
// Get https response with setting cookie over18=1
resp := getResponseWithCookie(target)
doc, err := goquery.NewDocumentFromResponse(resp)
if err != nil {
log.Println(err)
return 0, 0
}
var likeCount int
var disLikeCount int
doc.Find(".push-tag").Each(func(i int, s *goquery.Selection) {
if strings.Contains(s.Text(), "推") {
likeCount++
} else if strings.Contains(s.Text(), "噓") {
disLikeCount++
}
})
// fmt.Println("like:", likeCount, " dislike:", disLikeCount)
return likeCount, disLikeCount
}
// Search with specific keyword, fetch all post and return article count back
func (p *PTT) ParseSearchByKeyword(keyword string) int {
// Get https response with setting cookie over18=1
resp := getResponseWithCookie(p.SearchAddress + keyword)
doc, err := goquery.NewDocumentFromResponse(resp)
if err != nil {
log.Fatal(err)
}
posts := make([]PostDoc, 0)
doc.Find(".r-ent").Each(func(i int, s *goquery.Selection) {
title := strings.TrimSpace(s.Find(".title").Text())
if CheckTitleWithBeauty(title) {
likeCount, _ := strconv.Atoi(s.Find(".nrec span").Text())
href, _ := s.Find(".title a").Attr("href")
link := p.baseAddress + href
newPost := PostDoc{
ArticleID: "",
ArticleTitle: title,
URL: link,
Likeint: likeCount,
}
posts = append(posts, newPost)
}
})
p.storedPost = posts
return len(p.storedPost)
}
// CheckTitleWithBeauty: check if title contains "美女" or "美女圖" or "美女圖片" or "美女圖片"
func CheckTitleWithBeauty(title string) bool {
d, _ := regexp.MatchString("^\\[正妹\\].*", title)
return d
}
// isImageLink checks if the given URL is an image link from supported hosts.
func isImageLink(url string) bool {
return strings.Contains(url, "https://i.imgur.com/") ||
strings.Contains(url, "http://i.imgur.com/") ||
strings.Contains(url, "https://pbs.twimg.com/") ||
strings.Contains(url, "https://imgur.com/") ||
strings.Contains(url, "https://i.meee.com.tw/") ||
strings.Contains(url, "https://i.ytimg.com/") ||
strings.Contains(url, "https://d.img.vision/")
}