-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
156 lines (121 loc) · 3.44 KB
/
parser.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
package main
import (
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/nxshock/gwp"
"github.com/sirupsen/logrus"
"golang.org/x/net/proxy"
"golang.org/x/text/encoding/charmap"
)
type Parser struct {
httpClient *http.Client
}
var parser *Parser
func initParser() error {
logrus.Info("Инициализация парсера...")
parser = &Parser{
httpClient: &http.Client{
Timeout: 5 * time.Second}}
if config.HttpProxyAddress != "" {
dialer, err := proxy.SOCKS5("tcp", config.HttpProxyAddress, nil, proxy.Direct)
if err != nil {
return err
}
parser.httpClient.Transport = &http.Transport{Dial: dialer.Dial}
}
return nil
}
func (parser *Parser) Update() error {
logrus.Info("Начато обновление базы данных...")
beforeUpdateMaxId, err := lastDbId()
if err != nil {
return fmt.Errorf("lastDbId(): %v", err)
}
logrus.WithFields(logrus.Fields{
"от": beforeUpdateMaxId - config.UpdateForwardRecordCount,
"до": beforeUpdateMaxId + config.UpdateBackwardRecordCount,
}).Debug("Начат процесс обновления...")
workerPool := gwp.New(config.ParserThreadCount)
newMaxId := beforeUpdateMaxId
for i := beforeUpdateMaxId - config.UpdateBackwardRecordCount; i <= beforeUpdateMaxId+config.UpdateForwardRecordCount; i++ {
if i <= 0 {
continue
}
workerPool.Add(func() error {
n := i
info, err := parser.GetPage(n)
if err != nil {
logrus.WithField("id", n).Debug(err)
return err
}
if n > newMaxId {
newMaxId = n
}
err = db.Set(n, *info)
if err != nil {
logrus.WithField("id", i).Errorln("Ошибка при выполнении вставки в базу данных:", err)
return err
}
index.Add(n, info.Title)
return nil
})
}
workerPool.CloseAndWait()
err = index.Save()
if err != nil {
return fmt.Errorf("ошибка при сохранении индекса: %v", err)
}
err = db.Set("maxId", newMaxId)
if err != nil {
return fmt.Errorf("ошибка при сохранении maxId: %v", err)
}
logrus.WithFields(logrus.Fields{
"добавлено": newMaxId - beforeUpdateMaxId,
"ошибок": workerPool.ErrorCount(),
}).Info("Обновление базы данных завершено.") // TODO: вместо "добавлено" показывает изменение ID
return nil
}
func (parser *Parser) GetPage(id int) (*Info, error) {
resp, err := parser.httpClient.Get(fmt.Sprintf("https://rutracker.org/forum/viewtopic.php?t=%d", id))
if err != nil {
return nil, err
}
doc, err := goquery.NewDocumentFromResponse(resp)
if err != nil {
return nil, err
}
title := decode(doc.Find("a#topic-title").First().Text())
if title == "" {
return nil, errors.New("title not found")
}
forumName := decode(doc.Find("td.nav > a").First().Text())
if title == "" {
return nil, errors.New("forum not found")
}
magnet, exists := doc.Find("a.magnet-link").First().Attr("href")
if !exists {
return nil, errors.New("magnet not found")
}
mu, _ := url.Parse(magnet)
xt, exists := mu.Query()["xt"]
if !exists || len(xt) == 0 {
return nil, errors.New("xt not found")
}
info := &Info{
Title: title,
ForumName: forumName,
MagnetData: strings.TrimPrefix(xt[0], "urn:btih:")}
return info, nil
}
func decode(s string) string {
decoded, err := charmap.Windows1251.NewDecoder().String(s)
if err != nil {
return s
}
return decoded
}