-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.go
666 lines (593 loc) · 16.1 KB
/
utils.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/hashicorp/go-cleanhttp"
"golang.org/x/exp/slices"
"github.com/mtgban/go-mtgban/mtgban"
"github.com/mtgban/go-mtgban/mtgmatcher"
"github.com/mtgban/go-mtgban/mtgmatcher/mtgjson"
)
var Country2flag = map[string]string{
"EU": "🇪🇺",
"JP": "🇯🇵",
}
type GenericCard struct {
UUID string
Name string
Edition string
SetCode string
Number string
Variant string
Keyrune string
ImageURL string
Foil bool
Etched bool
Reserved bool
Title string
SearchURL string
SypList bool
Stocks bool
StocksURL string
Printings string
Products string
TCGId string
Date string
Sealed bool
Booster bool
HasDeck bool
CKRestockURL string
SourceSealed []string
}
func fileExists(filename string) bool {
fi, err := os.Lstat(filename)
if errors.Is(err, os.ErrNotExist) {
return false
}
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
link, err := os.Readlink(filename)
if err != nil {
return false
}
fi, err = os.Stat(link)
if errors.Is(err, os.ErrNotExist) {
return false
}
return !fi.IsDir()
}
return !fi.IsDir()
}
func mkDirIfNotExisting(dirName string) error {
_, err := os.Stat(dirName)
if errors.Is(err, os.ErrNotExist) {
err = os.MkdirAll(dirName, 0700)
}
return err
}
func keyruneForCardSet(cardId string) string {
co, err := mtgmatcher.GetUUID(cardId)
if err != nil {
return ""
}
set, err := mtgmatcher.GetSet(co.Card.SetCode)
if err != nil {
// Try again if token is under a related set
if co.Card.Rarity == "token" {
set, err = mtgmatcher.GetSet(strings.TrimPrefix(co.Card.SetCode, "T"))
}
if err != nil {
return ""
}
}
keyrune := set.KeyruneCode
out := "ss-" + strings.ToLower(keyrune)
rarity := co.Card.Rarity
if rarity == "special" || co.Etched {
rarity = "timeshifted"
} else if rarity == "token" || rarity == "oversize" {
rarity = "common"
}
// Skip setting rarity for common, so that a color is not forcefully set
// on the symbol, and can become white on a dark theme
// Also skip setting rarity on any foil cards due to rendering issues
// https://github.com/andrewgioia/keyrune/issues/228
if rarity != "common" && !co.Foil {
out += " ss-" + rarity
}
if co.Foil {
out += " ss-foil ss-grad"
}
return out
}
func scryfallImageURL(cardId string, small bool) string {
co, err := mtgmatcher.GetUUID(cardId)
if err != nil {
return ""
}
if co.Sealed {
tcgId, found := co.Identifiers["tcgplayerProductId"]
if !found {
return ""
}
return "https://product-images.tcgplayer.com/" + tcgId + ".jpg"
}
version := "normal"
if small {
version = "small"
}
number := co.Card.Number
// Retrieve the original number if present
dupe, found := co.Identifiers["originalScryfallNumber"]
if found {
number = dupe
}
// Support BAN's custom sets
code := strings.ToLower(co.SetCode)
if strings.HasSuffix(code, "ita") {
code = strings.TrimSuffix(code, "ita")
number += "/it"
} else if strings.HasSuffix(code, "jpn") {
code = strings.TrimSuffix(code, "jpn")
number += "/ja"
}
code = strings.TrimSuffix(code, "alt")
return fmt.Sprintf("https://api.scryfall.com/cards/%s/%s?format=image&version=%s", code, number, version)
}
func scryfallImageCropURL(cardId string) string {
co, err := mtgmatcher.GetUUID(cardId)
if err != nil {
return ""
}
scryfallId, found := co.Identifiers["scryfallId"]
if !found || len(scryfallId) < 3 {
return ""
}
return fmt.Sprintf("https://cards.scryfall.io/art_crop/front/%s/%s/%s.jpg", scryfallId[0:1], scryfallId[1:2], scryfallId)
}
func editionTitle(cardId string) string {
co, err := mtgmatcher.GetUUID(cardId)
if err != nil {
return ""
}
edition := co.Edition
tag := ""
if co.OriginalReleaseDate != "" {
tag = co.OriginalReleaseDate
}
if co.Subsets != nil {
tag = strings.Join(co.Subsets, " ")
}
if tag != "" {
edition = fmt.Sprintf("%s (%s)", edition, tag)
}
finish := ""
if co.Etched {
finish = " Etched"
} else if co.Foil {
finish = " Foil"
}
extra := ""
if co.Sealed {
subtype := strings.Replace(co.Side, "_", " ", -1)
category := strings.Replace(co.Layout, "_", " ", -1)
extra = mtgmatcher.Title(subtype + " " + category)
} else {
extra = "#" + co.Card.Number
}
return fmt.Sprintf("%s -%s %s %s", edition, finish, mtgmatcher.Title(co.Card.Rarity), extra)
}
func insertNavBar(page string, nav []NavElem, extra []NavElem) []NavElem {
out := make([]NavElem, len(nav)+len(extra))
var j int
for i := range nav {
out[j] = nav[i]
if out[j].Name == page {
for e := range extra {
j++
out[j] = extra[e]
}
}
j++
}
return out
}
const (
// 9 per line for default size, otherwise 19-21 depending on size
MaxBeforeShrink = 18
// After this amount just stop adding symbols
MaxRuneSymbols = 57
)
// Look up a vendor and return its buylist
func findSellerInventory(shorthand string) (mtgban.InventoryRecord, error) {
for _, seller := range Sellers {
if seller == nil {
continue
}
if strings.ToLower(seller.Info().Shorthand) == strings.ToLower(shorthand) {
return seller.Inventory()
}
}
return nil, errors.New("seller not found")
}
// Look up a vendor and return its buylist
func findVendorBuylist(shorthand string) (mtgban.BuylistRecord, error) {
for _, vendor := range Vendors {
if vendor == nil {
continue
}
if strings.ToLower(vendor.Info().Shorthand) == strings.ToLower(shorthand) {
return vendor.Buylist()
}
}
return nil, errors.New("vendor not found")
}
func uuid2card(cardId string, flags ...bool) GenericCard {
co, err := mtgmatcher.GetUUID(cardId)
if err != nil {
return GenericCard{}
}
var stocksURL string
var sypList bool
syp, err := findVendorBuylist("SYP")
if err == nil {
_, sypList = syp[cardId]
}
inv, _ := findSellerInventory("STKS")
entries, stocks := inv[co.UUID]
if stocks {
stocksURL = entries[0].URL
}
variant := ""
if co.HasPromoType(mtgjson.PromoTypeBoosterfun) {
switch {
case co.HasFrameEffect(mtgjson.FrameEffectShowcase):
variant = "Showcase "
case co.HasFrameEffect(mtgjson.FrameEffectExtendedArt):
variant = "Extended Art "
case co.BorderColor == mtgjson.BorderColorBorderless:
variant = "Borderless "
case co.FrameVersion == "1997":
variant = "Retro Frame "
}
}
// Loop through the supported promo types, skipping Boosterfun already processed above
for _, promoType := range co.PromoTypes {
if slices.Contains(mtgmatcher.AllPromoTypes(), promoType) && promoType != mtgjson.PromoTypeBoosterfun {
variant += mtgmatcher.Title(promoType) + " "
}
}
isJPN := co.Language == mtgjson.LanguageJapanese
if isJPN {
variant = "JPN " + variant
}
variant = strings.TrimSpace(variant)
name := co.Name
if co.FlavorName != "" {
if variant != "" {
variant = " - " + variant
}
variant = fmt.Sprintf("\"%s\" %s", co.FlavorName, variant)
}
query := co.Name
if !co.Sealed {
query = fmt.Sprintf("%s s:%s cn:%s", co.Name, co.SetCode, co.Number)
if co.Etched {
query += " f:etched"
// Append Etched information to the tag
if variant != "" {
variant += " "
}
variant += "Etched"
} else if co.Foil {
query += " f:foil"
} else if !co.Etched && !co.Foil {
query += " f:nonfoil"
}
}
smallImg := false
if len(flags) > 0 {
smallImg = flags[0]
}
printings := ""
if len(flags) > 1 && flags[1] {
// Hack to generate HTML in the template
for i, setCode := range co.Printings {
set, err := mtgmatcher.GetSet(setCode)
if err != nil {
continue
}
keyruneCode := strings.ToLower(set.KeyruneCode)
printings += fmt.Sprintf(`<a class="pagination" title="%s" href="/search?q=%s"><i class="ss ss-%s ss-2x"></i> </a>`, set.Name, url.QueryEscape(co.Name+" s:"+setCode), keyruneCode)
if i == MaxRuneSymbols && len(co.Printings) > MaxRuneSymbols {
printings += "<br>and many more (too many to list)..."
break
}
}
// Shrink icons to fit more of them
if len(co.Printings) > MaxBeforeShrink {
printings = strings.Replace(printings, "ss-2x", "ss-1x", -1)
}
}
if co.Sealed {
// The first chunk is always present, even for foil-only sets
printings = "<h6>Set Value</h6><table class='setValue'>"
for i, title := range ProductTitles {
entries, found := Infos[ProductKeys[i]][co.SetCode]
if found {
printings += fmt.Sprintf("<tr class='setValue'><td class='setValue'><h5>%s</h5></td><td>$ %.02f</td></tr>", title, entries[0].Price)
}
}
printings += "</table>"
// The second chunk is optional, check for the first key
if len(Infos[ProductFoilKeys[0]][co.SetCode]) > 0 {
printings += "<br>"
printings += "<h6>Foil Set Value</h6><table class='setValue'>"
for i, title := range ProductTitles {
entries, found := Infos[ProductFoilKeys[i]][co.SetCode]
if found {
printings += fmt.Sprintf("<tr class='setValue'><td class='setValue'><h5>%s</h5></td><td>$ %.02f</td></tr>", title, entries[0].Price)
}
}
printings += "</table>"
}
}
var canBoosterGen bool
var hasDecklist bool
path := "search"
if co.Sealed {
path = "sealed"
canBoosterGen = mtgmatcher.SealedIsRandom(co.SetCode, co.UUID)
hasDecklist = mtgmatcher.SealedHasDecklist(co.SetCode, co.UUID)
}
var sourceSealed []string
if co.Sealed {
sourceSealed = co.SourceProducts["sealed"]
} else if co.Etched {
sourceSealed = co.SourceProducts["etched"]
} else if co.Foil {
sourceSealed = co.SourceProducts["foil"]
} else {
sourceSealed = co.SourceProducts["nonfoil"]
}
var products string
if len(sourceSealed) > 0 {
products += "<h4>"
for _, sealed := range sourceSealed {
// The sealed uuids while known might have changed and we need to
// make sure they don't crash the system here
sealedCo, err := mtgmatcher.GetUUID(sealed)
if err != nil {
continue
}
products += "<a href=/sealed?q=" + sealed + ">" + sealedCo.Name + "</a><br>"
}
products += "</h4>"
if len(sourceSealed) > 5 {
products = strings.Replace(products, "h4>", "h6>", -1)
} else if len(sourceSealed) > 3 {
products = strings.Replace(products, "h4>", "h5>", -1)
}
}
tcgId := co.Card.Identifiers["tcgplayerProductId"]
if co.Etched {
tcgId = co.Card.Identifiers["tcgplayerEtchedProductId"]
}
// Retrieve the CK URL from the in memory api list, which uses mtgjson ids
var restockURL string
CKAPIMutex.RLock()
restock, found := CKAPIOutput[co.Identifiers["mtgjsonId"]]
CKAPIMutex.RUnlock()
if found {
if co.Etched && restock.Etched != nil {
restockURL = restock.Etched.URL
} else if co.Foil && restock.Foil != nil {
restockURL = restock.Foil.URL
} else if !co.Etched && !co.Foil && restock.Normal != nil {
restockURL = restock.Normal.URL
}
if restockURL != "" {
restockURL = strings.Replace(restockURL, "mtg", "catalog/restock_notice", 1)
restockURL += "?partner=" + Config.Affiliate["CK"]
}
}
return GenericCard{
UUID: co.UUID,
Name: name,
Edition: co.Edition,
SetCode: co.Card.SetCode,
Number: co.Card.Number,
Variant: variant,
Foil: co.Foil,
Etched: co.Etched,
Keyrune: keyruneForCardSet(cardId),
ImageURL: scryfallImageURL(cardId, smallImg),
Title: editionTitle(cardId),
Reserved: co.Card.IsReserved,
SearchURL: fmt.Sprintf("/%s?q=%s", path, url.QueryEscape(query)),
SypList: sypList,
Stocks: stocks,
StocksURL: stocksURL,
Printings: printings,
Products: products,
TCGId: tcgId,
Date: co.OriginalReleaseDate,
Sealed: co.Sealed,
Booster: canBoosterGen,
HasDeck: hasDecklist,
CKRestockURL: restockURL,
SourceSealed: sourceSealed,
}
}
type Notification struct {
Username string `json:"username"`
Content string `json:"content"`
}
// Log and send the notification for a user action
func ServerNotify(kind, message string, flags ...bool) {
log.Println(message)
if Config.DiscordNotifHook == "" {
return
}
if len(flags) > 0 && flags[0] {
message = "@here " + message
}
go notify(kind, message, Config.DiscordNotifHook)
}
// Only send the notification for a user action
func UserNotify(kind, message string, flags ...bool) {
if DevMode {
log.Println(message)
}
if Config.DiscordHook == "" {
return
}
if len(flags) > 0 && flags[0] {
message = "@here " + message
}
go notify(kind, message, Config.DiscordHook)
}
func notify(kind, message, hook string) {
var payload Notification
payload.Username = kind
if DevMode {
payload.Content = "[DEV] "
}
payload.Content += message
reqBody, err := json.Marshal(&payload)
if err != nil {
log.Println(err)
return
}
resp, err := cleanhttp.DefaultClient().Post(hook, "application/json", bytes.NewReader(reqBody))
if err != nil {
log.Println(err)
return
}
resp.Body.Close()
}
// Read the query parameter, if present set a cookie that will be
// used as default preference, otherwise retrieve the said cookie
func readSetFlag(w http.ResponseWriter, r *http.Request, queryParam, cookieName string) bool {
val := r.FormValue(queryParam)
flag, err := strconv.ParseBool(val)
if err != nil {
flag, _ = strconv.ParseBool(readCookie(r, cookieName))
return flag
}
setCookie(w, r, cookieName, val)
return flag
}
// Read a cookie from the request
func readCookie(r *http.Request, cookieName string) string {
for _, cookie := range r.Cookies() {
if cookie.Name == cookieName {
return cookie.Value
}
}
return ""
}
// Set a cookie in the response with no expiration at the default root
func setCookie(w http.ResponseWriter, r *http.Request, cookieName, value string) {
domain := "mtgban.com"
if strings.Contains(getBaseURL(r), "localhost") {
domain = "localhost"
}
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Domain: domain,
Path: "/",
// No expiration
Expires: time.Now().Add(10 * 365 * 24 * 60 * 60 * time.Second),
Value: value,
// Enforce first party cookies only
SameSite: http.SameSiteStrictMode,
})
}
// Retrieve default blocklists according to the signature contents
func getDefaultBlocklists(sig string) ([]string, []string) {
var blocklistRetail, blocklistBuylist []string
blocklistRetailOpt := GetParamFromSig(sig, "SearchDisabled")
if blocklistRetailOpt == "" {
blocklistRetail = Config.SearchRetailBlockList
} else if blocklistRetailOpt != "NONE" {
blocklistRetail = strings.Split(blocklistRetailOpt, ",")
}
blocklistBuylistOpt := GetParamFromSig(sig, "SearchBuylistDisabled")
if blocklistBuylistOpt == "" {
blocklistBuylist = Config.SearchBuylistBlockList
} else if blocklistBuylistOpt != "NONE" {
blocklistBuylist = strings.Split(blocklistBuylistOpt, ",")
}
return blocklistRetail, blocklistBuylist
}
// Return a random uuid from the pool of singles or sealed uuids
func randomUUID(sealed bool) string {
uuids := mtgmatcher.GetUUIDs()
if sealed {
uuids = mtgmatcher.GetSealedUUIDs()
}
index := rand.Intn(len(uuids))
return uuids[index]
}
type Pagination struct {
TotalIndex int
CurrentIndex int
PrevIndex int
NextIndex int
}
// Divide results in sub pages
// slice - input results
// pageIndex - the current page being viewed
// maxResults - how many items can be present in a single page
// maxTotalResults - how many items can be present in all results
func Paginate[T any](slice []T, pageIndex, maxResults, maxTotalResults int) ([]T, Pagination) {
var page Pagination
page.TotalIndex = len(slice)/maxResults + 1
if page.TotalIndex > maxTotalResults/maxResults {
page.TotalIndex = maxTotalResults / maxResults
}
// Parse the requested input page
if pageIndex <= 1 {
pageIndex = 1
} else if pageIndex > page.TotalIndex {
pageIndex = page.TotalIndex
}
// Assign the current page index to enable pagination
page.CurrentIndex = pageIndex
// Initialize previous and next pagination links
if page.CurrentIndex > 0 {
page.PrevIndex = page.CurrentIndex - 1
}
if page.CurrentIndex < page.TotalIndex {
page.NextIndex = page.CurrentIndex + 1
}
// Chop results where needed
head := maxResults * (pageIndex - 1)
tail := maxResults * pageIndex
if tail > len(slice) {
tail = len(slice)
}
return slice[head:tail], page
}
// Retrieve the TCG_MARKET price of any given card
func getTCGMarketPrice(cardId string) float64 {
inv, err := findSellerInventory(TCG_MARKET)
if err != nil {
return 0
}
entries, found := inv[cardId]
if !found {
return 0
}
return entries[0].Price
}