-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
206 lines (158 loc) · 4.63 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
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
package main
import (
"errors"
"flag"
"fmt"
"strings"
"sync"
"time"
"github.com/gocolly/colly"
"github.com/mgagliardo91/blacksmith"
"github.com/mgagliardo91/go-utils"
"github.com/mgagliardo91/offline-collector/proxy"
)
type OfflineEventRequest struct {
Date time.Time `json:"date"`
Title string `json:"title"`
Details string `json:"details"`
URL string `json:"url"`
}
type FailureMap struct {
failures map[string]uint64
mux sync.Mutex
}
type SimpleDate time.Time
func (f *FailureMap) increment(val string) uint64 {
f.mux.Lock()
defer f.mux.Unlock()
v, ok := f.failures[val]
if !ok {
f.failures[val] = 0
} else {
f.failures[val] = v + 1
}
return f.failures[val]
}
const (
EventDetail blacksmith.TaskName = iota
)
const calendarFormat = "2006-01-02"
const calendarURL = "https://www.get-offline.com/raleigh/calendar"
var (
MaxWorker = utils.GetEnvInt("MAX_WORKERS", 10)
OfflineServer = utils.GetEnvString("OFFLINE_SERVER", "http://0.0.0.0")
OfflinePort = utils.GetEnvString("OFFLINE_PORT", "3000")
)
var events map[time.Time][]OfflineEventRequest
var failureMap = FailureMap{
failures: make(map[string]uint64),
}
func nextDateURL(date time.Time) string {
nextRequestDate := date.AddDate(0, 0, 1)
return createCalendarURL(nextRequestDate.Format(calendarFormat))
}
func createCalendarURL(dateString string) string {
return fmt.Sprintf("%s?date=%s", calendarURL, dateString)
}
func (s *SimpleDate) String() string {
return time.Time(*s).Format(calendarFormat)
}
func (s *SimpleDate) Set(value string) error {
dateVal, err := time.Parse(calendarFormat, value)
if err != nil {
return errors.New("Unable to parse to date value. Format YYYY-MM-DD")
}
*s = SimpleDate(dateVal)
return nil
}
func main() {
if OfflineServer == "" || OfflinePort == "" {
GetLogger().Fatalf("Invalid offline server address.")
return
}
GetLogger().Infof("Using offline server at: %s:%s", OfflineServer, OfflinePort)
var startDate, endDate SimpleDate
flag.Var(&startDate, "start", "Start date YYYY-MM-DD")
flag.Var(&endDate, "end", "End date YYYY-MM-DD")
flag.Parse()
if startDate == (SimpleDate{}) {
startDate.Set(time.Now().Format(calendarFormat))
}
if endDate == (SimpleDate{}) {
endDate.Set(startDate.String())
}
GetLogger().Infof("Collecting offline events between %s and %s \n", startDate.String(), endDate.String())
utils.SetLoggerLevel(blacksmith.LoggerName, "info")
startProxyService(proxy.RequestGetProxy)
defer stopProxyService()
c := createCollector()
var dateSet sync.Map
blacksmith := blacksmith.New(MaxWorker)
blacksmith.SetHandler(EventDetail, collectDetail).Run()
c.OnHTML(".experience-thumb--calendar > a[href]", func(e *colly.HTMLElement) {
var date time.Time
if dateVal, ok := e.Request.Ctx.GetAny("date").(time.Time); ok {
date = dateVal
} else {
return
}
link := e.Attr("href")
el := e.DOM
event := OfflineEventRequest{
Date: date,
Title: strings.TrimSpace(el.Find("div[class$=\"_title\"]").Text()),
Details: strings.TrimSpace(el.Find("div[class$=\"_details\"]").Text()),
URL: e.Request.AbsoluteURL(link),
}
blacksmith.QueueTask(EventDetail, event)
})
c.OnHTML(".calender-sliders__date", func(e *colly.HTMLElement) {
date := e.Attr("id")
if _, hasDate := dateSet.Load(date); !hasDate {
dateSet.Store(date, true)
dateVal, err := time.Parse(calendarFormat, date)
if err != nil {
GetLogger().Errorf("Unable to parse date ID as date: %s. %s", date, err)
}
if (time.Time(endDate).Equal(dateVal) || time.Time(endDate).After(dateVal)) && (time.Time(startDate).Before(dateVal)) {
nextURL := nextDateURL(dateVal)
c.Visit(nextURL)
}
}
})
c.OnRequest(func(r *colly.Request) {
GetLogger().Infoln("visiting", r.URL.String())
})
c.OnResponse(func(r *colly.Response) {
dateString := r.Request.URL.Query().Get("date")
date, _ := time.Parse(calendarFormat, dateString)
r.Request.Ctx.Put("date", date)
dateSet.Store(dateString, true)
})
// Set error handler
c.OnError(func(r *colly.Response, err error) {
GetLogger().Infoln("Request URL:", r.Request.URL, "failed with response:", r, "\nError:", err)
proxyURL := r.Request.Headers.Get(ProxyURLKey)
if len(proxyURL) > 0 {
failures := failureMap.increment(proxyURL)
if failures > 2 {
proxyList.Remove(proxyURL)
}
} else {
time.Sleep(2 * time.Second)
}
// try again
c.Visit(r.Request.URL.String())
})
// Start scraping
c.Visit(createCalendarURL(startDate.String()))
c.Wait()
blacksmith.Stop()
}
var logger *utils.LogWrapper
func GetLogger() *utils.LogWrapper {
if logger == nil {
logger = utils.NewLogger("collector")
}
return logger
}