/
imgparse.go
419 lines (378 loc) · 10.8 KB
/
imgparse.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
package imgserver
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/asaskevich/govalidator"
"sync"
"time"
"github.com/cenk/backoff"
"golang.org/x/net/context"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
type imgTag struct {
srcIndex int
attr []html.Attribute
}
func (img *imgTag) setSrc(src string) {
img.attr[img.srcIndex].Val = src
}
func (img imgTag) src() string {
return img.attr[img.srcIndex].Val
}
func (img imgTag) isDataURL() bool {
return strings.HasPrefix(img.src(), "data:")
}
var supportedImgAttributes = map[string]bool{
"src": true,
"alt": true,
"style": true,
"longdesc": true,
"width": true,
"height": true,
}
func (img imgTag) token() html.Token {
return html.Token{
Type: html.StartTagToken,
DataAtom: atom.Img,
Data: "img",
Attr: img.attr,
}
}
//run goroutine that parse http and goroutine for image download
type imgExtractor interface {
//read html data from r and return all <img> tags converted to data:URL form
extractImages(ctx context.Context, r io.Reader) ([]imgTag, error)
}
type imgExtractorFunc func(ctx context.Context, r io.Reader) ([]imgTag, error)
func (f imgExtractorFunc) extractImages(ctx context.Context, r io.Reader) ([]imgTag, error) {
return f(ctx, r)
}
type imgExtractorImp struct {
parser imageParser
fetcher imageFetcher
}
func (imp imgExtractorImp) extractImages(ctx context.Context, r io.Reader) ([]imgTag, error) {
log := getLocalLogger(ctx, "extractImages")
log.Debug("Extracting images")
ctx, cancel := context.WithCancel(ctx)
parseResChan, parseErrChan := imp.parser.parseImage(ctx, r)
// by contract all fetch subrotines should write either to res either to err channel
fetchResChan := make(chan imgTag)
fetchErrChan := make(chan error)
await := 0 //number of fetch routines to await
var result []imgTag
//await subroutines on panic or
defer func() {
cancel() // cancel subroutines fetch requests
//await canceled subroutines
log.WithField("fetchToAwait", await).Debug("awaiting")
for ; await > 0; await-- {
select {
case <-fetchResChan:
log.Debug("img awaited")
case <-fetchErrChan:
log.Debug("error awaited")
}
}
//for debug close fetch channels
//leaked fetch subroutine will cause panic on closed channel
close(fetchResChan)
close(fetchErrChan)
}()
folderURL := *getFolderURL(*getURLParam(ctx))
log.Debug("Async await")
//while parsing in process and fetch tasks not finished
for parseResChan != nil || await > 0 {
select {
case img, ok := <-parseResChan:
log.Debug("Async got image")
if !ok {
//check if parse finish successful
log.Debug("parse finished succesfuly")
//disable parse channels on parse finish
parseResChan = nil
parseErrChan = nil
continue
}
//create new fetch routine on img
if img.isDataURL() {
log.Debug("img with data URL parsed")
result = append(result, img)
continue
}
imgURL, err := getImgURL(img.src(), folderURL)
if err != nil {
return nil, err
}
log.WithField("token", img.token().String()).
Debug("img parsed. Send for fetching")
await++
log.Debug("Async fetching image")
imp.fetcher.fetchImage(ctx, img, imgURL, fetchResChan, fetchErrChan)
case err := <-parseErrChan:
log.Debug("parse finished with error")
return nil, err
case img := <-fetchResChan:
log.Debug("img fetched")
await--
result = append(result, img)
case err := <-fetchErrChan:
log.Debug("error on img fetch")
await--
return nil, err
}
}
log.Debug("Async await Done")
return result, nil
}
type imageFetcher interface {
// try to download parsedImage
// on success send only img to imgc
// on fail send only error to errc
fetchImage(ctx context.Context, img imgTag, imgURL string, imgc chan<- imgTag, errc chan<- error)
}
type imageFetcherFunc func(ctx context.Context, img imgTag, imgURL string, imgc chan<- imgTag, errc chan<- error)
func (f imageFetcherFunc) fetchImage(ctx context.Context, img imgTag, imgURL string, imgc chan<- imgTag, errc chan<- error) {
f(ctx, img, imgURL, imgc, errc)
}
func fetchImage(ctx context.Context, img imgTag, imgURL string, imgc chan<- imgTag, errc chan<- error) {
go func() {
resp, err := cxtAwareGet(ctx, imgURL)
if err != nil {
errc <- &HandlerError{500, "can't fetch image: " + imgURL, err}
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
errc <- NewHandlerError(400, fmt.Sprintf("expected status code 200 but found %v on image: %v )", resp.StatusCode, imgURL))
return
}
ct := strings.TrimSpace(resp.Header.Get("Content-Type"))
if ct == "" {
errc <- NewHandlerError(400, "no content-type on image: "+imgURL)
return
}
if !strings.HasPrefix(ct, "image") {
errc <- NewHandlerError(400, "not image content-type on image: "+imgURL)
return
}
dataURLBuf := bytes.NewBufferString("data:")
dataURLBuf.WriteString(ct)
dataURLBuf.WriteString(";base64,")
w := base64.NewEncoder(base64.StdEncoding, dataURLBuf)
defer w.Close()
_, err = io.Copy(w, resp.Body)
if err != nil {
errc <- &HandlerError{400, "image fetching error: " + imgURL, err}
return
}
resImg := imgTag{ //copy
img.srcIndex,
append([]html.Attribute{}, img.attr...),
}
resImg.setSrc(dataURLBuf.String())
imgc <- resImg
}()
}
type backoffImageFetcher struct {
backoffLock *sync.Mutex
backoff backoff.BackOff
}
func (h backoffImageFetcher) NextBackOff() time.Duration {
h.backoffLock.Lock()
res := h.backoff.NextBackOff()
h.backoffLock.Unlock()
return res
}
func (h backoffImageFetcher) Reset() {
h.backoffLock.Lock()
h.backoff.Reset()
h.backoffLock.Unlock()
}
func (bif backoffImageFetcher) fetchImage(ctx context.Context, img imgTag, imgURL string, imgc chan<- imgTag, errc chan<- error) {
go func() {
log := getLocalLogger(ctx, "backoffFetcher")
var (
opErr error
opImg * imgTag
)
operation := func() error {
// return err on retry need, or just returns
log.Debug("Another try")
//TODO remove code duplication
resp, err := cxtAwareGet(ctx, imgURL)
if err != nil {
log.Debug("Get error")
opErr = &HandlerError{500, "can't fetch image: " + imgURL, err}
return nil
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
//retry on server error
log.Debug("Got server error response -> do next try")
return &HandlerError{500, "need retry", nil}
}
if resp.StatusCode != http.StatusOK {
opErr = NewHandlerError(400, fmt.Sprintf("expected status code 200 but found %v on image: %v )", resp.StatusCode, imgURL))
return nil
}
ct := strings.TrimSpace(resp.Header.Get("Content-Type"))
if ct == "" {
opErr = NewHandlerError(400, "no content-type on image: "+imgURL)
return nil
}
if !strings.HasPrefix(ct, "image") {
opErr = NewHandlerError(400, "not image content-type on image: "+imgURL)
return nil
}
dataURLBuf := bytes.NewBufferString("data:")
dataURLBuf.WriteString(ct)
dataURLBuf.WriteString(";base64,")
w := base64.NewEncoder(base64.StdEncoding, dataURLBuf)
defer w.Close()
_, err = io.Copy(w, resp.Body)
if err != nil {
opErr = &HandlerError{400, "image fetching error: " + imgURL, err}
return nil
}
opImg = &imgTag{ //copy
img.srcIndex,
append([]html.Attribute{}, img.attr...),
}
opImg.setSrc(dataURLBuf.String())
return nil
}
//err := backoff.Retry(operation, bif)
err := backoff.Retry(operation, backoff.NewExponentialBackOff())
if err != nil {
errc <- err
} else {
if opErr != nil {
errc <- err
} else {
imgc <- img
}
}
}()
}
type imageParser interface {
//parse html content in separate goroutine and send imgTags to output img chan
//img chan will be closed on parse finish
//on parse error, parser send err to error chan before finish
//err chan is unbuffered
parseImage(ctx context.Context, r io.Reader) (<-chan imgTag, <-chan error)
}
type imageParserFunc func(ctx context.Context, r io.Reader) (<-chan imgTag, <-chan error)
func (f imageParserFunc) parseImage(ctx context.Context, r io.Reader) (<-chan imgTag, <-chan error) {
return f(ctx, r)
}
type imageParserImp struct {
tokenParse imgTokenParser
}
//TODO test
func (imp imageParserImp) parseImage(ctx context.Context, r io.Reader) (<-chan imgTag, <-chan error) {
imgc := make(chan imgTag)
errc := make(chan error)
go func() {
// on error, error is send before deffer, so receiver got error, and then close signal
defer func() {
close(imgc)
}() // indicate finish
z := html.NewTokenizer(r)
for {
tokenType := z.Next()
if tokenType == html.ErrorToken {
if z.Err() != io.EOF {
//EOF == successful finish
errc <- z.Err() //block until receiver got error
}
return
}
token := z.Token()
switch tokenType {
case html.SelfClosingTagToken:
fallthrough
case html.StartTagToken: // <tag>
if token.DataAtom != atom.Img || token.Data != "img" {
continue
}
img, err := imp.tokenParse.parseImgToken(token)
if err != nil {
errc <- err
return
}
imgc <- img
}
}
}()
return imgc, errc
}
type imgTokenParser interface {
parseImgToken(token html.Token) (imgTag, error)
}
type imgTokenParserFunc func(token html.Token) (imgTag, error)
func (f imgTokenParserFunc) parseImgToken(token html.Token) (imgTag, error) {
return f(token)
}
func parseImgToken(token html.Token) (imgTag, error) {
img := imgTag{-1, make([]html.Attribute, 0, len(token.Attr))}
for i, attr := range token.Attr {
key := attr.Key
if supportedImgAttributes[key] {
if key == "src" {
img.srcIndex = len(img.attr)
}
img.attr = append(img.attr, token.Attr[i])
}
}
if img.srcIndex < 0 {
return imgTag{}, NewHandlerError(400, "no src attribute for <img/> tag")
}
return img, nil
}
func getFolderURL(pageURL url.URL) *url.URL {
pageURL.Fragment = ""
pageURL.RawQuery = ""
pageURL.Path = strings.Trim(pageURL.Path, "/")
if !strings.ContainsRune(pageURL.Path, '/') {
pageURL.Path = ""
} else {
split := strings.Split(pageURL.Path, "/")
pageURL.Path = strings.Join(split[:len(split)-1], "/")
}
return &pageURL
}
func getImgURL(src string, folderURL url.URL) (string, error) {
imgSrcURL, err := url.Parse(src)
if err != nil {
return "", &HandlerError{400, "invalid img tag src URL: url parse", err}
}
var res string
if imgSrcURL.IsAbs() {
res = src
} else if strings.HasPrefix(src, "//") {
//yep, is absolute too
res = "http:" + src
} else if src[0] == '/' {
folderURL.Path = src
folderURL.RawPath = src
res = folderURL.String()
} else {
folderStr := strings.TrimRight(folderURL.String(), "/") //caulse relative
if folderStr[len(folderStr)-1] == '/' {
res = folderStr + src
} else {
res = folderStr + "/" + src
}
}
if !govalidator.IsURL(res) {
return "", &HandlerError{400, "invalid img tag src URL: is not valid URL", err}
}
return res, nil
}