forked from markusmobius/go-trafilatura
/
sitemap-downloader.go
185 lines (151 loc) · 4.28 KB
/
sitemap-downloader.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
// This file is part of go-trafilatura, Go package for extracting readable
// content, comments and metadata from a web page. Source available in
// <https://github.com/AlirezaNeGe/go-trafilatura>.
// Copyright (C) 2021 Markus Mobius
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"context"
"fmt"
"net/http"
nurl "net/url"
"strings"
"sync"
"time"
betree "github.com/beevik/etree"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
)
type sitemapDownloader struct {
sync.RWMutex
cache map[string]struct{}
semaphore *semaphore.Weighted
httpClient *http.Client
userAgent string
delay time.Duration
filterFunc func(*nurl.URL) bool
}
func (sd *sitemapDownloader) downloadURLs(ctx context.Context, urls []*nurl.URL) []*nurl.URL {
pageURLs := []*nurl.URL{}
g, ctx := errgroup.WithContext(context.Background())
for _, url := range urls {
url := url
g.Go(func() error {
// Make sure this url hasn't been downloaded
if sd.isDownloaded(url) {
return nil
}
// Acquire semaphore to limit concurrent download
err := sd.semaphore.Acquire(ctx, 1)
if err != nil {
return nil
}
// Download and parse url
newSitemapURLs, newPageURLs, err := sd.downloadURL(url)
sd.markAsDownloaded(url)
sd.semaphore.Release(1)
if err != nil {
logrus.Warnf("failed to parse sitemap: %v", err)
return nil
}
// Process the additional urls
additionalPageURLs := sd.downloadURLs(ctx, newSitemapURLs)
// Save all page URLs
sd.Lock()
pageURLs = append(pageURLs, newPageURLs...)
pageURLs = append(pageURLs, additionalPageURLs...)
sd.Unlock()
return nil
})
}
g.Wait()
// Make sure page URLs are unique
uniquePageURLs := []*nurl.URL{}
uniqueTracker := make(map[string]struct{})
for _, url := range pageURLs {
if sd.filterFunc != nil && !sd.filterFunc(url) {
continue
}
strURL := url.String()
if _, exist := uniqueTracker[strURL]; exist {
continue
}
uniqueTracker[strURL] = struct{}{}
uniquePageURLs = append(uniquePageURLs, url)
}
return uniquePageURLs
}
func (sd *sitemapDownloader) downloadURL(url *nurl.URL) ([]*nurl.URL, []*nurl.URL, error) {
// Download URL
strURL := url.String()
logrus.Println("downloading sitemap", strURL)
resp, err := download(sd.httpClient, sd.userAgent, strURL)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
// Make sure it's XML
contentType := resp.Header.Get("Content-Type")
if !sd.contentIsXML(contentType) {
return nil, nil, fmt.Errorf("%s is not xml: \"%s\"", strURL, contentType)
}
// Parse
doc := betree.NewDocument()
if _, err := doc.ReadFrom(resp.Body); err != nil {
return nil, nil, err
}
pageURLs := []*nurl.URL{}
sitemapURLs := []*nurl.URL{}
for _, loc := range doc.FindElements("//loc") {
parsedURL, valid := validateURL(loc.Text())
if !valid {
continue
}
parent := loc.Parent()
if parent == nil {
continue
}
switch parent.Tag {
case "url":
pageURLs = append(pageURLs, parsedURL)
case "sitemap":
sitemapURLs = append(sitemapURLs, parsedURL)
}
}
// Add delay (to prevent too many request to target server)
time.Sleep(sd.delay)
return sitemapURLs, pageURLs, nil
}
func (sd *sitemapDownloader) isDownloaded(url *nurl.URL) bool {
sd.RLock()
defer sd.RUnlock()
_, processed := sd.cache[url.String()]
return processed
}
func (sd *sitemapDownloader) markAsDownloaded(url *nurl.URL) {
sd.Lock()
sd.cache[url.String()] = struct{}{}
sd.Unlock()
}
func (sd *sitemapDownloader) contentIsXML(contentType string) bool {
switch {
case strings.Contains(contentType, "text/xml"),
strings.Contains(contentType, "application/xml"):
return true
default:
return false
}
}