forked from omstrumpf/tts-mtg-importer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.lua
More file actions
1914 lines (1620 loc) · 60 KB
/
loader.lua
File metadata and controls
1914 lines (1620 loc) · 60 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
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include json_parser
------ CONSTANTS
SCRYFALL_ID_BASE_URL = "https://api.scryfall.com/cards/"
SCRYFALL_MULTIVERSE_BASE_URL = "https://api.scryfall.com/cards/multiverse/"
SCRYFALL_SET_NUM_BASE_URL = "https://api.scryfall.com/cards/"
SCRYFALL_SEARCH_BASE_URL = "https://api.scryfall.com/cards/search/?q="
SCRYFALL_NAME_BASE_URL = "https://api.scryfall.com/cards/named/?exact="
SCRYFALL_COLLECTION_URL = "https://api.scryfall.com/cards/collection"
PACK_ODDS_URL = "https://raw.githubusercontent.com/taw/magic-sealed-data/refs/heads/master/sealed_basic_data.json"
BOOSTER_INDEX_URL =
"https://raw.githubusercontent.com/Morgenmvffel/tts-mtg-booster-creator/refs/heads/master/booster_index.json"
BASE_BOOSTER_FILE_URL =
"https://raw.githubusercontent.com/Morgenmvffel/tts-mtg-booster-creator/refs/heads/master/booster"
BOOSTER_IMAGE_URL =
"https://steamusercontent-a.akamaihd.net/ugc/12048320118311789698/728EE5247F5FE466F92DAAC0E9997225CD3E8865/"
FOIL_EFFECT_URL =
"https://steamusercontent-a.akamaihd.net/ugc/18215652933654632959/A843EB4C96D1CE5E339D66F48A414D671B2CB4CC/"
MAINDECK_POSITION_OFFSET = { 1.89, 0.2, -0.04 }
TOKENS_POSITION_OFFSET = { 1.8, 0.2, 1 }
POSITION_SPACING = -0.756
DEFAULT_CARDBACK =
"https://gamepedia.cursecdn.com/mtgsalvation_gamepedia/f/f8/Magic_card_back.jpg?version=0ddc8d41c3b69c2c3c4bb5d72669ffd7"
DEFAULT_LANGUAGE = "en"
-- Pack Amounts
MAX_PACK_AMOUNT = 6
MIN_PACK_AMOUNT = 1
-- API Rate Limiting and Timeouts
RATE_LIMIT_DELAY = 0.1 -- seconds between API requests (10 req/sec)
MAX_RETRY_ATTEMPTS = 5
RETRY_BACKOFF_BASE = 2 -- seconds for first retry (doubles each time)
RETRY_BACKOFF_MAX = 10 -- maximum seconds to wait
QUERY_TIMEOUT = 30 -- seconds before individual query times out
FETCH_TIMEOUT = 60 -- seconds before batch fetch times out
LOAD_TIMEOUT = 120 -- seconds before full load times out
TOKEN_RETRY_DELAY = 2 -- seconds to wait before retrying token fetch
COLLECTION_BATCH_SIZE = 75 -- Scryfall collection API limit
LANGUAGES = {
["en"] = "en",
["es"] = "es",
["sp"] = "sp",
["fr"] = "fr",
["de"] = "de",
["it"] = "it",
["pt"] = "pt",
["ja"] = "ja",
["jp"] = "ja",
["ko"] = "ko",
["kr"] = "ko",
["ru"] = "ru",
["zcs"] = "zcs",
["cs"] = "zcs",
["zht"] = "zht",
["ph"] = "ph",
["english"] = "en",
["spanish"] = "es",
["french"] = "fr",
["german"] = "de",
["italian"] = "it",
["portugese"] = "pt",
["japanese"] = "ja",
["korean"] = "ko",
["russian"] = "ru",
["chinese"] = "zhs",
["simplified chinese"] = "zhs",
["traditional chinese"] = "zht",
["phyrexian"] = "ph"
}
------ UI IDs
UI_ADVANCED_PANEL = "MTGDeckLoaderAdvancedPanel"
UI_CARD_BACK_INPUT = "MTGDeckLoaderCardBackInput"
UI_LANGUAGE_INPUT = "MTGDeckLoaderLanguageInput"
UI_FORCE_LANGUAGE_TOGGLE = "MTGDeckLoaderForceLanguageToggleID"
------ GLOBAL STATE
lock = false
playerColor = nil
advanced = false
cardBackInput = ""
languageInput = ""
forceLanguage = false
enableFoil = true
blowCache = false
pngGraphics = true
spawnEverythingFaceDown = false
filteredBoosters = nil -- Will store filtered boosters for random selection, nil means all boosters
randomBoostersPerPack = true -- When true, each pack gets a random booster
useRandomBoosterSelection = false -- True when generation was started from the Random button
-- Booster search/filter state
boosterSearchFilter = "" -- current search text for dropdown filter
-- Booster filter options
filterDraft = true
filterCollector = true
filterPlay = true
filterSet = false
filterArena = false
filterPrerelease = false
filterJumpstart = true
filterTheme = false
filterOther = false
filterVintage = true
filterSLD = false
------ UTILITY
local function trim(s)
if not s then
return ""
end
local n = s:find "%S"
return n and s:match(".*%S", n) or ""
end
local function underline(s)
if not s or string.len(s) == 0 then
return ""
end
return s .. '\n' .. string.rep('-', string.len(s)) .. '\n'
end
local function shallowCopyTable(t)
if type(t) == 'table' then
local copy = {}
for key, val in pairs(t) do
copy[key] = val
end
return copy
end
return {}
end
local function printErr(s)
printToColor(s, playerColor, {
r = 1,
g = 0,
b = 0
})
end
local function printInfo(s)
printToColor(s, playerColor)
end
local function stringToBool(s)
-- It is truly ridiculous that this needs to exist.
return (string.lower(s) == "true")
end
------ CARD SPAWNING
local function jsonForCardFace(face, position, rotationY, flipped, foil)
local rotation = self.getRotation()
local rotZ = rotation.z
if flipped then
rotZ = math.fmod(rotZ + 180, 360)
end
local json = {
Name = "Card",
Transform = {
posX = position.x,
posY = position.y,
posZ = position.z,
rotX = rotation.x,
rotY = rotation.y + rotationY,
rotZ = rotZ,
scaleX = 1,
scaleY = 1,
scaleZ = 1
},
Nickname = face.name,
Description = face.oracleText,
Locked = false,
Grid = true,
Snap = true,
IgnoreFoW = false,
MeasureMovement = false,
DragSelectable = true,
Autoraise = true,
Sticky = true,
Tooltip = true,
GridProjection = false,
HideWhenFaceDown = true,
Hands = true,
CardID = 2440000,
SidewaysCard = false,
CustomDeck = {},
LuaScript = "",
LuaScriptState = ""
}
json.CustomDeck["24400"] = {
FaceURL = face.imageURI,
BackURL = getCardBack(),
NumWidth = 1,
NumHeight = 1,
BackIsHidden = true,
UniqueBack = false,
Type = 0
}
if enableFoil and foil then
json.LuaScript = [[
decal = {
name = "Foil",
url = "https://steamusercontent-a.akamaihd.net/ugc/18215652933654632959/A843EB4C96D1CE5E339D66F48A414D671B2CB4CC/",
position = Vector(0, 0.25, 0),
rotation = Vector(90, 0, 0),
scale = Vector(-2.14, -3.06, 1)
}
function onLoad(saved_data)
if self.getDecals() == nil then
self.addDecal(decal)
-- log("added Decal")
end
end
]]
end
return json
end
-- Spawns the given card [faces] at [position].
-- Card will be face down if [flipped].
-- Calls [onFullySpawned] when the object is spawned.
local function spawnCard(faces, position, rotation, flipped, onFullySpawned)
if not faces or not faces[1] then
faces = { {
name = card.name,
oracleText = "Card not found",
imageURI =
"https://vignette.wikia.nocookie.net/yugioh/images/9/94/Back-Anime-2.png/revision/latest?cb=20110624090942"
} }
end
-- Force flipped if the user asked for everything to be spawned face-down
if spawnEverythingFaceDown then
flipped = true
end
local jsonFace1 = jsonForCardFace(faces[1], position, rotation, flipped, false)
if #faces > 1 then
jsonFace1.States = {}
for i = 2, (#(faces)) do
local jsonFaceI = jsonForCardFace(faces[i], position, rotation, flipped, false)
jsonFace1.States[tostring(i)] = jsonFaceI
end
end
local cardObj = spawnObjectJSON({
json = JSON.encode(jsonFace1)
})
onFullySpawned(cardObj)
return cardObj
end
-- Spawns a deck named [name] containing the given [cards] at [position].
-- Deck will be face down if [flipped].
-- Calls [onFullySpawned] when the object is spawned.
local function spawnDeck(cards, name, position, rotation, flipped, onFullySpawned, onError)
local cardObjects = {}
local sem = 0
local function incSem()
sem = sem + 1
end
local function decSem()
sem = sem - 1
end
for _, card in ipairs(cards) do
for i = 1, (card.count or 1) do
if not card.faces or not card.faces[1] then
card.faces = { {
name = card.name,
oracleText = "Card not found",
imageURI =
"https://vignette.wikia.nocookie.net/yugioh/images/9/94/Back-Anime-2.png/revision/latest?cb=20110624090942"
} }
end
incSem()
spawnCard(card.faces, position, rotation, flipped, function(obj)
table.insert(cardObjects, obj)
decSem()
end)
end
end
Wait.condition(function()
local deckObject
if cardObjects[1] and cardObjects[2] then
deckObject = cardObjects[1].putObject(cardObjects[2])
if success and deckObject then
deckObject.setPosition(position)
deckObject.setName(name)
else
deckObject = cardObjects[1]
end
else
deckObject = cardObjects[1]
end
onFullySpawned(deckObject)
end, function()
return (sem == 0)
end, 5, function()
onError("Error collating packs... timed out.")
end)
end
local function sortCardsBySheetOrder(cards, sheetOrder)
-- Create a mapping of sheet names to their index in sheetOrder
local sheetIndex = {}
for i, sheet in ipairs(sheetOrder) do
sheetIndex[sheet] = i
end
-- Function to get the sheet index for sorting
local function getCardSheetIndex(card)
local sheet = (card.sheetName or ""):lower()
-- If the sheet is in the sheetOrder, return its index, otherwise return a high index to place it at the end
if sheetIndex[sheet] then
return sheetIndex[sheet]
else
-- Log a message if the sheetName is not in the sheetOrder
log("Warning: sheetName '" .. sheet .. "' not found in sheetOrder.")
return #sheetOrder + 1 -- Place this card at the end if the sheet is not found in sheetOrder
end
end
-- Sort cards based on their sheet order in reverse
table.sort(cards, function(a, b)
local indexA = getCardSheetIndex(a)
local indexB = getCardSheetIndex(b)
-- First, sort by reversed sheet order (descending index)
if indexA ~= indexB then
return indexA > indexB -- Reverse the order (descending index)
end
-- If they are from the same sheet, fallback to sorting alphabetically by sheetName (or use the collectorNum as a tie-breaker if needed)
return a.collectorNum < b.collectorNum
end)
end
local function spawnBagWithCards(cards, bagName, position, flipped, sheetOrder, onFullySpawned, onError)
log("spawnBagWithCards: Creating bag '" .. bagName .. "' with " .. #cards .. " cards")
-- Sort cards alphabetically by sheetName (fallback to name if missing)
-- log(sheetOrder)
sortCardsBySheetOrder(cards, sheetOrder)
local containedObjects = {}
local boosterName = ""
for _, card in ipairs(cards) do
for i = 1, (card.count or 1) do
local faces = card.faces or { {
name = card.name,
oracleText = "Card not found",
imageURI =
"https://vignette.wikia.nocookie.net/yugioh/images/9/94/Back-Anime-2.png/revision/latest?cb=20110624090942"
} }
-- Build the card JSON with States for multiple faces
local jsonFace1 = jsonForCardFace(faces[1], position, 0, flipped, card.foil)
if #faces > 1 then
jsonFace1.States = {}
for j = 2, #faces do
local jsonFaceJ = jsonForCardFace(faces[j], position, 0, flipped, card.foil)
jsonFace1.States[tostring(j)] = jsonFaceJ
end
end
table.insert(containedObjects, jsonFace1)
end
boosterName = card.packName
end
local bagJSON = {
Name = "Custom_Model_Bag",
Transform = {
posX = position[1],
posY = position[2],
posZ = position[3],
rotX = 0,
rotY = 180,
rotZ = 0,
scaleX = 1,
scaleY = 1,
scaleZ = 1
},
Nickname = boosterName .. bagName,
Description = "",
ColorDiffuse = {
r = 1,
g = 1,
b = 1
},
Locked = false,
Grid = true,
Snap = true,
Autoraise = true,
Sticky = true,
Tooltip = true,
MeshCollider = false,
MaterialIndex = -1,
MeshIndex = -1,
CustomMesh = {
MeshURL = "http://pastebin.com/raw/PqfGKtKR",
DiffuseURL = BOOSTER_IMAGE_URL,
NormalURL = "http://i.imgur.com/pEN77ux.png",
Convex = true,
MaterialIndex = 0,
TypeIndex = 6,
CastShadows = true,
specular_intensity = 0.3, -- Moderate shine
specular_color = {
r = 0.95,
g = 0.98,
b = 1.0
}, -- Neutral white highlight
specular_sharpness = 5, -- Clean but not razor-sharp
fresnel_strength = 0.2
},
ContainedObjects = containedObjects,
LuaScript = [[
function onLoad()
self.addContextMenuItem("Crack the Pack", unloadAllCards)
end
function unloadAllCards(player_color, position, object)
local objects = self.getObjects()
local basePos = self.positionToWorld({0, 0.5, 0})
local yOffset = 0
for i, obj in ipairs(objects) do
self.takeObject({
guid = obj.guid,
position = {basePos.x, basePos.y + yOffset, basePos.z},
smooth = false,
callback_function = function(takenObj)
takenObj.setRotationSmooth({0, 180, 0})
end
})
yOffset = yOffset + 0.2
end
Wait.time(checkEmptyAndDestroy, 0.5)
end
function onObjectLeaveContainer(container, leaving_object)
if container == self then
Wait.time(checkEmptyAndDestroy, 0.2)
end
end
function checkEmptyAndDestroy()
if #self.getObjects() == 0 then
self.destruct()
end
end
]]
}
local bagObj = spawnObjectJSON({
json = JSON.encode(bagJSON)
})
if bagObj then
log("spawnBagWithCards: Successfully spawned bag '" .. bagName .. "'")
onFullySpawned(bagObj)
else
log("spawnBagWithCards: FAILED to spawn bag '" .. bagName .. "'")
if onError then
onError("Failed to spawn custom bag")
end
end
end
------ SCRYFALL
local function stripScryfallImageURI(uri)
if not uri or string.len(uri) == 0 then
return ""
end
return uri:match("(.*)%?") or ""
end
local function pickImageURI(cardData, highres_image, image_status)
if not cardData or not cardData.image_uris then
return ""
end
local highres_image
if highres_image == nil then
highres_image = cardData.highres_image
end
local image_status
if image_status == nil then
image_status = cardData.image_status
end
local uri
if pngGraphics and cardData.image_uris.png then
uri = stripScryfallImageURI(cardData.image_uris.png)
else
uri = stripScryfallImageURI(cardData.image_uris.large)
end
local sep
if uri:find("?") then
sep = "&"
else
sep = "?"
end
if blowCache then
local cachebuster = string.gsub(tostring(Time.time), "%.", "-")
uri = uri .. sep .. "CACHEBUSTER_" .. cachebuster
elseif (not highres_image) or image_status ~= "highres_scan" then
uri = uri .. sep .. "LOWRES_CACHEBUSTER"
end
return uri
end
-- Returns a nicely formatted card name with type_line and cmc
local function getAugmentedName(cardData)
local name = cardData.name:gsub('"', '') or ""
if cardData.type_line then
name = name .. '\n' .. cardData.type_line
end
if cardData.cmc then
name = name .. '\n' .. cardData.cmc .. ' CMC'
end
return name
end
-- Returns a nicely formatted oracle text with power/toughness or loyalty
-- if present
local function getAugmentedOracleText(cardData)
local oracleText = cardData.oracle_text:gsub('"', "'")
if cardData.power and cardData.toughness then
oracleText = oracleText .. '\n[b]' .. cardData.power .. '/' .. cardData.toughness .. '[/b]'
elseif cardData.loyalty then
oracleText = oracleText .. '\n[b]' .. tostring(cardData.loyalty) .. '[/b]'
end
return oracleText
end
-- Collects oracle text from multiple faces if present
local function collectOracleText(cardData)
local oracleText = ""
if cardData.card_faces then
for i, face in ipairs(cardData.card_faces) do
oracleText = oracleText .. underline(face.name) .. getAugmentedOracleText(face)
if i < #cardData.card_faces then
oracleText = oracleText .. '\n\n'
end
end
else
oracleText = getAugmentedOracleText(cardData)
end
return oracleText
end
local function parseCardData(cardID, data)
local card = shallowCopyTable(cardID)
card.name = getAugmentedName(data)
card.oracleText = collectOracleText(data)
card.faces = {}
card.scryfallID = data.id
card.oracleID = data.oracle_id
card.language = data.lang
card.setCode = data.set
card.collectorNum = data.collector_number
if data.layout == "transform" or data.layout == "art_series" or data.layout == "double_sided" or data.layout ==
"modal_dfc" or data.layout == "double_faced_token" or data.layout == "reversible_card" then
for i, face in ipairs(data.card_faces) do
card.faces[i] = {
imageURI = pickImageURI(face, data.highres_image, data.image_status),
name = getAugmentedName(face),
oracleText = card.oracleText
}
end
else
card.faces[1] = {
imageURI = pickImageURI(data),
name = card.name,
oracleText = card.oracleText
}
end
return card
end
-- Parses scryfall response data for a card.
-- Queries for tokens and associated cards.
-- onSuccess is called with a populated card table, and list of tokens.
local function handleCardResponse(cardID, data, onSuccess, onError)
local sem = 0
local function incSem()
sem = sem + 1
end
local function decSem()
sem = sem - 1
end
local tokens = {}
local tokenDataForButtons = {}
local function addToken(name, uri)
incSem()
local headers = {
["User-Agent"] = "TTSMTGBoosterCreator/1.0",
["Accept"] = "application/json;q=0.9,*/*;q=0.8"
}
WebRequest.custom(uri, "GET", true, "", headers, function(webReturn)
if webReturn.is_error or webReturn.error or string.len(webReturn.text) == 0 then
local errorMsg = webReturn.error or "unknown"
-- Handle 429 rate limit with retry
if errorMsg:match("429") then
log("Rate limited (429) for token, retrying in " .. TOKEN_RETRY_DELAY .. " seconds...")
Wait.time(function()
addToken(name, uri)
end, TOKEN_RETRY_DELAY)
-- Don't decrement semaphore here - the retry will handle it
return
end
log("Error fetching token: " .. errorMsg)
decSem()
return
end
local success, data = pcall(function()
return jsondecode(webReturn.text)
end)
if not success or not data or data.object == "error" then
log("Error fetching token: JSON Parse")
decSem()
return
end
local token = parseCardData({}, data)
token.name = name
table.insert(tokens, token)
-- Store pared down token data for token buttons
local front
local back
if token.faces[1] then
front = token.faces[1].imageURI
end
if token.faces[2] then
back = token.faces[2].imageURI
else
back = getCardBack()
end
table.insert(tokenDataForButtons, {
name = token.name,
oracleText = token.oracleText,
front = front,
back = back
})
decSem()
end)
end
-- On normal cards, check for tokens or related effects (i.e. city's blessing)
if data.all_parts and not (data.layout == "token" or data.type_line == "Card") then
for _, part in ipairs(data.all_parts) do
if part.component and (part.type_line == "Card" or part.component == "token") then
addToken(part.name, part.uri)
-- shorten name on emblems
elseif part.component and
(string.sub(part.type_line, 1, 6) == "Emblem" and not (string.sub(data.type_line, 1, 6) == "Emblem")) then
addToken("Emblem", part.uri)
end
end
end
local card = parseCardData(cardID, data)
-- Store token data on each face
for _, face in ipairs(card.faces) do
face.tokenData = tokenDataForButtons
end
Wait.condition(function()
onSuccess(card, tokens)
end, function()
return (sem == 0)
end, QUERY_TIMEOUT, function()
onError("Error loading card data... timed out.")
end)
end
-- Queries scryfall by the [cardID].
-- cardID must define at least one of scryfallID, multiverseID, or name.
-- if forceNameQuery is true, will query scryfall by card name ignoring other data.
-- if forceSetNumLangQuery is true, will query scryfall by set/num/lang ignoring other data.
-- onSuccess is called with a populated card table, and a table of associated tokens.
local function queryCard(cardID, forceStandardLanguage, onSuccess, onError, retryCount)
retryCount = retryCount or 0
-- Validate input
if not cardID or not cardID.setCode or not cardID.collectorNum then
local errMsg = "Invalid cardID: missing setCode or collectorNum"
log(errMsg)
onError(errMsg)
return
end
if retryCount > MAX_RETRY_ATTEMPTS then
log("Max retries exceeded for card: " .. cardID.setCode .. ":" .. cardID.collectorNum)
onError("Max retries exceeded")
return
end
local query_url
local language_code = getLanguageCode()
if forceStandardLanguage and string.len(cardID.setCode) > 0 and string.len(cardID.collectorNum) > 0 then
query_url = SCRYFALL_SET_NUM_BASE_URL .. string.lower(cardID.setCode) .. "/" .. cardID.collectorNum
elseif string.len(cardID.setCode) > 0 and string.len(cardID.collectorNum) > 0 then
query_url = SCRYFALL_SET_NUM_BASE_URL ..
string.lower(cardID.setCode) .. "/" .. cardID.collectorNum .. "/" .. language_code
else
local errMsg = "Empty setCode or collectorNum for card"
log(errMsg)
onError(errMsg)
return
end
log("queryCard: " .. query_url)
local headers = {
["User-Agent"] = "TTSMTGBoosterCreator/1.0",
["Accept"] = "application/json;q=0.9,*/*;q=0.8"
}
local webRequest = WebRequest.custom(query_url, "GET", true, "", headers, function(webReturn)
if webReturn.is_error or webReturn.error then
local errorMsg = webReturn.error or "unknown error"
-- Handle 429 rate limit with exponential backoff
if errorMsg:match("429") then
local backoffTime = math.min(RETRY_BACKOFF_BASE * (2 ^ retryCount), RETRY_BACKOFF_MAX)
log(string.format("[RATE-LIMIT] 429 for %s:%s - retry #%d in %.1fs", cardID.setCode, cardID.collectorNum, retryCount + 1, backoffTime))
Wait.time(function()
queryCard(cardID, forceStandardLanguage, onSuccess, onError, retryCount + 1)
end, backoffTime)
return
end
log(string.format("[ERROR] WebRequest failed for %s:%s - %s", cardID.setCode, cardID.collectorNum, errorMsg))
onError("Web request error: " .. errorMsg)
return
elseif string.len(webReturn.text) == 0 then
log(string.format("[ERROR] Empty response for %s:%s", cardID.setCode, cardID.collectorNum))
onError("empty response")
return
end
local success, data = pcall(function() return jsondecode(webReturn.text) end)
if not success then
onError("failed to parse JSON response")
return
elseif not data then
onError("empty JSON response")
return
elseif data.object == "error" then
onError("failed to find card")
return
end
-- Grab the first card if response is a list
if data.object == "list" then
if data.total_cards == 0 or not data.data or not data.data[1] then
onError("failed to find card")
return
end
data = data.data[1]
end
handleCardResponse(cardID, data, onSuccess, onError)
end)
end
-- Queries multiple cards using Scryfall's Collection API (bulk endpoint)
-- Much faster than individual queries - batches up to 75 cards per request
local function queryCardCollection(cardIDs, onSuccess, onError, retryCount)
retryCount = retryCount or 0
if retryCount > MAX_RETRY_ATTEMPTS then
log("[ERROR] Max retries exceeded for collection query")
onError("Max retries exceeded")
return
end
-- Build the identifiers array for the collection API
local identifiers = {}
for _, cardID in ipairs(cardIDs) do
table.insert(identifiers, {
set = string.lower(cardID.setCode),
collector_number = cardID.collectorNum
})
end
-- Create the request body
local requestBody = jsonencode({
identifiers = identifiers
})
log(string.format("queryCardCollection: Fetching %d cards in bulk", #cardIDs))
local headers = {
["User-Agent"] = "TTSMTGBoosterCreator/1.0",
["Accept"] = "application/json;q=0.9,*/*;q=0.8",
["Content-Type"] = "application/json"
}
local webRequest = WebRequest.custom(SCRYFALL_COLLECTION_URL, "POST", true, requestBody, headers, function(webReturn)
if webReturn.is_error or webReturn.error then
local errorMsg = webReturn.error or "unknown error"
-- Handle 429 rate limit with exponential backoff
if errorMsg:match("429") then
local backoffTime = math.min(RETRY_BACKOFF_BASE * (2 ^ retryCount), RETRY_BACKOFF_MAX)
log(string.format("[RATE-LIMIT] 429 for collection query - retry #%d in %.1fs", retryCount + 1, backoffTime))
Wait.time(function()
queryCardCollection(cardIDs, onSuccess, onError, retryCount + 1)
end, backoffTime)
return
end
log("[ERROR] Collection API request failed: " .. errorMsg)
onError("Collection API error: " .. errorMsg)
return
elseif string.len(webReturn.text) == 0 then
log("[ERROR] Empty response from collection API")
onError("empty response")
return
end
local success, data = pcall(function() return jsondecode(webReturn.text) end)
if not success then
onError("failed to parse JSON response")
return
elseif not data then
onError("empty JSON response")
return
elseif data.object == "error" then
onError("Collection API returned error: " .. (data.details or "unknown"))
return
end
-- Process all returned cards
if not data.data or #data.data == 0 then
log("[WARNING] Collection API returned no cards")
onSuccess({})
return
end
-- Create a map of cards by set:collector_number for quick lookup
local cardMap = {}
for _, cardData in ipairs(data.data) do
local key = string.lower(cardData.set) .. ":" .. cardData.collector_number
cardMap[key] = cardData
end
-- Match returned cards to our cardIDs in order, handling missing cards
local results = {}
for _, cardID in ipairs(cardIDs) do
local key = string.lower(cardID.setCode) .. ":" .. cardID.collectorNum
local cardData = cardMap[key]
if cardData then
table.insert(results, {
cardID = cardID,
data = cardData
})
else
log(string.format("[WARNING] Card not found in collection response: %s:%s", cardID.setCode, cardID.collectorNum))
-- We'll need to query this one individually later
table.insert(results, {
cardID = cardID,
data = nil
})
end
end
onSuccess(results)
end)
end
-- Queries card data for all cards using bulk Collection API
local function fetchCardData(cards, onComplete, onError)
log("fetchCardData: Starting bulk fetch for " .. #cards .. " cards")
local sem = 0
local function incSem() sem = sem + 1 end
local function decSem() sem = sem - 1 end
local cardData = {}
local tokensData = {}
local function cleanCollectorNum(collectorNum)
return string.match(collectorNum, "%d+")
end
-- Split cards into batches of COLLECTION_BATCH_SIZE (75)
local batches = {}
for i = 1, #cards, COLLECTION_BATCH_SIZE do
local batch = {}
for j = i, math.min(i + COLLECTION_BATCH_SIZE - 1, #cards) do
table.insert(batch, cards[j])
end
table.insert(batches, batch)
end
log(string.format("fetchCardData: Split into %d batches", #batches))
-- Process each batch with a slight delay
local batchDelay = 0
for batchIndex, batch in ipairs(batches) do
incSem()
Wait.time(function()
queryCardCollection(batch, function(results)
-- Process results and handle cards that need individual queries
local cardsNeedingRetry = {}
for _, result in ipairs(results) do
if result.data then
-- Card found, process it
incSem()
handleCardResponse(result.cardID, result.data, function(card, tokens)
table.insert(cardData, card)
for _, token in ipairs(tokens) do
table.insert(tokensData, token)
end
decSem()
end, function(e)
log("[ERROR] Failed to process card from collection: " .. e)
decSem()
end)
else
-- Card not found in collection, need individual query
table.insert(cardsNeedingRetry, result.cardID)
end
end
-- Query missing cards individually
for _, cardID in ipairs(cardsNeedingRetry) do