-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoonshine.go
477 lines (407 loc) · 13 KB
/
moonshine.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package main
import (
"bufio"
"flag"
"fmt"
"log"
"math"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
SR "github.com/httpreserve/simplerequest"
)
// Example SHINE uri: https://www.webarchive.org.uk/shine/search?page=2&query=content_ffb:%220baddeed%22&sort=crawl_date&order=asc
// shineRequest holds the information needed to make a request to Shine.
type shineRequest struct {
shineURL string // https://www.webarchive.org.uk/shine/search?
page string // page=2
badDeed string // &query=content_ffb:"0baddeed"
sort string // sort=crawl_date, title, score, comain, content
order string // order=asc
}
var (
version = "dev-0.0.0"
commit = "000000000000000000000000000000000baddeed"
date = "1970-01-01T00:00:01Z"
)
var agent string = fmt.Sprintf("moonshine/%s", version)
// Search result limits to be kind to Shine.
const solrMaxPages int = 1000
const resultsPerPage int = 10
// Consistently limit requests via this app, e.g. download a single page
// or five pages. This also helps us play nice with the service.
const singlePage int = 1
const multiPage int = 5
// Limit the number of sampled results to return in sample mode.
const maxSample int = 20
// FFB for the GIF file format.
const ffbGIF string = "47494638"
// FFB for the first PPT format, which inspired this code.
const ffbBadDeed string = "0baddeed"
var (
vers bool
ffb string
gif bool
random bool
page int
list bool
stat bool
sample bool
)
func init() {
flag.StringVar(&ffb, "ffb", ffbBadDeed, "first four bytes of file to find")
flag.BoolVar(&gif, "gif", false, fmt.Sprintf("return a single gif (hex \"%s\")", ffbGIF))
flag.BoolVar(&list, "list", false, "list the first five pages from page number")
flag.BoolVar(&sample, "sample", false, "return a sampled list of up to 20 files across the maximum no. results")
flag.IntVar(&page, "page", 1, fmt.Sprintf("specify a page number to return from, [max: %d]", solrMaxPages))
flag.BoolVar(&random, "random", true, "return a random link to a file")
flag.BoolVar(&stat, "stats", false, "return statistics for the resource")
flag.BoolVar(&vers, "version", false, "Return version")
}
func minInt(int1 int, int2 int) int {
if int1 < int2 {
return int1
}
return int2
}
func newSearchString(newShine shineRequest) string {
searchString := fmt.Sprintf("%s?page=%s&%s&%s&%s", newShine.shineURL,
newShine.page,
newShine.badDeed,
newShine.sort,
newShine.order)
log.Printf("created URL: %s\n", searchString)
return searchString
}
func newRequest(badDeedURL string) SR.SimpleRequest {
sr, err := SR.Create("GET", badDeedURL)
if err != nil {
log.Fatalf("create request failed: %s\n", err)
}
sr.Agent(agent)
return sr
}
func parseHtmForResults(htm string) (int, error) {
// Look for: Results <span id="displayingXOfY">1 to 10 of 179</span>
var res string
// Splits on newlines by default.
scanner := bufio.NewScanner(strings.NewReader(htm))
for scanner.Scan() {
if strings.Contains(scanner.Text(), "<span id=\"displayingXOfY\">") {
res = strings.TrimSpace(scanner.Text())
res = strings.Replace(res, "Results <span id=\"displayingXOfY\">", "", 1)
res = strings.Replace(res, "</span>", "", 1)
res = strings.Replace(res, ",", "", -1)
resList := strings.Split(res, "of")
res, _ := strconv.ParseInt(strings.TrimSpace(resList[len(resList)-1]), 10, 32)
resInt := int(res)
return resInt, nil
}
if strings.Contains(scanner.Text(), "message:Service Temporarily Unavailable") {
log.Fatal("exiting: UKWA server is currently experiencing technical difficultues")
}
}
// if we arrive here, we've no results
return 0, fmt.Errorf("no results string in htm")
}
func parseHtmForLinks(htm string) ([]string, error) {
const httpIndex int = 1 // location in the split where the URL will be
var httpSlice []string
// Splits on newlines by default.
scanner := bufio.NewScanner(strings.NewReader(htm))
found := false
for scanner.Scan() {
if found {
lnk := strings.Split(strings.TrimSpace(scanner.Text()), "\"")[httpIndex]
if !strings.Contains(lnk, "http") &&
!strings.Contains(lnk, "https") {
return nil, fmt.Errorf("no http")
}
httpSlice = append(httpSlice, lnk)
found = false
}
if strings.Contains(scanner.Text(), "<h4 class=\"list-group-item-heading\">") {
found = true
}
if strings.Contains(scanner.Text(), "message:Service Temporarily Unavailable") {
log.Fatal("exiting: UKWA server is currently experiencing technical difficultues")
}
}
if len(httpSlice) == 0 {
return nil, fmt.Errorf("no results")
}
return httpSlice, nil
}
func statResults(resp string) (int, int, error) {
return statShineResults(resp)
}
func ping(badDeedURL string) (string, int, int) {
log.Printf("pinging URL: %s", badDeedURL)
req := newRequest(badDeedURL)
resp, _ := req.Do()
if resp.StatusCode != 200 {
log.Fatalf("unsuccessful request: %s", resp.StatusText)
}
// Stat the results at all times to understand what other processing
// is needed.
fileCount, pageCount, err := statResults(resp.Data)
if err != nil {
log.Println(err)
}
// Shine doesn't used a zero-based index.
if fileCount > 0 && pageCount == 0 {
pageCount = 1
}
return resp.Data, fileCount, pageCount
}
func concatenateResults(linkSlice []string, page string) ([]string, error) {
var res []string
var err error
res, err = parseHtmForLinks(page)
if err != nil {
return linkSlice, err
}
linkSlice = append(linkSlice, res...)
return linkSlice, nil
}
func getSinglePage(linkSlice []string, pageNumber int, badDeedRequest shineRequest) []string {
var err error
badDeedRequest.page = strconv.Itoa(pageNumber)
searchString := newSearchString(badDeedRequest)
sr := newRequest(searchString)
resp, _ := sr.Do()
if resp.StatusCode != 200 {
log.Fatalf("unsuccessful request: %s, exiting", resp.StatusText)
}
linkSlice, err = concatenateResults(linkSlice, resp.Data)
if err != nil {
log.Fatalf("%s", err)
}
return linkSlice
}
// listResults returns a slice of all results for a given page.
func listResults(badDeedRequest shineRequest, pageContent string, pageNumber int,
numberOfPages int) []string {
var linkSlice []string
var err error
if numberOfPages == 1 && pageNumber == 1 {
log.Println("first result already in memory")
linkSlice, err = concatenateResults(linkSlice, pageContent)
if err != nil {
log.Fatalf("%s", err)
}
return linkSlice
}
if numberOfPages == 1 {
return getSinglePage(linkSlice, pageNumber, badDeedRequest)
}
for pages := 0; pages < numberOfPages; pages++ {
if pageNumber+pages == 1 {
log.Println("first result already in memory")
linkSlice, _ = concatenateResults(linkSlice, pageContent)
continue
}
linkSlice = getSinglePage(linkSlice, pageNumber+pages, badDeedRequest)
time.Sleep(500 * time.Millisecond)
}
return linkSlice
}
func validateHex(magic string) error {
/*hex errors to return*/
const NOTHEX string = "contains invalid hexadecimal characters"
const UNEVEN string = "contains uneven character filecount"
const LENGTH string = "ffb must be four bytes"
var regexString = "^[A-Fa-f\\d]+$"
res, _ := regexp.MatchString(regexString, magic)
if !res {
return fmt.Errorf(NOTHEX)
}
if len(magic)%2 != 0 {
return fmt.Errorf(UNEVEN)
}
if len(magic) < 8 || len(magic) > 8 {
return fmt.Errorf(LENGTH)
}
return nil
}
func returnRandomFile(pageCount int, badDeedRequest shineRequest, pageContent string) {
// Shine doesn't use a zero-based index.
randomPageNumber := getRandom(pageCount) + 1
linkSlice := listResults(badDeedRequest, pageContent, randomPageNumber, singlePage)
if len(linkSlice) == 0 {
log.Fatalf("returned zero attempting to get random result. Exiting.")
}
randomFileNumber := getRandom(len(linkSlice))
// Out slice uses a zero-based index so we don't need to increment.
log.Printf("returning file: %d from page: %d", randomFileNumber+1, randomPageNumber)
fmt.Println(linkSlice[randomFileNumber])
}
func checkExistence(needle int, slice []int) bool {
for _, value := range slice {
if value == needle {
return true
}
}
return false
}
// Return a bar distribution for the pages files are selected from.
func getDistribution(dist []int) {
sort.Ints(dist)
var distString string
columns := 100
for i := 0; i < columns; i++ {
for _, v := range dist {
x := float64(v)
y := float64(solrMaxPages)
percentage := float64((x / y) * 100)
calculated := int(math.Ceil(percentage))
if calculated == i {
distString = fmt.Sprintf("%s|", distString)
continue
}
}
distString = fmt.Sprintf("%s‖", distString)
}
log.Printf("distribution (pages): %s", distString)
}
func returnSampledList(badDeedRequest shineRequest, pageCount int, fileCount int) {
var randomFiles []int
var returnSlice []string
for i := 0; i < maxSample; i++ {
possibleFile := getRandom(fileCount)
// If performance is terrible we can rely on the map to de-dupe and return
// less than 20.
if checkExistence(possibleFile, randomFiles) {
// Decrement counter and find another value.
i--
continue
}
randomFiles = append(randomFiles, possibleFile)
}
// Map file number to a page number, map([file]pageNumber)
indexPageMap := make(map[int]int)
var pageDist []int
var keys []int
for _, value := range randomFiles {
page := int(value/10) + 1
indexPageMap[value] = page
pageDist = append(pageDist, page)
keys = append(keys, value)
}
getDistribution(pageDist)
sort.Ints(keys)
pageCounter := 0
var newLinkSlice []string
for _, value := range keys {
_page := indexPageMap[value]
if _page != pageCounter {
pageCounter = _page
log.Println("get page", pageCounter)
newLinkSlice = nil
newLinkSlice = getSinglePage(newLinkSlice, pageCounter, badDeedRequest)
} else {
log.Println("page already in memory:", pageCounter)
}
index := value % 10
returnSlice = append(returnSlice, newLinkSlice[index])
}
for _, value := range returnSlice {
// Print our random sample out to the console.
fmt.Println(value)
}
}
// getFile is the primary runner of this app,
func getFile() {
// Override the ffb and enter GIF mode...
if gif {
log.Println("searching in GIF mode")
ffb = ffbGIF
}
// Convert the ffb to lowercase for Shine then validate
ffb = strings.ToLower(ffb)
err := validateHex(ffb)
if err != nil {
log.Fatal("invalid hexadecimal string: ", err)
}
// Ping the first page of the shine service to configure the search.
var badDeedRequest shineRequest
var pageContent string
var fileCount, pageCount int
log.Println("searching Shine@UKWA")
badDeedRequest = newShineSearch(1, ffb, "crawl_date", "asc")
pageContent, fileCount, pageCount = ping(newSearchString(badDeedRequest))
log.Printf("files discovered: '%d'", fileCount)
log.Printf("pages available: '%d'", pageCount)
// if this, our work is done...
if stat || fileCount == 0 {
// No files to return.
return
}
if fileCount > 0 && pageCount == 0 {
// Non-zero based indexing.
pageCount = singlePage
}
// Shine's SOLR has a issue deep paging beyond 10,000 results. This eats
// RAM and CPU. To be kind to Shine we will keep the limits lower than that.
if pageCount >= solrMaxPages {
log.Printf("setting pageCount ('%d') max to: %d (solrMaxPages)", pageCount, solrMaxPages)
pageCount = solrMaxPages
fileCount = solrMaxPages * resultsPerPage
}
if random && !list && !sample {
if page > 0 {
log.Printf("argument `-page %d` has no effect when random (default) is selected", page)
}
// Return a random file and then exit.
returnRandomFile(pageCount, badDeedRequest, pageContent)
return
}
if sample && fileCount > maxSample {
log.Println("returning a sampled list...")
returnSampledList(badDeedRequest, pageCount, fileCount)
return
}
// Else, list five pages of files from a given offset.
listSize := minInt((pageCount-page), multiPage) + 1
if page > pageCount {
log.Printf("page number: '%d' too high, setting to max: '%d' (list size: %d)", page, pageCount, listSize)
page = pageCount
listSize = 1
}
if page == 0 {
log.Println("page can't be zero, setting to 1")
page = 1
}
linkSlice := listResults(badDeedRequest, pageContent, page, listSize)
log.Printf("returning %d results\n", len(linkSlice))
for _, value := range linkSlice {
fmt.Println(value)
}
}
func main() {
flag.Parse()
if vers {
fmt.Fprintf(os.Stderr, "%s (%s) commit: %s date: %s\n", agent, version, commit, date)
os.Exit(0)
} else if flag.NFlag() < 0 { // can access args w/ len(os.Args[1:]) too
fmt.Fprintln(os.Stderr, "Usage: baddeed")
fmt.Fprintln(os.Stderr, " OPTIONAL: [-ffb] ... OPTIONAL: [-list] ...")
fmt.Fprintln(os.Stderr, " OPTIONAL: [-ffb] ... OPTIONAL: [-sample] ...")
fmt.Fprintln(os.Stderr, " OPTIONAL: [-gif] ...")
fmt.Fprintln(os.Stderr, " OPTIONAL: [-stat]")
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "Output: [STRING] {url}")
fmt.Fprintln(os.Stderr, "Output: [LIST] {url}")
fmt.Fprintln(os.Stderr, " {url}")
fmt.Fprintln(os.Stderr, " ... ")
fmt.Fprintln(os.Stderr, " ... ")
fmt.Fprintf(os.Stderr, "Output: [STRING] '%s ...'\n\n", agent)
flag.Usage()
os.Exit(0)
} else {
getFile()
}
}