-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathembed.go
401 lines (351 loc) · 10.2 KB
/
embed.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
package main
import (
"fmt"
"path"
"sort"
"strings"
"github.com/mtgban/go-mtgban/mtgban"
)
const (
// Overflow prevention for field.Value size
MaxCustomEntries = 7
// Discord API constants
MaxEmbedFieldsValueLength = 1024
MaxEmbedFieldsNumber = 25
// Timeout before cancelling a last sold price request
LastSoldTimeout = 30
)
type OEmbed struct {
Version string `json:"version"`
ProviderName string `json:"provider_name"`
ProviderURL string `json:"provider_url"`
Title string `json:"title"`
Type string `json:"type"`
HTML string `json:"html"`
ThumbnailURL string `json:"thumbnail_url"`
ThumbnailWidth int `json:"thumbnail_width"`
ThumbnailHeight int `json:"thumbnail_height"`
}
type EmbedSearchResult struct {
Invalid bool
CardId string
ResultsIndex []SearchEntry
ResultsSellers []SearchEntry
ResultsVendors []SearchEntry
EditionSearched string
NamesOverride []string
}
type EmbedField struct {
Name string
Values []EmbedFieldValue
Raw string
Length int
Inline bool
}
type EmbedFieldValue struct {
ScraperName string
Tag string
ExtraSpaces string
Link string
Price string
HasAlarm bool
HasFire bool
}
func embedfieldlength(value EmbedFieldValue) int {
// Buffer for formatting
extra := 12
if value.HasAlarm {
extra += 2
}
if value.HasFire {
extra += 2
}
return len(value.ScraperName) + len(value.Tag) + len(value.ExtraSpaces) + len(value.Link) + len(value.Price) + extra
}
var EmbedFieldsNames = []string{
"Index", "Retail", "Buylist",
}
func FormatEmbedSearchResult(searchRes *EmbedSearchResult) (fields []EmbedField) {
// Add two embed fields, one for retail and one for buylist
for i, results := range [][]SearchEntry{
searchRes.ResultsIndex, searchRes.ResultsSellers, searchRes.ResultsVendors,
} {
// Skip amepty results
if results == nil {
continue
}
// Assign name or override
fieldName := EmbedFieldsNames[i]
if len(searchRes.NamesOverride) > i {
fieldName = searchRes.NamesOverride[i]
}
field := EmbedField{
Name: fieldName,
}
if EmbedFieldsNames[i] != "Index" {
field.Inline = true
}
// Results look really bad after MaxCustomEntries, and too much info
// does not help, so sort by best price, trim, then sort back to original
if len(results) > MaxCustomEntries {
if fieldName == "Retail" {
sort.Slice(results, func(i, j int) bool {
return results[i].Price < results[j].Price
})
} else if fieldName == "Buylist" {
sort.Slice(results, func(i, j int) bool {
return results[i].Price > results[j].Price
})
}
// Do not crop the first section, indexes are good price indicators
if i != 0 {
results = results[:MaxCustomEntries]
}
}
sort.Slice(results, func(i, j int) bool {
return results[i].ScraperName < results[j].ScraperName
})
// Alsign to the longest name by appending whitespaces
alignLength := longestName(results)
for _, entry := range results {
var value EmbedFieldValue
for i := len(entry.ScraperName); i < alignLength; i++ {
value.ExtraSpaces += " "
}
value.ScraperName = entry.ScraperName
value.Price = fmt.Sprintf("$%0.2f", entry.Price)
// Build url for our redirect
kind := strings.ToLower(string(EmbedFieldsNames[i][0]))
store := strings.Replace(entry.Shorthand, " ", "%20", -1)
value.Link = "https://" + DefaultHost + "/" + path.Join("go", kind, store, searchRes.CardId)
if entry.Ratio > 60 {
value.HasFire = true
}
if EmbedFieldsNames[i] == "Index" {
var shouldSkip bool
var j int
var newScraperName string
var newTag string
isSealed := strings.Contains(value.ScraperName, "EV") || strings.Contains(value.ScraperName, "Sim")
// Determine which index we're merging (either 'TCG' or 'MKM')
// since the scraper names are ('TCG Low' and 'TCG Market')
fields := strings.Fields(value.ScraperName)
if len(fields) < 2 || (fields[1] == "Direct" && !isSealed) {
continue
}
found := false
for j = range field.Values {
// Look if an existing tag is present
if (!isSealed && !strings.HasPrefix(field.Values[j].ScraperName, fields[0])) ||
(isSealed && !strings.HasPrefix(field.Values[j].ScraperName, strings.Join(fields[0:2], " "))) {
continue
}
newScraperName = fields[0]
newTag = fmt.Sprintf("Low/%s", fields[1])
// Sealed case, since results are in order, if one is found, append a new tag
if isSealed {
// Skip in case Mediam is equal to EV
if field.Values[j].Price == value.Price {
shouldSkip = true
field.Values[j].ExtraSpaces = ""
break
}
newScraperName = field.Values[j].ScraperName
newTag = "EV/Sim"
if field.Values[j].Tag == newTag {
newTag = "EV/Sim/Std"
}
}
found = true
break
}
if shouldSkip {
continue
}
// If found, then edit the exiting one instead of appending a new value
if found {
field.Length -= embedfieldlength(field.Values[j])
// Rebuild the Value and move to the next item
field.Values[j] = EmbedFieldValue{
// Update the name
ScraperName: newScraperName,
// Update the tags
Tag: newTag,
// Handle alignment manually
ExtraSpaces: "",
// Append the second price
Price: fmt.Sprintf("%s / %s", field.Values[j].Price, value.Price),
// Either is fine
Link: value.Link,
}
field.Length += embedfieldlength(field.Values[j])
continue
}
} else if EmbedFieldsNames[i] == "Buylist" {
for _, subres := range searchRes.ResultsSellers {
// 90% of sell price is the minimum for arbit
if subres.Price < entry.Price*0.9 {
value.HasAlarm = true
break
}
}
}
length := embedfieldlength(value)
// If we go past the maximum value for embed field values,
// make a new field for any spillover, as long as we are within
// the limits of the number of embeds allowed
if field.Length+length > MaxEmbedFieldsValueLength && len(fields) < MaxEmbedFieldsNumber {
fields = append(fields, field)
field = EmbedField{
Name: EmbedFieldsNames[i] + " (cont'd)",
Inline: true,
}
}
field.Values = append(field.Values, value)
field.Length += length
}
// Rename scrapers, yes the space is intentional
for i := range field.Values {
if field.Values[i].ScraperName == "TCG Direct (net) EV" {
field.Values[i].ScraperName = "Direct EV "
}
}
if len(results) == 0 {
field.Raw = "N/A"
// The very first item is allowed not to have entries
if EmbedFieldsNames[i] == "Index" {
continue
}
}
fields = append(fields, field)
}
return
}
// Obtain the length of the scraper with the longest name
func longestName(results []SearchEntry) (out int) {
for _, entry := range results {
probe := len(entry.ScraperName)
if probe > out {
out = probe
}
}
return
}
func grabLastSold(cardId string, lang string) ([]EmbedField, error) {
var fields []EmbedField
lastSales, err := getLastSold(cardId)
if err != nil {
return nil, err
}
var hasValues bool
for _, entry := range lastSales {
// Skip any language non matching the requested language
if entry.Language != lang {
continue
}
value := "-"
if entry.PurchasePrice != 0 {
hasValues = true
value = fmt.Sprintf("$%0.2f", entry.PurchasePrice)
if entry.ShippingPrice != 0 {
value += fmt.Sprintf(" (+$%0.2f)", entry.ShippingPrice)
}
}
fields = append(fields, EmbedField{
Name: entry.OrderDate.Format("2006-01-02"),
Raw: value,
Inline: true,
})
if len(fields) > 5 {
break
}
}
// No prices received, this is not an error,
// but print a message warning the user
if !hasValues {
return nil, nil
}
return fields, nil
}
// Retrieve cards from Sellers using the very first result
func ProcessEmbedSearchResultsSellers(foundSellers map[string]map[string][]SearchEntry, index bool) []SearchEntry {
if len(foundSellers) == 0 {
return nil
}
var results []SearchEntry
sortedKeysSeller := make([]string, 0, len(foundSellers))
for cardId := range foundSellers {
sortedKeysSeller = append(sortedKeysSeller, cardId)
}
if len(sortedKeysSeller) > 1 {
sort.Slice(sortedKeysSeller, func(i, j int) bool {
return sortSets(sortedKeysSeller[i], sortedKeysSeller[j])
})
}
cardId := sortedKeysSeller[0]
if index {
results = foundSellers[cardId]["INDEX"]
// Add the TCG_DIRECT to the Index section too, considering conditions
for _, cond := range []string{"NM", "SP"} {
done := false
foundResults := foundSellers[cardId][cond]
for _, result := range foundResults {
if result.ScraperName == TCG_DIRECT {
results = append(results, result)
done = true
break
}
}
if done {
break
}
}
} else {
founders := map[string]string{}
// Query results with the known (ordered) conditions
for _, cond := range mtgban.DefaultGradeTags {
foundResults := foundSellers[cardId][cond]
// Loop through the results, keep track of the precessed
// elements in the map (and skip lower condition ones)
for _, result := range foundResults {
_, found := founders[result.ScraperName]
if found {
continue
}
founders[result.ScraperName] = cond
// If not NM, add a small tag
if cond != "NM" {
result.ScraperName += " (" + cond + ")"
}
results = append(results, result)
}
}
}
if len(results) > 0 {
// Drop duplicates by looking at the last one as they are alredy sorted
tmp := append(results[:0], results[0])
for i := range results {
if results[i].ScraperName != tmp[len(tmp)-1].ScraperName {
tmp = append(tmp, results[i])
}
}
results = tmp
}
return results
}
// Retrieve cards from Vendors using the very first result
func ProcessEmbedSearchResultsVendors(foundVendors map[string]map[string][]SearchEntry) []SearchEntry {
if len(foundVendors) == 0 {
return nil
}
sortedKeysVendor := make([]string, 0, len(foundVendors))
for cardId := range foundVendors {
sortedKeysVendor = append(sortedKeysVendor, cardId)
}
if len(sortedKeysVendor) > 1 {
sort.Slice(sortedKeysVendor, func(i, j int) bool {
return sortSets(sortedKeysVendor[i], sortedKeysVendor[j])
})
}
return foundVendors[sortedKeysVendor[0]]["NM"]
}