-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile2.go
428 lines (393 loc) · 12.7 KB
/
file2.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package inner
import (
"context"
"encoding/json"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/dom"
"github.com/chromedp/chromedp"
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"myrepo/internal/chromedphandler"
"myrepo/internal/elastichandler"
"myrepo/internal/headlesshandler"
"myrepo/internal/mongodbhandler"
"myrepo/internal/nsqhandler"
"myrepo/internal/urlhandler"
"myrepo/internal/utility"
"myrepo/internal/workerhandler"
"myrepo/svc/worker/headless"
"golang.org/x/sync/semaphore"
"log"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
func GenContext(opts []chromedp.ExecAllocatorOption) (context.Context, context.CancelFunc) {
ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
ctx, cancel = chromedp.NewContext(ctx)
err := chromedp.Run(ctx)
if err != nil {
fmt.Println("TOP CONTEXT")
fmt.Println("CONTEXT ERROR", err)
}
return ctx, cancel
}
//CheckDB accepts the standard options, and operates a top level context, however it loops until all URLS are found
// based on the initial seed URLS.
//If a seed is a nested link "https://x.com/aboutus", it will parse upwards as well.
//Internal links only, not external.
//Redirects are also stored and sanatized to prevent endless loops
//urls with query params ?id="bob" are stripped before entering as internal links to prevent useless loop. This misses
// some sites that use query params for rendering content i.e.
//https://appexchange.salesforce.com/appxListingDetail?listingId=a0N30000000q64KEAQ&channel=featured&placement=a0d3A000007VqCzQAK
func CheckDB(w workerhandler.Worker, connections workerhandler.Connections, opts []chromedp.ExecAllocatorOption) bool {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
} else {
fmt.Println("connected")
}
//make sure and elastic index exists
elastichandler.IndexCheck("elastic" + w.Elasticname)
crawlinnerDatabase := client.Database("mongodb" + w.Mongodbname)
workingCollection := crawlinnerDatabase.Collection("mongodb" + w.Mongodbname)
loopNum := 0
for {
seedURLS := make(map[string]string)
//ATR arrayToRun is the results of checking mongo for the initial URLS, scrubing them to the host name,
//comparing them to the links found in mongo and setting ATR to what needs to be done
var ATR []string
active := mongodbhandler.LoopDB(&w, connections, workingCollection, ctx, &ATR, &seedURLS, loopNum)
if active == false || loopNum == 20 {
break
}
w.SeedURLs = seedURLS
BrowserSplit(ATR, w, connections, opts)
time.Sleep(time.Second * 8)
loopNum++
}
return true
}
//BrowserSplit Creates Parent Browser context for pushing work and connections into
func BrowserSplit(dbURLs []string, w workerhandler.Worker, connections workerhandler.Connections, opts []chromedp.ExecAllocatorOption) bool {
browserCount := 1 // @@@ this sets the number of browsers to use
ss := utility.SliceToSliceSlice(dbURLs, browserCount)
var wg sync.WaitGroup
for _, s := range ss {
wg.Add(1)
ctx, cancel := chromedphandler.GenContext(opts)
defer cancel() // <- THIS IS OK!!!
//Reason: We're looping through a slice, creating a browser context and passing the context inside a go routine.
//We can't cancel outside the for loop because they're generated inside.
//--Running it as a go func will cause immediate termination.
//go func(cancel context.CancelFunc) {
// defer cancel()
//}(cancel)
//--Running it as a plain func will cause it to close early also
//func(cancel context.CancelFunc) {
// defer cancel()
//}(cancel)
connections.Ctx = ctx
go Split(w, connections, s, &wg)
}
wg.Wait()
return true
}
//Split is an individual browser context, tied to master context, used to operate each tab.
//Cancellation propagates up, but not until all tabs and browser are completed
func Split(w workerhandler.Worker, connections workerhandler.Connections, tabURLS []string, wg *sync.WaitGroup) {
browserCtx := connections.Ctx
nsqp := connections.Nsqp
defer func() {
wg.Done()
}()
var wgi sync.WaitGroup
//Passing all the URLs for this browser into a channel
PairChan := make(chan workerhandler.URLSeedChan, len(tabURLS))
for _, j := range tabURLS {
URLSeedChan := new(workerhandler.URLSeedChan)
for k, v := range w.SeedURLs {
if strings.Contains(j, v) {
URLSeedChan.SeedURL = k
URLSeedChan.URL = j
}
}
PairChan <- *URLSeedChan
}
// @@@ NUMBER OF TABS
tabCount := 30
sema := semaphore.NewWeighted(int64(tabCount))
for tab := 1; tab <= tabCount; tab++ {
wgi.Add(1)
err := sema.Acquire(context.Background(), 1)
if err != nil {
fmt.Println(err)
}
ctx, _ := chromedp.NewContext(browserCtx)
connections := workerhandler.Connections{
Ctx: ctx,
Nsqp: nsqp,
TabNum: tab,
}
tabContent := workerhandler.TabContent{
Command: w.Command,
Params: w.Params,
Outputs: w.Outputs,
}
go func() {
Manager(&wgi, connections, PairChan, tabContent)
sema.Release(1)
}()
//slow down the next tab creation
}
close(PairChan)
fmt.Println("CLOSED JOBS")
wgi.Wait()
}
//Manager the work coming into manager is distributed across a channel, wg closes once work is done.
func Manager(wgi *sync.WaitGroup, connections workerhandler.Connections, PairChan chan workerhandler.URLSeedChan, tabContent workerhandler.TabContent) {
i := 0
defer func() {
wgi.Done()
}()
//ranges over all the values sent down via channel
for j := range PairChan {
i++
Default(j.URL, j.SeedURL, connections, tabContent)
}
}
//Default visits the page and grabs url,redirect,links,title and other details
func Default(URL string, seedurl string, tabContext workerhandler.Connections, tabContent workerhandler.TabContent) {
if tabContent.Params.Speed != "" {
s, _ := strconv.Atoi(tabContent.Params.Speed)
time.Sleep(time.Millisecond * time.Duration(s))
}
start := time.Now()
var redir, pageTitle, urlORredir, str string
var nodes []*cdp.Node
err := chromedp.Run(
tabContext.Ctx,
headless.RunWithTimeOut(&tabContext.Ctx, 255, chromedp.Tasks{
chromedp.Navigate(URL),
chromedp.Location(&redir),
chromedp.Nodes("a", &nodes),
chromedp.Title(&pageTitle),
chromedp.ActionFunc(func(ctx2 context.Context) error {
time.Sleep(time.Millisecond * 2000)
node, err := dom.GetDocument().Do(ctx2)
if err != nil {
return err
}
str, err = dom.GetOuterHTML().WithNodeID(node.NodeID).Do(ctx2)
return err
}),
}),
)
redirected := false
if redir != URL {
fmt.Println("REDIRECT OCCURRED", URL, "-->", redir)
urlORredir = redir
redirected = true
} else {
urlORredir = URL
}
//fmt.Println(">>URLORREDIR", urlORredir)
noError := headless.ResponseError(err, redir, urlORredir, URL)
fqdn, host := urlhandler.SchemeHostSplit(urlORredir)
fmt.Println("FQDN IS", fqdn)
fmt.Println("HOST IS", host)
fmt.Printf("length of str is %v", len(str))
accessDenied := strings.HasPrefix(str, "<html><head>\n<title>Access Denied</title>")
if accessDenied == true {
fmt.Println("we have been blocked on this site")
}
if nodes != nil && noError == true && accessDenied != true {
URLS, urlsIQS := headlesshandler.NodeCheck(nodes, fqdn, host)
ints, exts := urlhandler.IntExtSort(fqdn, URLS)
fmt.Println("\n")
//for i, x := range ints {
// fmt.Println("##", i, " XX", x)
//}
fmt.Println(len(ints), "-------", len(exts))
//for i, x := range exts {
// fmt.Println("##", i, " XX", x)
//}
fmt.Println("\n")
intqs, extqs := urlhandler.IntExtSort(urlORredir, urlsIQS)
doc, err := goquery.NewDocumentFromReader(strings.NewReader(str))
if err != nil {
fmt.Println("issue with go query")
log.Fatal(err)
}
doc.Find("script").Remove()
doc.Find("style").Remove()
doc.Find("aria-hidden").Remove()
doc.Find("aria-label").Remove()
bodyText := doc.Find("body").Text()
space := regexp.MustCompile(`\s{2,}`)
s := space.ReplaceAllString(bodyText, "\n")
//bodyHTML, err := doc.Find("body").Html()
//if err != nil {
// fmt.Println("Error getting body html", err)
//}
id := uuid.New()
specid := id.String()
now := time.Now()
sec := now.Unix()
h := mongodbhandler.CrawlHit{
UUID: specid,
ElasticName: tabContent.Elasticname,
MongodbName: tabContent.Mongodbname,
SeedURL: seedurl,
URL: urlORredir,
InternalLinks: ints,
InternalLinksQP: intqs,
ExternalLinks: exts,
ExternalLinksQP: extqs,
Redirect: redirected,
RedirectFrom: URL,
RedirectTo: urlORredir,
Visited: true,
Method: "headlessinner",
PageTitle: pageTitle,
//TContent: s,
}
jsonData, err := json.Marshal(h)
if err != nil {
fmt.Println("error marshaling")
log.Println(err)
}
dataM := nsqhandler.NSQPub{Nsqp: tabContext.Nsqp, JSONData: jsonData, ChanName: "mongodbheadlessinner"}
nsqhandler.NsqPublish(dataM)
//fmt.Println("published to mongodbheadlessinner")
//if URL+"/" != urlORredir || URL+"/" != fqdn {
// if redirected == true {
// redirectDoc := mongodbhandler.CrawlRedirect{
// UUID: specid,
// ElasticName: tabContent.Elasticname,
// MongodbName: tabContent.Mongodbname,
// SeedURL: seedurl,
// URL: URL,
// RedirectFrom: URL,
// RedirectTo: urlORredir,
// Visited: true,
// Method: "crawlpage",
// }
// jsonData, err := json.Marshal(redirectDoc)
// if err != nil {
// fmt.Println("error marshaling redirectDoc")
// log.Println(err)
// }
// data := nsqhandler.NSQPub{Nsqp: tabContext.Nsqp, JSONData: jsonData, ChanName: "mongodbheadlessredir"}
// nsqhandler.NsqPublish(data)
// fmt.Println("published to mongodbheadlessredir")
// }
//}
e := elastichandler.ElasticDoc{
UUID: specid,
ElasticName: tabContent.Elasticname,
MongodbName: tabContent.Mongodbname,
TLD: host,
SeedURL: fqdn,
URL: urlORredir,
InternalLinks: ints,
InternalLinksQP: intqs,
ExternalLinks: exts,
ExternalLinksQP: extqs,
TextContent: s,
Method: "headlessinner",
PageTitle: pageTitle,
Timestamp: sec,
}
jsonDatae, err := json.Marshal(e)
if err != nil {
fmt.Println("error marshaling")
log.Println(err)
}
//if elasticname != "" {
dataE := nsqhandler.NSQPub{Nsqp: tabContext.Nsqp, JSONData: jsonDatae, ChanName: "elasticheadlessinner"}
nsqhandler.NsqPublish(dataE)
//fmt.Println("published to elasticheadlessinner")
//fmt.Println("URL", URL)
} else if nodes != nil && noError == false {
fmt.Println("# Nodes length was #", len(nodes), "on", URL, "-->", redir, "-->urlORredir", urlORredir)
} else if nodes == nil {
fmt.Println("# unable to capture due to error", URL, "-->")
} else if accessDenied == true {
fmt.Println("SKIPPED ENTERING", URL)
} else {
fmt.Println("# somehow we got to this else. Nodes length was #", len(nodes), "on", URL, "-->", redir, "-->urlORredir", urlORredir)
}
duration := time.Since(start)
fmt.Printf("body is %v kb \n", len(str)/1000)
fmt.Println("URL", URL, " DURATION", duration)
}
type Worker struct {
Command `json:"Command"`
Worker string `json:"Worker"`
Urls []string `json:"URLs"`
SeedURLs map[string]string `json:"seedurls,omitempty"`
Params `json:"Params"`
Outputs `json:"Outputs"`
Endpoints `json:"Endpoints"`
}
type Command struct {
Cmd string `json:"Cmd"`
}
type Params struct {
Headless string `json:"headless,omitempty"`
Speed string `json:"speed,omitempty"`
GetHTML string `json:"gethtml,omitempty"`
}
type Outputs struct {
Mongodbname string `json:"mongodbname,omitempty"`
Elasticname string `json:"elasticname,omitempty"`
}
type TabContent struct {
Command `json:"Command"`
Params `json:"Params"`
Outputs `json:"Outputs"`
}
type Connections struct {
Ctx context.Context
Nsqp *nsq.Producer
MongoClient *mongo.Client
TabNum int
TimeOut int
}
type URLSeedChan struct {
URL string
SeedURL string
}
type Endpoints struct {
MongodbLocation string `json:"mongodblocation,omitempty"`
ElasticLocation string `json:"elasticlocation,omitempty"`
PostgresLocation string `json:"postgreslocation,omitempty"`
}
type EndpointOptions struct {
URL string
I int
Wg *sync.WaitGroup
Regexes *regexp.Regexp
P *nsq.Producer
Elasticname string
Mongodbname string
Space *regexp.Regexp
}