-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.go
More file actions
119 lines (106 loc) · 2.49 KB
/
worker.go
File metadata and controls
119 lines (106 loc) · 2.49 KB
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
/*
Download images from album by album URL.
```sh
imgurfetch -h
Usage of imgurfetch:
imgurfetch [arguments] <url> [path(default: .)]
-g group images by resolution
-r duration
rate limit(how often requests could happen)
-w int
number of workers (default 10)
```
*/
package imgurfetch
import (
"context"
"errors"
"fmt"
"github.com/rs/zerolog/log"
"golang.org/x/time/rate"
"io/ioutil"
"net/http"
"os"
"path"
)
const imageURLTpl = "%s/%s%s"
//ImageWorker - contains information about how to download images
// and where to store them. Worker receives tasks from "in" channel.
//when task is done it send signal to "done" channel.
//Before each task it asks limiter to get permission for execution.
type ImageWorker struct {
hostname string //i.imgur.com
in <-chan Image
done chan<- struct{}
path string
grByRes bool
http *http.Client
limit *rate.Limiter
}
//NewWorker create new worker instance.
//If grByRes is true, it will create sub directory WxH.
func NewWorker(host string, in <-chan Image, done chan<- struct{}, path string, grByRes bool, l *rate.Limiter, hc *http.Client) *ImageWorker {
if hc == nil {
hc = http.DefaultClient
}
return &ImageWorker{
host,
in,
done,
path,
grByRes,
hc,
l,
}
}
//Run loop which waits tasks in "in" channel until ctx signals done.
//Before executing tasks it asks limiter for permission.
func (w *ImageWorker) Run(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case img := <-w.in:
if err := w.limit.Wait(ctx); err != nil {
if !errors.Is(err, context.Canceled) {
log.Err(err).Send()
}
}
err := w.imageDownload(img)
if err != nil {
log.Err(err).Send()
}
w.done <- struct{}{}
}
}
}
//imageDownload downloads image and saves it to w.path
//If path is not exist, function will try to create it.
//If flag grByRes is set, it will create sub directory WxH.
func (w *ImageWorker) imageDownload(img Image) error {
url := fmt.Sprintf(imageURLTpl, w.hostname, img.Hash, img.Ext)
res, err := w.http.Get(url)
if err != nil {
return err
}
if res.StatusCode >= 400 {
return errors.New(res.Status)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
ipath := w.path
if w.grByRes {
ipath = path.Join(ipath, fmt.Sprintf("%dx%d", img.Width, img.Height))
}
err = os.MkdirAll(ipath, 0777)
if err != nil {
return err
}
err = ioutil.WriteFile(path.Join(ipath, img.Hash+img.Ext), body, 0644)
if err != nil {
return err
}
return nil
}