This repository was archived by the owner on Nov 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
233 lines (210 loc) · 4.66 KB
/
main.go
File metadata and controls
233 lines (210 loc) · 4.66 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
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
package main
import (
"bufio"
"context"
"expvar"
"flag"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)
// Flags
var (
outDir string
idListPath string
idFormat int
nRoutines int
useFastHTTP bool
timeout time.Duration
reportI time.Duration
)
var ctx context.Context
var idListWriter *bufio.Writer
var stats struct {
reqs *expvar.Int
done *expvar.Int
failed *expvar.Int
}
const (
IDBoth = iota
ID5
ID7
)
func init() {
stats.reqs = expvar.NewInt("reqs")
stats.failed = expvar.NewInt("failed")
stats.done = expvar.NewInt("done")
rand.Seed(time.Now().UnixNano())
}
func main() {
flag.StringVar(&outDir, "out-dir", "./images", "Directory containing images")
flag.StringVar(&idListPath, "id-list", "./ids.txt", "List with downloaded IDs")
idFormatStr := flag.String("id-format", "both", "ID format to scrape (id5, id7, both)")
flag.BoolVar(&useFastHTTP, "fasthttp", false, "Use fasthttp (HTTP/1.1) library instead of stdlib HTTP")
flag.IntVar(&nRoutines, "routines", runtime.NumCPU(), "Number of instances to run in parallel")
flag.DurationVar(&timeout, "timeout", 10*time.Second, "Request timeout")
flag.DurationVar(&reportI, "report-interval", time.Second, "Report interval")
monBind := flag.String("expvar-bind", ":6960", "Where to run expvar HTTP server (off to disable)")
flag.Parse()
if err := os.MkdirAll(outDir, 0777); err != nil {
log.Fatalf("Failed to make out dir: %s", err)
}
switch strings.ToLower(*idFormatStr) {
case "id5":
idFormat = ID5
case "id7":
idFormat = ID7
case "both":
idFormat = IDBoth
default:
log.Fatal("Invalid ID format specified")
}
switch *monBind {
case "off", "":
break
default:
go func() {
err := http.ListenAndServe(*monBind, expvar.Handler())
if err != nil {
log.Fatalf("Failed to bind monitoring: %s", err)
}
}()
}
if idListPath != "" {
idListFile, err := os.OpenFile(idListPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0777)
if err != nil {
log.Fatalf("Failed to open ID list: %s", err)
}
defer idListFile.Close()
idListWriter = bufio.NewWriter(idListFile)
defer idListWriter.Flush()
}
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(context.Background())
go func() {
intC := make(chan os.Signal)
signal.Notify(intC, os.Interrupt)
<-intC
log.Print("Shutting down")
cancel()
}()
var wg sync.WaitGroup
wg.Add(nRoutines)
go reporter(reportI)
for i := 0; i < nRoutines; i++ {
go dumper(&wg)
}
wg.Wait()
}
func dumper(wg *sync.WaitGroup) {
defer wg.Done()
var req Requester
if useFastHTTP {
req = NewFastHTTPRequester()
} else {
req = NewVanillaRequester()
}
for {
select {
case <-ctx.Done():
return
default:
id := nextID()
exists, err := dumpNext(req, id)
if err != nil {
stats.failed.Add(1)
log.Printf("ERR Failed to dump %s: %s", id, err)
}
if exists && idListWriter != nil {
stats.done.Add(1)
_, _ = idListWriter.WriteString(id)
_ = idListWriter.WriteByte('\n')
}
}
}
}
func dumpNext(req Requester, id string) (bool, error) {
// Check if exists
exists, err := req.Exists(id)
stats.reqs.Add(1)
if err != nil {
return false, err
}
if !exists {
return false, nil
}
// Open file
f, err := os.Create(filepath.Join(outDir, fmt.Sprintf("%s.jpg", id)))
if err != nil {
return true, err
}
defer f.Close()
// Write to file
err = req.StreamTo(id, f)
stats.reqs.Add(1)
return true, err
}
func reporter(interval time.Duration) {
start := time.Now()
var lastCount int64
for {
select {
case <-ctx.Done():
return
case <-time.Tick(interval):
reqs := stats.reqs.Value()
done := stats.done.Value()
failed := stats.failed.Value()
delta := done - lastCount
perSecond := float64(delta) / interval.Seconds()
average := float64(done) / time.Since(start).Seconds()
log.Printf("%10d reqs |\t %10d done |\t%6d fail |\t%6.0f dl/s cur |\t%6.0f dl/s avg",
reqs, done, failed, perSecond, average)
lastCount = done
}
}
}
func nextID() string {
switch idFormat {
case ID5:
return nextID5()
case ID7:
return nextID7()
default:
if rand.Intn(2) == 0 {
return nextID5()
} else {
return nextID7()
}
}
}
var charList = []byte("abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"1234567890")
func nextID5() string {
var chars [5]byte
for i := range chars {
chars[i] = charList[rand.Intn(len(charList))]
}
return string(chars[:])
}
func nextID7() string {
var chars [7]byte
for i := range chars {
chars[i] = charList[rand.Intn(len(charList))]
}
return string(chars[:])
}
type Requester interface {
Exists(id string) (bool, error)
StreamTo(id string, w io.Writer) error
}