mirror of
https://github.com/foomo/walker.git
synced 2026-12-04 10:51:48 +00:00
hello world
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
.*
|
||||
!.git*
|
||||
/frontend/.next
|
||||
/frontend/node_modules
|
||||
@@ -0,0 +1,8 @@
|
||||
test-prod-a:
|
||||
GOOS=linux go build -o /tmp/test-prod-a cmd/walker/walker.go
|
||||
scp -C /tmp/test-prod-a demo.globus-stage.bestbytes.net:~/.
|
||||
ssh demo.globus-stage.bestbytes.net ./test-prod-a
|
||||
test-prod-b:
|
||||
GOOS=linux go build -o /tmp/test-prod-b cmd/walker/walker.go
|
||||
scp -C /tmp/test-prod-b demo.globus-stage.bestbytes.net:~/.
|
||||
ssh demo.globus-stage.bestbytes.net ./test-prod-b
|
||||
@@ -0,0 +1,11 @@
|
||||
# Walker
|
||||
|
||||
Walker walkes through websites and collects performance and SEO relevant data. The results can be browsed through a web interface. Apart from that they are exposed as prometheus metrics.
|
||||
|
||||
## Configuration
|
||||
|
||||
```yaml
|
||||
---
|
||||
|
||||
...
|
||||
```
|
||||
@@ -0,0 +1,5 @@
|
||||
target: http://www.bestbytes.de
|
||||
addr: ":3001"
|
||||
frontend: "http://localhost:3000"
|
||||
ignore:
|
||||
- /foomo
|
||||
@@ -0,0 +1,71 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/foomo/walker"
|
||||
"github.com/foomo/walker/config"
|
||||
)
|
||||
|
||||
type server struct {
|
||||
servicePath string
|
||||
serviveProxy http.Handler
|
||||
p *httputil.ReverseProxy
|
||||
}
|
||||
|
||||
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, s.servicePath) {
|
||||
fmt.Println("service call", r.URL.Path)
|
||||
s.serviveProxy.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
fmt.Println("proxying", r.URL.Path)
|
||||
s.p.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func must(comment string, err error) {
|
||||
if err != nil {
|
||||
fmt.Println(comment, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
flag.Parse()
|
||||
if len(flag.Args()) != 1 {
|
||||
fmt.Println("usage:", os.Args[0], "path/to/config.yaml")
|
||||
os.Exit(1)
|
||||
}
|
||||
conf, errConf := config.Get(flag.Arg(0))
|
||||
must("config error:", errConf)
|
||||
spew.Dump(conf)
|
||||
proxyURL, errProxyURL := url.Parse(conf.Frontend)
|
||||
must("can not parse frontend url: "+conf.Frontend+" :", errProxyURL)
|
||||
fmt.Println("proxying frontend requests to", proxyURL)
|
||||
if conf.UseCookies {
|
||||
fmt.Println("using cookies")
|
||||
cookieJar, _ := cookiejar.New(nil)
|
||||
http.DefaultClient.Jar = cookieJar
|
||||
}
|
||||
|
||||
s, errS := walker.NewService(conf)
|
||||
must("could not start service", errS)
|
||||
|
||||
serviceProxy := walker.NewDefaultServiceGoTSRPCProxy(s, []string{})
|
||||
|
||||
log.Fatal(http.ListenAndServe(conf.Addr, &server{
|
||||
servicePath: serviceProxy.EndPoint,
|
||||
serviveProxy: serviceProxy,
|
||||
p: httputil.NewSingleHostReverseProxy(proxyURL),
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
|
||||
yaml "gopkg.in/yaml.v1"
|
||||
)
|
||||
|
||||
type CheckContent struct {
|
||||
Title bool
|
||||
Description bool
|
||||
Tags []string
|
||||
}
|
||||
|
||||
type Group struct {
|
||||
Routes []string
|
||||
CheckContent *CheckContent
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Frontend string
|
||||
Addr string
|
||||
Target string
|
||||
Groups []*Group
|
||||
Ignore []string
|
||||
UseCookies bool
|
||||
}
|
||||
|
||||
func Get(filename string) (conf *Config, err error) {
|
||||
yamlBytes, errRead := ioutil.ReadFile(filename)
|
||||
if errRead != nil {
|
||||
err = errRead
|
||||
return
|
||||
}
|
||||
errUnmarshal := yaml.Unmarshal(yamlBytes, &conf)
|
||||
if errUnmarshal != nil {
|
||||
err = errUnmarshal
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package walker
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
)
|
||||
|
||||
type Heading struct {
|
||||
Level int
|
||||
Text string
|
||||
}
|
||||
type LinkedData struct {
|
||||
Context string `json:"@context"`
|
||||
Type string ` json:"@type"`
|
||||
}
|
||||
type Structure struct {
|
||||
Title string
|
||||
Description string
|
||||
Headings []Heading
|
||||
LinkedData []LinkedData
|
||||
Canonical string
|
||||
LinkPrev string
|
||||
LinkNext string
|
||||
// <link rel="prev" href="/herren/herrenmode/jacken">
|
||||
// <link rel="next" href="/herren/herrenmode/jacken?page=3">
|
||||
// <link rel="canonical" href="https://www.globus.ch/damen/damenmode/kleider">
|
||||
}
|
||||
|
||||
func extractStructure(doc *goquery.Document) (s Structure, err error) {
|
||||
description, _ := doc.Find("meta[name=description]").First().Attr("content")
|
||||
s = Structure{
|
||||
Title: doc.Find("title").First().Text(),
|
||||
Description: description,
|
||||
}
|
||||
doc.Find("link[rel=prev], link[rel=next], link[rel=canonical]").Each(func(i int, sel *goquery.Selection) {
|
||||
attrRelVal, attrRelOK := sel.Attr("rel")
|
||||
attrHref, attrHrefOK := sel.Attr("href")
|
||||
if attrRelOK && attrHrefOK {
|
||||
switch attrRelVal {
|
||||
case "canonical":
|
||||
s.Canonical = attrHref
|
||||
case "prev":
|
||||
s.LinkPrev = attrHref
|
||||
case "next":
|
||||
s.LinkNext = attrHref
|
||||
}
|
||||
}
|
||||
})
|
||||
doc.Find("script[type=\"application/ld+json\"]").Each(func(i int, sel *goquery.Selection) {
|
||||
ld := &LinkedData{}
|
||||
errDoc := json.Unmarshal([]byte(sel.Text()), &ld)
|
||||
if errDoc != nil {
|
||||
fmt.Println("json crap", errDoc)
|
||||
return
|
||||
}
|
||||
s.LinkedData = append(s.LinkedData, *ld)
|
||||
})
|
||||
doc.Find("h1, h2, h3, h4, h5, h6").Each(func(i int, sel *goquery.Selection) {
|
||||
level := 0
|
||||
switch sel.Get(0).Data {
|
||||
case "h1":
|
||||
level = 1
|
||||
case "h2":
|
||||
level = 2
|
||||
case "h3":
|
||||
level = 3
|
||||
case "h4":
|
||||
level = 4
|
||||
case "h5":
|
||||
level = 5
|
||||
case "h6":
|
||||
level = 6
|
||||
}
|
||||
s.Headings = append(s.Headings, Heading{
|
||||
Level: level,
|
||||
Text: sel.Text(),
|
||||
})
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package walker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
const testDocHTML = `
|
||||
<html>
|
||||
<head>
|
||||
<title>Hello Test</title>
|
||||
<meta name="description" content="this is a test doc and i am a description">
|
||||
<link rel="canonical" href="https://www.globus.ch/damen/damenmode/kleider">
|
||||
<link rel="prev" href="/herren/herrenmode/jacken">
|
||||
<link rel="next" href="/herren/herrenmode/jacken?page=3">
|
||||
</head>
|
||||
<body>
|
||||
<h1>h1-0</h1>
|
||||
<h2>h2-0</h2>
|
||||
<h2>h2-1</h2>
|
||||
<h3>h3-0</h3>
|
||||
<h1>h1-1</h1>
|
||||
<h2>h2-2</h2>
|
||||
<script type="application/ld+json">{"@context":"http://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/","name":"Globus"}},{"@type":"ListItem","position":2,"item":{"@id":"/home-living","name":"Home & Living"}},{"@type":"ListItem","position":3,"item":{"@id":"/home-living/weihnachten","name":"Weihnachten"}},{"@type":"ListItem","position":4,"item":{"@id":"/home-living/weihnachten/baumschmuck","name":"Baumschmuck"}},{"@type":"ListItem","position":5,"item":{"@id":"/globus-baumschmuck-schwan-bu0937790012000","name":"Baumschmuck SCHWAN"}}]}</script>
|
||||
<script type="application/ld+json">{"@context":"http://schema.org/","@type":"Product","name":"Baumschmuck SCHWAN","image":"https://www.globus.ch/media/shop/1894881/1538742072000","color":"weiss","brand":{"@type":"Thing","name":"GLOBUS"},"description":"Ist mundgeblasen, Ist handbemalt, Made in Europe","offers":[{"@type":"Offer","sku":"1257706000","price":"12.90","category":"Globus > Home & Living > Weihnachten > Baumschmuck","priceCurrency":"CHF","itemCondition":"NewCondition","availability":"InStock"}]}</script>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
const emptyDocHTML = ``
|
||||
|
||||
func getDoc(t *testing.T, html string) *goquery.Document {
|
||||
htmlReader := bytes.NewReader([]byte(html))
|
||||
doc, errDoc := goquery.NewDocumentFromReader(htmlReader)
|
||||
assert.Nil(t, errDoc)
|
||||
return doc
|
||||
}
|
||||
|
||||
func TestExtract(t *testing.T) {
|
||||
testDoc := getDoc(t, testDocHTML)
|
||||
emptyDoc := getDoc(t, emptyDocHTML)
|
||||
testDocStructure, eStucture := extractStructure(testDoc)
|
||||
t.Log(testDocStructure, eStucture)
|
||||
spew.Dump(testDocStructure)
|
||||
emptyDocStructure, eStucture := extractStructure(emptyDoc)
|
||||
t.Log(emptyDocStructure, eStucture)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import fetch from 'isomorphic-unfetch';
|
||||
import { ServiceClient } from './service/service';
|
||||
|
||||
const getTransport = endpoint => async (method, args = []) => {
|
||||
const uri = endpoint + '/' + encodeURIComponent(method);
|
||||
let lastResponse: any;
|
||||
console.log('fetching', uri);
|
||||
return fetch(uri, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(args),
|
||||
})
|
||||
.then(r => {
|
||||
// console.log(endpoint, 'response', r);
|
||||
return r.text();
|
||||
})
|
||||
.then(text => {
|
||||
lastResponse = text;
|
||||
return JSON.parse(text);
|
||||
})
|
||||
.catch(e => {
|
||||
console.error('getTransport', e, lastResponse);
|
||||
// e.lastResponse = lastResponse;
|
||||
return e;
|
||||
});
|
||||
};
|
||||
|
||||
interface ServiceConstructor<ST> extends Function {
|
||||
defaultEndpoint: string;
|
||||
prototype: ST;
|
||||
new (transport: <T>(method: string, data?: any[]) => Promise<T>): ST;
|
||||
}
|
||||
|
||||
const getAsyncClient = <T>(clientClass: ServiceConstructor<T>, endpoint?: string) => {
|
||||
if (endpoint === undefined) {
|
||||
endpoint = clientClass.defaultEndpoint;
|
||||
}
|
||||
return new clientClass(getTransport(endpoint));
|
||||
};
|
||||
|
||||
// export const getPrefixedAsyncClient = <T>(clientClass: ServiceConstructor<T>, prefix: string = ''): T => {
|
||||
// return new clientClass(getTransport(prefix + clientClass.defaultEndpoint));
|
||||
// };
|
||||
|
||||
|
||||
export const LOAD_RESULTS = 'LOAD_RESULTS';
|
||||
|
||||
export const getResults = () => {
|
||||
const client = getAsyncClient(ServiceClient);
|
||||
try {
|
||||
let stats = client.getStatus();
|
||||
console.log(stats);
|
||||
} catch(error) {
|
||||
console.error("fu", error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
const withTypescript = require('@zeit/next-typescript')
|
||||
module.exports = withTypescript()
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "1.0.0",
|
||||
"description": "walker frontend",
|
||||
"main": "index.js",
|
||||
"author": "janhalfar",
|
||||
"license": "MIT",
|
||||
"private": false,
|
||||
"scripts": {
|
||||
"dev": "next",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"type-check": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/plugin-proposal-export-default-from": "^7.0.0",
|
||||
"@types/next": "^7.0.3",
|
||||
"@types/react": "^16.4.18",
|
||||
"@types/react-dom": "^16.0.9",
|
||||
"@types/react-redux": "^6.0.9",
|
||||
"@types/redux": "^3.6.0",
|
||||
"@types/styled-components": "^4.0.3",
|
||||
"@zeit/next-typescript": "^1.1.1",
|
||||
"isomorphic-unfetch": "^3.0.0",
|
||||
"next": "^7.0.2",
|
||||
"react": "^16.6.0",
|
||||
"react-dom": "^16.6.0",
|
||||
"react-redux": "^5.1.0",
|
||||
"redux": "^4.0.1",
|
||||
"styled-components": "^4.0.3",
|
||||
"typescript": "^3.1.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import Document, { DocumentProps, Head, Main, NextScript } from 'next/document';
|
||||
import React from 'react';
|
||||
import { ServerStyleSheet } from 'styled-components';
|
||||
|
||||
export interface GlobusDocumentProps extends DocumentProps {
|
||||
// Inject style tags for styled components
|
||||
styleTags: React.ReactElement<{}>[];
|
||||
}
|
||||
|
||||
class GlobusDocument extends Document<GlobusDocumentProps> {
|
||||
static getInitialProps = async ({ renderPage }) => {
|
||||
const sheet = new ServerStyleSheet();
|
||||
const page = renderPage(App => props => sheet.collectStyles(<App {...props} />));
|
||||
const styleTags = sheet.getStyleElement();
|
||||
return { ...page, styleTags };
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<html>
|
||||
<Head>
|
||||
{this.props.styleTags}
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
</Head>
|
||||
|
||||
<body>
|
||||
<Main />
|
||||
<NextScript />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const nextGlobusDocument = GlobusDocument;
|
||||
|
||||
export default GlobusDocument;
|
||||
@@ -0,0 +1,188 @@
|
||||
import React from "react";
|
||||
import { styled } from "../theme";
|
||||
import { ServiceClient } from "../service/service";
|
||||
import { getAsyncClient } from "../service/utils";
|
||||
import { ScrapeResult, FilterOptions } from "../service/vo-walker";
|
||||
|
||||
const Page = styled.div`
|
||||
padding: 2rem;
|
||||
font-family: sans-serif;
|
||||
a, input, th, td, button {
|
||||
font-size: 1rem;
|
||||
}
|
||||
input, button {
|
||||
border: 1px solid grey;
|
||||
border-radius: none;
|
||||
padding: 1rem;
|
||||
}
|
||||
button {
|
||||
background-color: grey;
|
||||
}
|
||||
table, tr, td {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
}
|
||||
`;
|
||||
|
||||
|
||||
const ScanResultRow = styled.tr`
|
||||
&:nth-child(even) {
|
||||
background-color: grey;
|
||||
}
|
||||
td {
|
||||
padding: 0.5rem;
|
||||
text-overflow: ellipsis;
|
||||
overflow: hidden;
|
||||
}
|
||||
`;
|
||||
|
||||
const StatusList = styled.ul`
|
||||
margin: 0;
|
||||
`;
|
||||
|
||||
const StatusListItem = styled.ul`
|
||||
margin: .5rem;
|
||||
padding: .5rem;
|
||||
list-style: none;
|
||||
display: inline-block;
|
||||
border: ${props => (props.selected ? "1px solid red" : "")};
|
||||
background-color: green;
|
||||
color: white;
|
||||
`;
|
||||
|
||||
const Pager = styled.div`
|
||||
border: 1px solid red;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
`;
|
||||
const PagerButton = styled.button`
|
||||
flex-direction: row;
|
||||
border: 1px solid black;
|
||||
`;
|
||||
|
||||
interface IndexProps {}
|
||||
|
||||
interface State {
|
||||
prefix: string;
|
||||
page: number;
|
||||
numPages: number;
|
||||
pageSize:number;
|
||||
status: number[];
|
||||
results: ScrapeResult[];
|
||||
filterOptions: FilterOptions;
|
||||
}
|
||||
|
||||
class Index extends React.Component<IndexProps, State> {
|
||||
private client: ServiceClient;
|
||||
constructor(props: IndexProps) {
|
||||
super(props);
|
||||
this.state = {
|
||||
filterOptions: {
|
||||
Status: [],
|
||||
MinDur: 0,
|
||||
MaxDur: 0
|
||||
},
|
||||
page: 0,
|
||||
numPages: 0,
|
||||
pageSize:100,
|
||||
status: [],
|
||||
results: [],
|
||||
prefix: ""
|
||||
};
|
||||
this.client = getAsyncClient(ServiceClient);
|
||||
}
|
||||
getResults = () => {
|
||||
this.client
|
||||
.getResults(
|
||||
{
|
||||
Prefix: this.state.prefix,
|
||||
Status: this.state.status,
|
||||
MinDur: 0,
|
||||
MaxDur: 0
|
||||
},
|
||||
this.state.page,
|
||||
this.state.pageSize,
|
||||
)
|
||||
.then(response => {
|
||||
console.log(response);
|
||||
this.setState({
|
||||
results: response.results,
|
||||
filterOptions: response.filterOptions,
|
||||
numPages: response.numPages
|
||||
});
|
||||
});
|
||||
};
|
||||
page = (inc:number) => {
|
||||
this.setState({page:this.state.page+inc});
|
||||
this.getResults()
|
||||
}
|
||||
render() {
|
||||
return (
|
||||
<Page>
|
||||
Hello
|
||||
<form
|
||||
onSubmit={e => {
|
||||
e.preventDefault();
|
||||
console.log("time to submit");
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="search"
|
||||
placeholder="enter a prefix to filter"
|
||||
onChange={e =>
|
||||
this.setState({
|
||||
prefix: e.target.value
|
||||
})
|
||||
}
|
||||
/>
|
||||
<StatusList>
|
||||
{this.state.filterOptions.Status.sort(
|
||||
(a, b) => (a.Code > b.Code ? 1 : -1)
|
||||
).map(s => (
|
||||
<StatusListItem
|
||||
selected={this.state.status.indexOf(s.Code) > -1}
|
||||
key={s.Code}
|
||||
onClick={e => {
|
||||
this.setState({ status: [s.Code] });
|
||||
}}
|
||||
>
|
||||
{s.Code} {s.Count}
|
||||
</StatusListItem>
|
||||
))}
|
||||
</StatusList>
|
||||
<button onClick={this.getResults}>load</button>
|
||||
</form>
|
||||
<Pager>
|
||||
<PagerButton onClick={e => this.page(-1)}>Prev</PagerButton>
|
||||
{this.state.page} / {this.state.numPages}
|
||||
<PagerButton onClick={e => this.page(1)}>Next</PagerButton>
|
||||
</Pager>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Code</th>
|
||||
<th>Error</th>
|
||||
<th>Duration ms</th>
|
||||
<th>url</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{this.state.results.map((r, i) => (
|
||||
<ScanResultRow key={i}>
|
||||
<td>{this.state.page * this.state.pageSize + i}</td>
|
||||
<td>{r.Code}</td>
|
||||
<td>{r.Error}</td>
|
||||
<td>{Math.round(r.Duration / 10000)}</td>
|
||||
<td>{r.TargetURL}</td>
|
||||
</ScanResultRow>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default Index;
|
||||
@@ -0,0 +1,18 @@
|
||||
/* tslint:disable */
|
||||
// hello commonjs - we need some imports - sorted in alphabetical order, by go package
|
||||
import * as github_com_foomo_walker from './vo-walker'; // frontend/service/service.ts to frontend/service/vo-walker.ts
|
||||
|
||||
export class ServiceClient {
|
||||
public static defaultEndpoint = "/service/walker";
|
||||
constructor(
|
||||
public transport:<T>(method: string, data?: any[]) => Promise<T>
|
||||
) {}
|
||||
async getResults(filters:github_com_foomo_walker.Filters, page:number, pageSize:number):Promise<{filterOptions:github_com_foomo_walker.FilterOptions; results:github_com_foomo_walker.ScrapeResult[]; numPages:number}> {
|
||||
let response = await this.transport<{0:github_com_foomo_walker.FilterOptions; 1:github_com_foomo_walker.ScrapeResult[]; 2:number}>("GetResults", [filters, page, pageSize])
|
||||
let responseObject = {filterOptions : response[0], results : response[1], numPages : response[2]};
|
||||
return responseObject;
|
||||
}
|
||||
async getStatus():Promise<github_com_foomo_walker.ServiceStatus> {
|
||||
return (await this.transport<{0:github_com_foomo_walker.ServiceStatus}>("GetStatus", []))[0]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import fetch from 'isomorphic-unfetch';
|
||||
|
||||
export const getTransport = endpoint => async (method, args = []) => {
|
||||
const uri = endpoint + '/' + encodeURIComponent(method);
|
||||
let lastResponse: any;
|
||||
console.log('fetching', uri);
|
||||
return fetch(uri, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(args),
|
||||
})
|
||||
.then(r => {
|
||||
// console.log(endpoint, 'response', r);
|
||||
return r.text();
|
||||
})
|
||||
.then(text => {
|
||||
lastResponse = text;
|
||||
return JSON.parse(text);
|
||||
})
|
||||
.catch(e => {
|
||||
console.error('getTransport', e, lastResponse);
|
||||
// e.lastResponse = lastResponse;
|
||||
return e;
|
||||
});
|
||||
};
|
||||
|
||||
export interface ServiceConstructor<ST> extends Function {
|
||||
defaultEndpoint: string;
|
||||
prototype: ST;
|
||||
new (transport: <T>(method: string, data?: any[]) => Promise<T>): ST;
|
||||
}
|
||||
|
||||
export const getAsyncClient = <T>(clientClass: ServiceConstructor<T>, endpoint?: string) => {
|
||||
if (endpoint === undefined) {
|
||||
endpoint = clientClass.defaultEndpoint;
|
||||
}
|
||||
return new clientClass(getTransport(endpoint));
|
||||
};
|
||||
|
||||
export const getPrefixedAsyncClient = <T>(clientClass: ServiceConstructor<T>, prefix: string = ''): T => {
|
||||
return new clientClass(getTransport(prefix + clientClass.defaultEndpoint));
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
/* tslint:disable */
|
||||
// hello commonjs - we need some imports - sorted in alphabetical order, by go package
|
||||
import * as github_com_foomo_walker from './vo-walker'; // frontend/service/vo-walker.ts to frontend/service/vo-walker.ts
|
||||
// github.com/foomo/walker.FilterOptions
|
||||
export interface FilterOptions {
|
||||
Status:github_com_foomo_walker.StatusStats[];
|
||||
MinDur:number;
|
||||
MaxDur:number;
|
||||
}
|
||||
// github.com/foomo/walker.Filters
|
||||
export interface Filters {
|
||||
Prefix:string;
|
||||
Status:number[];
|
||||
MinDur:number;
|
||||
MaxDur:number;
|
||||
}
|
||||
// github.com/foomo/walker.Heading
|
||||
export interface Heading {
|
||||
Level:number;
|
||||
Text:string;
|
||||
}
|
||||
// github.com/foomo/walker.LinkList
|
||||
export interface LinkList {
|
||||
[index:string]:number;
|
||||
}
|
||||
// github.com/foomo/walker.LinkedData
|
||||
export interface LinkedData {
|
||||
@context:string;
|
||||
@type:string;
|
||||
}
|
||||
// github.com/foomo/walker.ScrapeResult
|
||||
export interface ScrapeResult {
|
||||
TargetURL:string;
|
||||
Error:string;
|
||||
Code:number;
|
||||
Status:string;
|
||||
ContentType:string;
|
||||
Length:number;
|
||||
Links:github_com_foomo_walker.LinkList;
|
||||
Duration:number;
|
||||
Structure:github_com_foomo_walker.Structure;
|
||||
}
|
||||
// github.com/foomo/walker.ServiceStatus
|
||||
export interface ServiceStatus {
|
||||
TargetURL:string;
|
||||
Open:number;
|
||||
Done:number;
|
||||
Pending:number;
|
||||
}
|
||||
// github.com/foomo/walker.StatusStats
|
||||
export interface StatusStats {
|
||||
Code:number;
|
||||
Count:number;
|
||||
}
|
||||
// github.com/foomo/walker.Structure
|
||||
export interface Structure {
|
||||
Title:string;
|
||||
Description:string;
|
||||
Headings:github_com_foomo_walker.Heading[];
|
||||
LinkedData:github_com_foomo_walker.LinkedData[];
|
||||
Canonical:string;
|
||||
LinkPrev:string;
|
||||
LinkNext:string;
|
||||
}
|
||||
// end of common js
|
||||
@@ -0,0 +1,14 @@
|
||||
import * as styledComponents from "styled-components";
|
||||
import { ThemedStyledComponentsModule } from "styled-components";
|
||||
|
||||
export interface ThemeInterface {
|
||||
primaryColor: string;
|
||||
primaryColorInverted: string;
|
||||
}
|
||||
|
||||
const myStyledComponents = styledComponents as ThemedStyledComponentsModule<ThemeInterface>;
|
||||
|
||||
export const styled = myStyledComponents.default;
|
||||
|
||||
// export { styled, css, injectGlobal, keyframes, ThemeProvider };
|
||||
// export styled;
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
"jsx": "preserve",
|
||||
"lib": ["dom", "es2017"],
|
||||
"moduleResolution": "node",
|
||||
"allowJs": true,
|
||||
"noEmit": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"skipLibCheck": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"removeComments": false,
|
||||
"preserveConstEnums": true,
|
||||
"sourceMap": true
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+5014
File diff suppressed because it is too large
Load Diff
+90
@@ -0,0 +1,90 @@
|
||||
// Code generated by gotsrpc https://github.com/foomo/gotsrpc - DO NOT EDIT.
|
||||
|
||||
package walker
|
||||
|
||||
import (
|
||||
http "net/http"
|
||||
time "time"
|
||||
|
||||
gotsrpc "github.com/foomo/gotsrpc"
|
||||
)
|
||||
|
||||
type ServiceGoTSRPCProxy struct {
|
||||
EndPoint string
|
||||
allowOrigin []string
|
||||
service *Service
|
||||
}
|
||||
|
||||
func NewDefaultServiceGoTSRPCProxy(service *Service, allowOrigin []string) *ServiceGoTSRPCProxy {
|
||||
return &ServiceGoTSRPCProxy{
|
||||
EndPoint: "/service/walker",
|
||||
allowOrigin: allowOrigin,
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
func NewServiceGoTSRPCProxy(service *Service, endpoint string, allowOrigin []string) *ServiceGoTSRPCProxy {
|
||||
return &ServiceGoTSRPCProxy{
|
||||
EndPoint: endpoint,
|
||||
allowOrigin: allowOrigin,
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// ServeHTTP exposes your service
|
||||
func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
for _, origin := range p.allowOrigin {
|
||||
// todo we have to compare this with the referer ... and only send one
|
||||
w.Header().Add("Access-Control-Allow-Origin", origin)
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
if r.Method != http.MethodPost {
|
||||
if r.Method == http.MethodOptions {
|
||||
return
|
||||
}
|
||||
gotsrpc.ErrorMethodNotAllowed(w)
|
||||
return
|
||||
}
|
||||
|
||||
var args []interface{}
|
||||
funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)
|
||||
callStats := gotsrpc.GetStatsForRequest(r)
|
||||
if callStats != nil {
|
||||
callStats.Func = funcName
|
||||
callStats.Package = "github.com/foomo/walker"
|
||||
callStats.Service = "Service"
|
||||
}
|
||||
switch funcName {
|
||||
case "GetResults":
|
||||
var (
|
||||
arg_filters Filters
|
||||
arg_page int
|
||||
arg_pageSize int
|
||||
)
|
||||
args = []interface{}{&arg_filters, &arg_page, &arg_pageSize}
|
||||
err := gotsrpc.LoadArgs(&args, callStats, r)
|
||||
if err != nil {
|
||||
gotsrpc.ErrorCouldNotLoadArgs(w)
|
||||
return
|
||||
}
|
||||
executionStart := time.Now()
|
||||
getResultsFilterOptions, getResultsResults, getResultsNumPages := p.service.GetResults(arg_filters, arg_page, arg_pageSize)
|
||||
if callStats != nil {
|
||||
callStats.Execution = time.Now().Sub(executionStart)
|
||||
}
|
||||
gotsrpc.Reply([]interface{}{getResultsFilterOptions, getResultsResults, getResultsNumPages}, callStats, r, w)
|
||||
return
|
||||
case "GetStatus":
|
||||
executionStart := time.Now()
|
||||
getStatusRet := p.service.GetStatus()
|
||||
if callStats != nil {
|
||||
callStats.Execution = time.Now().Sub(executionStart)
|
||||
}
|
||||
gotsrpc.Reply([]interface{}{getStatusRet}, callStats, r, w)
|
||||
return
|
||||
default:
|
||||
gotsrpc.ClearStats(r)
|
||||
http.Error(w, "404 - not found "+r.URL.Path, http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
modulekind: commonjs
|
||||
# if you want an async api vs classic callbacks - here you are
|
||||
tsclientflavor: async
|
||||
targets:
|
||||
demo:
|
||||
services:
|
||||
/service/walker: Service
|
||||
package: github.com/foomo/walker
|
||||
out: frontend/service/service.ts
|
||||
tsrpc:
|
||||
- Service
|
||||
|
||||
mappings:
|
||||
github.com/foomo/walker:
|
||||
out: frontend/service/vo-walker.ts
|
||||
...
|
||||
@@ -0,0 +1,59 @@
|
||||
// Code generated by gotsrpc https://github.com/foomo/gotsrpc - DO NOT EDIT.
|
||||
|
||||
package walker
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
gotsrpc "github.com/foomo/gotsrpc"
|
||||
)
|
||||
|
||||
type ServiceGoTSRPCClient interface {
|
||||
GetResults(filters Filters, page int, pageSize int) (filterOptions FilterOptions, results []ScrapeResult, numPages int, clientErr error)
|
||||
GetStatus() (retGetStatus_0 ServiceStatus, clientErr error)
|
||||
SetClientEncoding(encoding gotsrpc.ClientEncoding)
|
||||
SetTransportHttpClient(client *http.Client)
|
||||
}
|
||||
|
||||
type tsrpcServiceGoTSRPCClient struct {
|
||||
URL string
|
||||
EndPoint string
|
||||
Client gotsrpc.Client
|
||||
}
|
||||
|
||||
func NewDefaultServiceGoTSRPCClient(url string) ServiceGoTSRPCClient {
|
||||
return NewServiceGoTSRPCClient(url, "/service/walker")
|
||||
}
|
||||
|
||||
func NewServiceGoTSRPCClient(url string, endpoint string) ServiceGoTSRPCClient {
|
||||
return NewServiceGoTSRPCClientWithClient(url, "/service/walker", nil)
|
||||
}
|
||||
|
||||
func NewServiceGoTSRPCClientWithClient(url string, endpoint string, client *http.Client) ServiceGoTSRPCClient {
|
||||
return &tsrpcServiceGoTSRPCClient{
|
||||
URL: url,
|
||||
EndPoint: endpoint,
|
||||
Client: gotsrpc.NewClientWithHttpClient(client),
|
||||
}
|
||||
}
|
||||
|
||||
func (tsc *tsrpcServiceGoTSRPCClient) SetClientEncoding(encoding gotsrpc.ClientEncoding) {
|
||||
tsc.Client.SetClientEncoding(encoding)
|
||||
}
|
||||
|
||||
func (tsc *tsrpcServiceGoTSRPCClient) SetTransportHttpClient(client *http.Client) {
|
||||
tsc.Client.SetTransportHttpClient(client)
|
||||
}
|
||||
func (tsc *tsrpcServiceGoTSRPCClient) GetResults(filters Filters, page int, pageSize int) (filterOptions FilterOptions, results []ScrapeResult, numPages int, clientErr error) {
|
||||
args := []interface{}{filters, page, pageSize}
|
||||
reply := []interface{}{&filterOptions, &results, &numPages}
|
||||
clientErr = tsc.Client.Call(tsc.URL, tsc.EndPoint, "GetResults", args, reply)
|
||||
return
|
||||
}
|
||||
|
||||
func (tsc *tsrpcServiceGoTSRPCClient) GetStatus() (retGetStatus_0 ServiceStatus, clientErr error) {
|
||||
args := []interface{}{}
|
||||
reply := []interface{}{&retGetStatus_0}
|
||||
clientErr = tsc.Client.Call(tsc.URL, tsc.EndPoint, "GetStatus", args, reply)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package walker
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
)
|
||||
|
||||
type Scraper struct {
|
||||
}
|
||||
|
||||
type LinkList map[string]int
|
||||
|
||||
type ScrapeResult struct {
|
||||
// index || noindex
|
||||
// <link rel="next" href="/damen/damentaschen/alle-taschen?page=2">
|
||||
// <meta name="robots" content="index,follow,noodp">
|
||||
TargetURL string
|
||||
Error string
|
||||
Code int
|
||||
Status string
|
||||
ContentType string
|
||||
Length int
|
||||
Links LinkList
|
||||
Duration time.Duration
|
||||
Structure Structure
|
||||
// duplication title, descr, h1
|
||||
// blocking robots txt
|
||||
}
|
||||
|
||||
var ErrorNoBody = "no body"
|
||||
|
||||
func Scrape(targetURL string, chanResult chan ScrapeResult) {
|
||||
result := ScrapeResult{
|
||||
Code: 0,
|
||||
TargetURL: targetURL,
|
||||
}
|
||||
start := time.Now()
|
||||
resp, errGet := http.Get(targetURL)
|
||||
if errGet != nil {
|
||||
result.Error = errGet.Error()
|
||||
chanResult <- result
|
||||
return
|
||||
}
|
||||
result.Duration = time.Now().Sub(start)
|
||||
result.Code = resp.StatusCode
|
||||
result.Status = resp.Status
|
||||
if resp.Body == nil {
|
||||
result.Error = ErrorNoBody
|
||||
chanResult <- result
|
||||
return
|
||||
}
|
||||
|
||||
result.ContentType = resp.Header.Get("Content-type")
|
||||
|
||||
if strings.Contains(result.ContentType, "html") {
|
||||
|
||||
doc, errNewDoc := goquery.NewDocumentFromResponse(resp)
|
||||
if errNewDoc != nil {
|
||||
result.Error = errNewDoc.Error()
|
||||
chanResult <- result
|
||||
return
|
||||
}
|
||||
|
||||
// result.Length = ???
|
||||
|
||||
linkList, errExtract := extractLinks(doc)
|
||||
resp.Body.Close()
|
||||
if errExtract != nil {
|
||||
result.Error = errExtract.Error()
|
||||
chanResult <- result
|
||||
return
|
||||
}
|
||||
result.Links = linkList
|
||||
|
||||
structure, errExtractStructure := extractStructure(doc)
|
||||
if errExtractStructure != nil {
|
||||
result.Error = errExtractStructure.Error()
|
||||
return
|
||||
}
|
||||
result.Structure = structure
|
||||
} else {
|
||||
|
||||
}
|
||||
chanResult <- result
|
||||
return
|
||||
}
|
||||
|
||||
func extractLinks(doc *goquery.Document) (linkList LinkList, err error) {
|
||||
linkList = LinkList{}
|
||||
doc.Find("a").Each(func(i int, s *goquery.Selection) {
|
||||
href, exists := s.Attr("href")
|
||||
if exists && href != "" {
|
||||
linkList[href]++
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
package walker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/foomo/walker/config"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
w *Walker
|
||||
targetURL string
|
||||
}
|
||||
|
||||
func NewService(conf *config.Config) (s *Service, err error) {
|
||||
w := NewWalker(32)
|
||||
w.Walk(conf.Target, conf.Ignore...)
|
||||
s = &Service{
|
||||
w: w,
|
||||
targetURL: conf.Target,
|
||||
}
|
||||
go func() {
|
||||
lastScanned := 0
|
||||
for {
|
||||
status := s.w.GetStatus()
|
||||
w.PrintStatus(status)
|
||||
scanned := len(status.Results)
|
||||
scannedInLoop := scanned - lastScanned
|
||||
line()
|
||||
fmt.Println("scanned", scannedInLoop, "in 5s => scan speed @", (float64(scannedInLoop) / 5.0), " docs/s")
|
||||
line()
|
||||
line()
|
||||
lastScanned = scanned
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
func filter(resultMap map[string]ScrapeResult, filterChain filterChain) {
|
||||
for targetURL, scrapeResult := range resultMap {
|
||||
for _, filterFunc := range filterChain {
|
||||
if !filterFunc(scrapeResult) {
|
||||
delete(resultMap, targetURL)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type filterFunc func(result ScrapeResult) bool
|
||||
type filterChain []filterFunc
|
||||
|
||||
type Filters struct {
|
||||
Prefix string
|
||||
Status []int
|
||||
MinDur time.Duration
|
||||
MaxDur time.Duration
|
||||
}
|
||||
|
||||
type StatusStats struct {
|
||||
Code int
|
||||
Count int
|
||||
}
|
||||
|
||||
type FilterOptions struct {
|
||||
Status []StatusStats
|
||||
MinDur time.Duration
|
||||
MaxDur time.Duration
|
||||
}
|
||||
|
||||
func getFilterChain(filters Filters) filterChain {
|
||||
chain := filterChain{}
|
||||
if filters.Prefix != "" {
|
||||
chain = append(chain, func(result ScrapeResult) bool {
|
||||
return strings.HasPrefix(result.TargetURL, filters.Prefix)
|
||||
})
|
||||
}
|
||||
if len(filters.Status) > 0 {
|
||||
chain = append(chain, func(result ScrapeResult) bool {
|
||||
for _, status := range filters.Status {
|
||||
if result.Code == status {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
if filters.MaxDur > 0 {
|
||||
chain = append(chain, func(result ScrapeResult) bool {
|
||||
return result.Duration < filters.MaxDur
|
||||
})
|
||||
}
|
||||
if filters.MinDur > 0 {
|
||||
chain = append(chain, func(result ScrapeResult) bool {
|
||||
return result.Duration > filters.MinDur
|
||||
})
|
||||
}
|
||||
return chain
|
||||
}
|
||||
|
||||
func getFilterOptions(resultMap map[string]ScrapeResult) FilterOptions {
|
||||
statusMap := map[int]int{}
|
||||
minDur := time.Duration(1000000000000000000)
|
||||
maxDur := time.Duration(0)
|
||||
for _, result := range resultMap {
|
||||
statusMap[result.Code]++
|
||||
if result.Duration > maxDur {
|
||||
maxDur = result.Duration
|
||||
}
|
||||
if result.Duration < minDur {
|
||||
minDur = result.Duration
|
||||
}
|
||||
}
|
||||
statusStats := []StatusStats{}
|
||||
for code, count := range statusMap {
|
||||
statusStats = append(statusStats, StatusStats{
|
||||
Code: code,
|
||||
Count: count,
|
||||
})
|
||||
}
|
||||
return FilterOptions{
|
||||
Status: statusStats,
|
||||
MinDur: minDur,
|
||||
MaxDur: maxDur,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) GetResults(
|
||||
filters Filters,
|
||||
page int,
|
||||
pageSize int,
|
||||
) (filterOptions FilterOptions, results []ScrapeResult, numPages int) {
|
||||
resultMap := s.w.GetStatus().Results
|
||||
|
||||
filterOptions = getFilterOptions(resultMap)
|
||||
if filters.Prefix != "" {
|
||||
filters.Prefix = s.targetURL + filters.Prefix
|
||||
}
|
||||
filter(resultMap, getFilterChain(filters))
|
||||
|
||||
i := 0
|
||||
results = make([]ScrapeResult, len(resultMap))
|
||||
|
||||
urls := make([]string, len(resultMap))
|
||||
for url := range resultMap {
|
||||
urls[i] = url
|
||||
i++
|
||||
}
|
||||
sort.Strings(urls)
|
||||
for index, url := range urls {
|
||||
results[index] = resultMap[url]
|
||||
}
|
||||
// paging is missing
|
||||
numPages = len(results) / pageSize
|
||||
min := 0
|
||||
max := len(results)
|
||||
start := page * pageSize
|
||||
end := start + pageSize
|
||||
|
||||
if start < min {
|
||||
start = min
|
||||
}
|
||||
if end > max {
|
||||
end = max
|
||||
}
|
||||
fmt.Println("slice", start, end)
|
||||
if end > start {
|
||||
results = results[start:end]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Service) GetStatus() ServiceStatus {
|
||||
walkerStatus := s.w.GetStatus()
|
||||
open := 0
|
||||
pending := 0
|
||||
for _, active := range walkerStatus.Jobs {
|
||||
if active {
|
||||
pending++
|
||||
} else {
|
||||
open++
|
||||
}
|
||||
}
|
||||
return ServiceStatus{
|
||||
TargetURL: s.targetURL,
|
||||
Done: len(walkerStatus.Results),
|
||||
Open: open,
|
||||
Pending: pending,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package walker
|
||||
|
||||
type Validation struct {
|
||||
}
|
||||
|
||||
func validate(strctr Structure) (v Validation) {
|
||||
v = Validation{}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package walker
|
||||
|
||||
type ServiceStatus struct {
|
||||
TargetURL string
|
||||
Open int
|
||||
Done int
|
||||
Pending int
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package walker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type start struct {
|
||||
targetURL string
|
||||
ignore []string
|
||||
}
|
||||
|
||||
type Status struct {
|
||||
Results map[string]ScrapeResult
|
||||
Jobs map[string]bool
|
||||
}
|
||||
|
||||
type Walker struct {
|
||||
concurrency int
|
||||
chanResult chan ScrapeResult
|
||||
chanStart chan start
|
||||
chanStatus chan Status
|
||||
chanErrStart chan error
|
||||
}
|
||||
|
||||
func NewWalker(concurrency int) *Walker {
|
||||
w := &Walker{
|
||||
concurrency: concurrency,
|
||||
chanResult: make(chan ScrapeResult),
|
||||
chanStart: make(chan start),
|
||||
chanStatus: make(chan Status),
|
||||
chanErrStart: make(chan error),
|
||||
}
|
||||
go w.main()
|
||||
return w
|
||||
}
|
||||
|
||||
func (w *Walker) main() {
|
||||
running := 0
|
||||
jobs := map[string]bool{}
|
||||
results := map[string]ScrapeResult{}
|
||||
ignore := []string{}
|
||||
var baseURL *url.URL
|
||||
for {
|
||||
select {
|
||||
case st := <-w.chanStart:
|
||||
ignore = st.ignore
|
||||
startU, errParseStartU := url.Parse(st.targetURL)
|
||||
if errParseStartU == nil {
|
||||
baseURL = startU
|
||||
running = 0
|
||||
jobs = map[string]bool{st.targetURL: false}
|
||||
results = map[string]ScrapeResult{}
|
||||
w.chanErrStart <- nil
|
||||
} else {
|
||||
w.chanErrStart <- errParseStartU
|
||||
}
|
||||
case <-w.chanStatus:
|
||||
resultsCopy := make(map[string]ScrapeResult, len(results))
|
||||
for targetURL, result := range results {
|
||||
resultsCopy[targetURL] = result
|
||||
}
|
||||
jobsCopy := make(map[string]bool, len(jobs))
|
||||
for targetURL, active := range jobs {
|
||||
jobsCopy[targetURL] = active
|
||||
}
|
||||
w.chanStatus <- Status{
|
||||
Results: resultsCopy,
|
||||
Jobs: jobsCopy,
|
||||
}
|
||||
case scanResult := <-w.chanResult:
|
||||
running--
|
||||
// fmt.Println("got a result", scanResult)
|
||||
delete(jobs, scanResult.TargetURL)
|
||||
results[scanResult.TargetURL] = scanResult
|
||||
|
||||
for linkURL := range scanResult.Links {
|
||||
// no paging
|
||||
if scanResult.Structure.LinkNext == linkURL ||
|
||||
scanResult.Structure.LinkPrev == linkURL {
|
||||
// fmt.Println("skipping pager link", linkURL)
|
||||
continue
|
||||
}
|
||||
|
||||
// ok, time to really look at that url
|
||||
linkU, errParseLinkU := normalizeLink(baseURL, linkURL)
|
||||
if errParseLinkU == nil {
|
||||
|
||||
// to be ignored ?!
|
||||
ignoreLink := false
|
||||
for _, ignorePrefix := range ignore {
|
||||
if strings.HasPrefix(linkU.Path, ignorePrefix) {
|
||||
ignoreLink = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if linkU.Host == baseURL.Host &&
|
||||
linkU.Scheme == baseURL.Scheme && !ignoreLink {
|
||||
scanResult.Links[linkU.String()] = scanResult.Links[linkURL]
|
||||
linkURL = linkU.String()
|
||||
_, existingResultOK := results[linkURL]
|
||||
_, existingJobOK := jobs[linkURL]
|
||||
if !existingResultOK && !existingJobOK {
|
||||
jobs[linkURL] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(jobs) > 0 {
|
||||
for jobURL, jobActive := range jobs {
|
||||
if running >= w.concurrency {
|
||||
// fmt.Println("pool exceeded")
|
||||
break
|
||||
}
|
||||
if !jobActive {
|
||||
running++
|
||||
jobs[jobURL] = true
|
||||
go Scrape(jobURL, w.chanResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeLink(baseURL *url.URL, linkURL string) (normalizedLink *url.URL, err error) {
|
||||
// let us ditch anchors
|
||||
anchorParts := strings.Split(linkURL, "#")
|
||||
linkURL = anchorParts[0]
|
||||
link, errParseLink := url.Parse(linkURL)
|
||||
if errParseLink != nil {
|
||||
err = errParseLink
|
||||
return
|
||||
}
|
||||
// host
|
||||
if link.Host == "" {
|
||||
link.Host = baseURL.Host
|
||||
}
|
||||
// scheme
|
||||
if link.Scheme == "" || link.Scheme == "//" {
|
||||
link.Scheme = baseURL.Scheme
|
||||
}
|
||||
if baseURL.User != nil {
|
||||
link.User = baseURL.User
|
||||
}
|
||||
// it is beautiful now
|
||||
normalizedLink = link
|
||||
return
|
||||
}
|
||||
|
||||
func (w *Walker) Walk(targetURL string, ignore ...string) error {
|
||||
w.chanStart <- start{
|
||||
targetURL: targetURL,
|
||||
ignore: ignore,
|
||||
}
|
||||
return <-w.chanErrStart
|
||||
}
|
||||
|
||||
func (w *Walker) GetStatus() Status {
|
||||
w.chanStatus <- Status{}
|
||||
return <-w.chanStatus
|
||||
}
|
||||
|
||||
func line() {
|
||||
fmt.Println("------------------------------------------------------------------------")
|
||||
}
|
||||
func headline(v ...interface{}) {
|
||||
line()
|
||||
v = append([]interface{}{"~"}, v...)
|
||||
fmt.Println(v...)
|
||||
line()
|
||||
}
|
||||
|
||||
func (w *Walker) PrintStatus(status Status) {
|
||||
headline("Status: ", " jobs: ", len(status.Jobs), ", results: ", len(status.Results))
|
||||
statusCodes := map[int]int{}
|
||||
notFoundKeys := []string{}
|
||||
notFoundMap := map[string]ScrapeResult{}
|
||||
errorKeys := []string{}
|
||||
errorMap := map[string]ScrapeResult{}
|
||||
for targetURL, result := range status.Results {
|
||||
statusCodes[result.Code]++
|
||||
switch true {
|
||||
case result.Code == 404:
|
||||
notFoundKeys = append(notFoundKeys, targetURL)
|
||||
notFoundMap[targetURL] = result
|
||||
case result.Code > 500:
|
||||
errorKeys = append(errorKeys, targetURL)
|
||||
errorMap[targetURL] = result
|
||||
}
|
||||
}
|
||||
sort.Strings(errorKeys)
|
||||
sort.Strings(notFoundKeys)
|
||||
|
||||
fmt.Println(statusCodes)
|
||||
type bucket struct {
|
||||
Name string
|
||||
From time.Duration
|
||||
To time.Duration
|
||||
Show bool
|
||||
}
|
||||
|
||||
buckets := []bucket{
|
||||
bucket{
|
||||
Name: "awesome < 50 ms",
|
||||
From: time.Duration(time.Millisecond * 0),
|
||||
To: time.Duration(time.Millisecond * 50),
|
||||
Show: false,
|
||||
},
|
||||
bucket{
|
||||
Name: "great < 100 ms",
|
||||
From: time.Duration(time.Millisecond * 50),
|
||||
To: time.Duration(time.Millisecond * 100),
|
||||
},
|
||||
bucket{
|
||||
Name: "ok < 200 ms",
|
||||
From: time.Duration(time.Millisecond * 100),
|
||||
To: time.Duration(time.Millisecond * 200),
|
||||
},
|
||||
bucket{
|
||||
Name: "not too good < 300 ms",
|
||||
From: time.Duration(time.Millisecond * 200),
|
||||
To: time.Duration(time.Millisecond * 300),
|
||||
Show: false,
|
||||
},
|
||||
bucket{
|
||||
Name: "meh < 500 ms",
|
||||
From: time.Duration(time.Millisecond * 300),
|
||||
To: time.Duration(time.Millisecond * 500),
|
||||
Show: false,
|
||||
},
|
||||
bucket{
|
||||
Name: "bad < 1 s",
|
||||
From: time.Duration(time.Millisecond * 500),
|
||||
To: time.Duration(time.Millisecond * 1000),
|
||||
Show: false,
|
||||
},
|
||||
bucket{
|
||||
Name: "really bad < 3 s",
|
||||
From: time.Duration(time.Millisecond * 1000),
|
||||
To: time.Duration(time.Millisecond * 3000),
|
||||
Show: false,
|
||||
},
|
||||
bucket{
|
||||
Name: "ouch < 5 s",
|
||||
From: time.Duration(time.Millisecond * 3000),
|
||||
To: time.Duration(time.Millisecond * 5000),
|
||||
Show: false,
|
||||
},
|
||||
bucket{
|
||||
Name: "catastrophic < 10 s",
|
||||
From: time.Duration(time.Millisecond * 5000),
|
||||
To: time.Duration(time.Millisecond * 10000),
|
||||
Show: false,
|
||||
},
|
||||
bucket{
|
||||
Name: "end of the world > 10 s",
|
||||
From: time.Duration(time.Millisecond * 10000),
|
||||
To: time.Duration(time.Hour),
|
||||
Show: false,
|
||||
},
|
||||
}
|
||||
for _, bucket := range buckets {
|
||||
bucketI := 0
|
||||
fmt.Println(bucket.Name, bucket.From, bucket.To)
|
||||
for _, result := range status.Results {
|
||||
if result.Duration > bucket.From && result.Duration < bucket.To {
|
||||
bucketI++
|
||||
if bucket.Show {
|
||||
fmt.Println(" ", result.Status, result.Duration, result.TargetURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Println(" -> bucket contains", bucketI)
|
||||
}
|
||||
headline("currently scanning")
|
||||
for targetURL, active := range status.Jobs {
|
||||
if active {
|
||||
fmt.Println(targetURL)
|
||||
}
|
||||
}
|
||||
headline("bad errors")
|
||||
|
||||
for _, targetURL := range errorKeys {
|
||||
result := status.Results[targetURL]
|
||||
fmt.Println(result.Code, result.Status, result.TargetURL, result.Error)
|
||||
// fmt.Println(result.Code, result.Status, result.ContentType, result.Duration, result.Error, result.TargetURL)
|
||||
|
||||
}
|
||||
headline("dead links")
|
||||
for _, targetURL := range notFoundKeys {
|
||||
fmt.Println(targetURL)
|
||||
// for _, result := range status.Results {
|
||||
// for link := range result.Links {
|
||||
// if link == targetURL {
|
||||
// fmt.Println(" ", result.TargetURL, result.Structure.Title)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
// for _, result := range status.Results {
|
||||
//fmt.Println(result.TargetURL, result.Code, result.Status, result.Error, len(result.Links))
|
||||
// }
|
||||
}
|
||||
Reference in New Issue
Block a user