-
Notifications
You must be signed in to change notification settings - Fork 1
/
admin.go
671 lines (568 loc) · 14 KB
/
admin.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"time"
cleanhttp "github.com/hashicorp/go-cleanhttp"
"github.com/mtgban/go-mtgban/mtgban"
"github.com/mtgban/go-mtgban/mtgmatcher"
"github.com/mackerelio/go-osstat/memory"
)
const (
mtgjsonURL = "https://mtgjson.com/api/v5/AllPrintings.json"
)
var BuildCommit = func() string {
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" {
return setting.Value
}
}
}
return ""
}()
func Admin(w http.ResponseWriter, r *http.Request) {
sig := getSignatureFromCookies(r)
page := r.FormValue("page")
pageVars := genPageNav("Admin", sig)
pageVars.Nav = insertNavBar("Admin", pageVars.Nav, []NavElem{
NavElem{
Name: "People",
Short: "👥",
Link: "/admin?page=people",
Active: page == "people",
Class: "selected",
},
})
msg := r.FormValue("msg")
if msg != "" {
pageVars.InfoMessage = msg
}
html := r.FormValue("html")
if html == "textfield" {
pageVars.SelectableField = true
}
refresh := r.FormValue("refresh")
if refresh != "" {
key, found := ScraperMap[refresh]
if !found {
pageVars.InfoMessage = refresh + " not found"
}
if key != "" {
_, found := ScraperOptions[key]
if !found {
pageVars.InfoMessage = key + " not found"
} else {
// Strip the request parameter to avoid accidental repeats
// and to give a chance to table to update
r.URL.RawQuery = ""
if ScraperOptions[key].Busy {
v := url.Values{
"msg": {key + " is already being refreshed"},
}
r.URL.RawQuery = v.Encode()
} else {
go reload(key)
}
http.Redirect(w, r, r.URL.String(), http.StatusFound)
return
}
}
}
logs := r.FormValue("logs")
if logs != "" {
key, found := ScraperMap[logs]
if !found {
pageVars.InfoMessage = key + " not found"
}
log.Println(path.Join(LogDir, key+".log"))
http.ServeFile(w, r, path.Join(LogDir, key+".log"))
return
}
spoof := r.FormValue("spoof")
if spoof != "" {
baseURL := getBaseURL(r)
sig := sign(baseURL, spoof, nil)
// Overwrite the current signature
putSignatureInCookies(w, r, sig)
http.Redirect(w, r, baseURL, http.StatusFound)
return
}
reboot := r.FormValue("reboot")
doReboot := false
var v url.Values
switch reboot {
case "mtgjson":
v = url.Values{}
v.Set("msg", "Reloading MTGJSON in the background...")
doReboot = true
go func() {
log.Println("Retrieving the latest version of mtgjson")
resp, err := cleanhttp.DefaultClient().Get(mtgjsonURL)
if err != nil {
log.Println(err)
return
}
defer resp.Body.Close()
log.Println("Loading the new mtgjson version")
err = mtgmatcher.LoadDatastore(resp.Body)
if err != nil {
log.Println(err)
return
}
log.Println("New mtgjson is ready")
}()
case "update":
v = url.Values{}
v.Set("msg", "Deploying...")
doReboot = true
go func() {
out, err := pullCode()
if err != nil {
log.Println("git -", err)
return
}
log.Println(out)
out, err = build()
if err != nil {
log.Println("go -", err)
return
}
log.Println(out)
log.Println("Restarting")
os.Exit(0)
}()
case "build", "code":
v = url.Values{}
doReboot = true
var out string
var err error
if reboot == "build" {
out, err = build()
} else if reboot == "code" {
out, err = pullCode()
}
if err != nil {
log.Println(err)
v.Set("msg", err.Error())
} else {
log.Println(out)
v.Set("msg", out)
}
case "cache":
v = url.Values{}
v.Set("msg", "Deleting old cache...")
doReboot = true
go deleteOldCache()
case "config":
v = url.Values{}
v.Set("msg", "New config loaded!")
doReboot = true
err := loadVars(DefaultConfigPath)
if err != nil {
v.Set("msg", "Failed to reload config: "+err.Error())
}
case "scrapers", "sellers", "vendors":
v = url.Values{}
v.Set("msg", fmt.Sprintf("Reloading %s in the background...", reboot))
doReboot = true
skip := false
for key, opt := range ScraperOptions {
if opt.Busy {
v.Set("msg", "Cannot reload everything while "+key+" is refreshing")
skip = true
break
}
}
if !skip && reboot == "scrapers" {
go loadScrapers()
}
if !skip {
go func() {
newbc := mtgban.NewClient()
for key, opt := range ScraperOptions {
if DevMode && !opt.DevEnabled {
continue
}
scraper, err := opt.Init(opt.Logger)
if err != nil {
msg := fmt.Sprintf("error initializing %s: %s", key, err.Error())
ServerNotify("init", msg, true)
return
}
if len(opt.Keepers) > 0 || len(opt.KeepersBL) > 0 {
if !opt.OnlyVendor {
if len(opt.Keepers) == 0 {
newbc.RegisterSeller(scraper)
}
for _, keeper := range opt.Keepers {
newbc.RegisterMarket(scraper.(mtgban.Market), keeper)
}
}
if !opt.OnlySeller {
if len(opt.KeepersBL) == 0 {
newbc.RegisterVendor(scraper)
}
for _, keeper := range opt.KeepersBL {
newbc.RegisterTrader(scraper.(mtgban.Trader), keeper)
ScraperMap[keeper] = key
ScraperNames[keeper] = keeper
}
}
} else if opt.OnlySeller {
newbc.RegisterSeller(scraper)
} else if opt.OnlyVendor {
newbc.RegisterVendor(scraper)
} else {
newbc.Register(scraper)
}
}
if reboot == "sellers" {
loadSellers(newbc)
} else if reboot == "vendors" {
loadVendors(newbc)
}
}()
}
case "server":
v = url.Values{}
v.Set("msg", "Restarting the server...")
doReboot = true
// Let the system restart the server
go func() {
time.Sleep(5 * time.Second)
log.Println("Admin requested server restart")
os.Exit(0)
}()
case "newKey":
v = url.Values{}
doReboot = true
user := r.FormValue("user")
dur := r.FormValue("duration")
duration, _ := strconv.Atoi(dur)
key, err := generateAPIKey(getBaseURL(r), user, time.Duration(duration)*24*time.Hour)
msg := key
if err != nil {
msg = "error: " + err.Error()
}
v.Set("msg", msg)
v.Set("html", "textfield")
}
if doReboot {
r.URL.RawQuery = v.Encode()
http.Redirect(w, r, r.URL.String(), http.StatusFound)
return
}
switch page {
case "people":
pageVars.DisableLinks = true
pageVars.Headers = []string{
"", "#", "Category", "Email", "Name", "Tier",
}
for i, person := range Config.Patreon.Grants {
row := []string{
fmt.Sprintf("%d", i+1),
person.Category,
person.Email,
person.Name,
person.Tier,
}
pageVars.Table = append(pageVars.Table, row)
}
pageVars.OtherHeaders = []string{
"", "#", "API User",
}
// Sort before show
var emails []string
for person := range Config.ApiUserSecrets {
emails = append(emails, person)
}
sort.Strings(emails)
for i, email := range emails {
row := []string{
fmt.Sprintf("%d", i+1),
email,
}
pageVars.OtherTable = append(pageVars.OtherTable, row)
}
default:
pageVars.Headers = []string{
"", "Name", "Id+Logs", "Tag", "Last Update", "Entries", "Status",
}
pageVars.OtherHeaders = pageVars.Headers
for i := range Sellers {
if Sellers[i] == nil {
row := []string{
fmt.Sprintf("Error at Seller %d", i), "", "", "", "", "",
}
pageVars.Table = append(pageVars.Table, row)
continue
}
scraperOptions, found := ScraperOptions[ScraperMap[Sellers[i].Info().Shorthand]]
if !found {
continue
}
lastUpdate := Sellers[i].Info().InventoryTimestamp.Format(time.Stamp)
inv, _ := Sellers[i].Inventory()
status := "✅"
if scraperOptions.Busy {
status = "🔶"
} else if len(inv) == 0 {
status = "🔴"
}
name := Sellers[i].Info().Name
if Sellers[i].Info().SealedMode {
name += " 📦"
}
if Sellers[i].Info().MetadataOnly {
name += " 🎯"
}
row := []string{
name,
Sellers[i].Info().Shorthand,
ScraperMap[Sellers[i].Info().Shorthand],
lastUpdate,
fmt.Sprint(len(inv)),
status,
}
pageVars.Table = append(pageVars.Table, row)
}
for i := range Vendors {
if Vendors[i] == nil {
row := []string{
fmt.Sprintf("Error at Vendor %d", i), "", "", "", "", "",
}
pageVars.OtherTable = append(pageVars.Table, row)
continue
}
scraperOptions, found := ScraperOptions[ScraperMap[Vendors[i].Info().Shorthand]]
if !found {
continue
}
lastUpdate := Vendors[i].Info().BuylistTimestamp.Format(time.Stamp)
bl, _ := Vendors[i].Buylist()
status := "✅"
if scraperOptions.Busy {
status = "🔶"
} else if len(bl) == 0 {
status = "🔴"
}
name := Vendors[i].Info().Name
if Vendors[i].Info().SealedMode {
name += " 📦"
}
if Vendors[i].Info().MetadataOnly {
name += " 🎯"
}
row := []string{
name,
Vendors[i].Info().Shorthand,
ScraperMap[Vendors[i].Info().Shorthand],
lastUpdate,
fmt.Sprint(len(bl)),
status,
}
pageVars.OtherTable = append(pageVars.OtherTable, row)
}
}
var tiers []string
for tierName := range Config.ACL {
tiers = append(tiers, tierName)
}
sort.Slice(tiers, func(i, j int) bool {
return tiers[i] < tiers[j]
})
pageVars.Tiers = tiers
pageVars.Uptime = uptime()
pageVars.DiskStatus = disk()
pageVars.MemoryStatus = mem()
pageVars.LatestHash = BuildCommit
pageVars.CurrentTime = time.Now()
pageVars.DemoKey = url.QueryEscape(getDemoKey(getBaseURL(r)))
render(w, "admin.html", pageVars)
}
func pullCode() (string, error) {
gitExecPath, err := exec.LookPath("git")
if err != nil {
return "", err
}
log.Println("Found git at", gitExecPath)
var out bytes.Buffer
for _, cmds := range [][]string{
[]string{"fetch"}, []string{"rest", "--hard", "origin/master"},
} {
cmd := exec.Command(gitExecPath, cmds...)
cmd.Stdout = &out
log.Println("Running git", strings.Join(cmds, " "))
err = cmd.Run()
if err != nil {
return "", err
}
}
return out.String(), nil
}
func build() (string, error) {
goExecPath, err := exec.LookPath("go")
if err != nil {
return "", err
}
log.Println("Found go at", goExecPath)
var out bytes.Buffer
cmd := exec.Command(goExecPath, "build")
cmd.Stderr = &out
err = cmd.Run()
if err != nil {
return "", err
}
if out.Len() == 0 {
return "Build successful", nil
}
return "", errors.New(out.String())
}
const fifteenDays = 15 * 24 * time.Hour
// Delete cache of inventory and buylist files older than 15 days
func deleteOldCache() {
var size int64
log.Println("Wiping cache")
for _, directory := range []string{"cache_inv/", "cache_bl/"} {
directory += Config.Game
// Open the directory and read all its files.
dirRead, err := os.Open(directory)
if err != nil {
continue
}
defer dirRead.Close()
dirFiles, err := dirRead.Readdir(0)
if err != nil {
continue
}
for _, subdir := range dirFiles {
if time.Since(subdir.ModTime()) < fifteenDays {
continue
}
// Read and list subdirectories
subPath := path.Join(directory, subdir.Name())
subDirRead, err := os.Open(subPath)
if err != nil {
continue
}
defer subDirRead.Close()
subDirFiles, err := subDirRead.Readdir(0)
if err != nil {
continue
}
// Loop over the directory's files and remove them
for _, files := range subDirFiles {
fullPath := path.Join(directory, subdir.Name(), files.Name())
// Skip deleting if there is a reference
storeTagExt := filepath.Base(fullPath)
storeBaseName := strings.Replace(storeTagExt, ".json", "-latest.json", 1)
link, err := os.Readlink(path.Join(directory, storeBaseName))
if err != nil {
continue
}
if link == fullPath {
continue
}
log.Println("Deleting", fullPath)
os.Remove(fullPath)
size += files.Size()
}
// Remove containing directory (if empty)
log.Println("Deleting", subPath)
os.Remove(subPath)
}
}
log.Printf("Cache is wiped, %dkb freed", size/1024)
}
// Custom time.Duration format to print days as well
func uptime() string {
since := time.Since(startTime)
days := int(since.Hours() / 24)
hours := int(since.Hours()) % 24
minutes := int(since.Minutes()) % 60
seconds := int(since.Seconds()) % 60
return fmt.Sprintf("%d days, %02d:%02d:%02d", days, hours, minutes, seconds)
}
func mem() string {
memData, err := memory.Get()
if err != nil {
return "N/A"
}
return fmt.Sprintf("%.2f%% of %.2fGB", float64(memData.Used)/float64(memData.Total)*100, float64(memData.Total)/1024/1024/1024)
}
const (
DefaultAPIDemoKeyDuration = 30 * 24 * time.Hour
DefaultAPIDemoUser = "demo@mtgban.com"
)
func getDemoKey(link string) string {
key, _ := generateAPIKey(link, DefaultAPIDemoUser, DefaultAPIDemoKeyDuration)
return key
}
var apiUsersMutex sync.RWMutex
func generateAPIKey(link, user string, duration time.Duration) (string, error) {
if user == "" {
return "", errors.New("missing user")
}
apiUsersMutex.RLock()
key, found := Config.ApiUserSecrets[user]
apiUsersMutex.RUnlock()
if !found {
key = randomString(15)
apiUsersMutex.Lock()
Config.ApiUserSecrets[user] = key
apiUsersMutex.Unlock()
file, err := os.Create(Config.filePath)
if err != nil {
return "", err
}
defer file.Close()
e := json.NewEncoder(file)
// Avoids & -> \u0026 and similar
e.SetEscapeHTML(false)
e.SetIndent("", " ")
err = e.Encode(&Config)
if err != nil {
return "", err
}
}
v := url.Values{}
v.Set("API", "ALL_ACCESS")
v.Set("APImode", "all")
v.Set("UserEmail", user)
var exp string
if duration != 0 {
expires := time.Now().Add(duration)
exp = fmt.Sprintf("%d", expires.Unix())
v.Set("Expires", exp)
}
data := fmt.Sprintf("GET%s%s%s", exp, link, v.Encode())
sig := signHMACSHA1Base64([]byte(key), []byte(data))
v.Set("Signature", sig)
return base64.StdEncoding.EncodeToString([]byte(v.Encode())), nil
}
// 32-126 are the printable characters in ashii, 33 excludes space
func randomString(l int) string {
rand.Seed(time.Now().UnixNano())
bytes := make([]byte, l)
for i := 0; i < l; i++ {
bytes[i] = byte(33 + rand.Intn(126-33))
}
return string(bytes)
}