Repository navigation
Expand file tree
/
Copy pathstorageCraftingServer.lua
More file actions
3756 lines (3427 loc) · 154 KB
/
Copy pathstorageCraftingServer.lua
File metadata and controls
3756 lines (3427 loc) · 154 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
math.randomseed(os.time() + (6 * os.getComputerID()))
local storage
items = {} -- GLOBAL: crafting thread needs to read this
local serverLAN, serverWireless
local tags = {}
local clients = {}
local slaves = {}
local recipes = {}
local storageServerSocket, masterCraftingServerSocket
local onCryptoNetEvent
local cryptoNetURL = "https://raw.githubusercontent.com/SiliconSloth/CryptoNet/master/cryptoNet.lua"
local detailDB
currentlyCrafting = {} -- GLOBAL: crafting thread modifies this, main thread reads it
local craftingUpdateClients = {}
local speakers = {}
local serverBootTime = os.epoch("utc") / 1000
local itemNameIndex = {}
local itemTagIndex = {}
local itemCacheDirty = true
if not fs.exists("cryptoNet") then
print("")
print("cryptoNet API not found on disk, downloading...")
local response = http.get(cryptoNetURL)
if response then
local file = fs.open("cryptoNet", "w")
file.write(response.readAll())
file.close()
response.close()
print("File downloaded as '" .. "cryptoNet" .. "'.")
else
print("Failed to download file from " .. cryptoNetURL)
end
end
os.loadAPI("cryptoNet")
-- Suppress IDE warnings
os.getComputerID = os.getComputerID
os.epoch = os.epoch
os.loadAPI = os.loadAPI
os.queueEvent = os.queueEvent
os.startThread = os.startThread
os.pullEvent = os.pullEvent
os.startTimer = os.startTimer
os.reboot = os.reboot
os.setComputerLabel = os.setComputerLabel
utf8 = utf8
cryptoNet = cryptoNet
-- Settings
settings.define("debug", {
description = "Enables debug options",
default = "false",
type = "boolean"
})
settings.define("isMainCraftingServer", {
description = "sets if this server is the main craftingTable server",
default = "true",
type = "boolean"
})
-- Oneliner bash to extract recipes from craft tweaker output:
-- grep craftingTable crafttweaker.log > recipes
settings.define("recipeURL", {
description = "The URL containing all recipes",
"https://raw.githubusercontent.com/schindlershadow/ComputerCraft-Item-Storage-System/main/vanillaRecipes.txt",
type = "string"
})
settings.define("recipeFile", {
description = "The temp file used for loading recipes",
"recipes",
type = "string"
})
settings.define("craftingChest", {
description = "The peripheral name of the crafting chest that is above the turtle",
"minecraft:chest_3",
type = "string"
})
settings.define("serverName", {
description = "The hostname of this server",
"CraftingServer" .. tostring(os.getComputerID()),
type = "string"
})
settings.define("StorageServer", {
description = "storage server hostname",
default = "StorageServer",
type = "string"
})
settings.define("requireLogin", {
description = "require a login for LAN clients",
default = "false",
type = "boolean"
})
settings.define("isMasterCraftingServer", {
description = "Defines master server vs slave server",
default = "true",
type = "boolean"
})
settings.define("masterCraftingServer", {
description = "The hostname of the master crafting server",
"CraftingServer",
type = "string"
})
settings.define("enableRSBridgeCrafting", {
description = "Enable crafting via RS Bridge (disable if it causes freezes)",
default = "false",
type = "boolean"
})
-- Settings fails to load
if settings.load() == false then
print("No settings have been found! Default values will be used!")
print("Only vanilla recipes will be loaded, change the recipeURL in .settings for modded Minecraft")
settings.set("serverName", "CraftingServer" .. tostring(os.getComputerID()))
settings.set("StorageServer", "StorageServer")
settings.set("debug", false)
settings.set("isMainCraftingServer", true)
settings.set("isMasterCraftingServer", true)
settings.set("masterCraftingServer", "CraftingServer")
settings.set("requireLogin", false)
settings.set("recipeURL",
"https://raw.githubusercontent.com/schindlershadow/ComputerCraft-Item-Storage-System/main/vanillaRecipes.txt")
settings.set("recipeFile", "recipes")
settings.set("craftingChest", "minecraft:chest_3")
print("Stop the server and edit .settings file with correct settings")
settings.save()
sleep(5)
end
-- Dumps a table to string
local function dump(o)
if type(o) == "table" then
local s = ""
for k, v in pairs(o) do
if type(k) ~= "table" then
if type(k) ~= "number" then
k = '"' .. k .. '"'
end
s = s .. "[" .. k .. "] = " .. dump(v) .. ","
end
end
return s
else
return tostring(o)
end
end
-- Logs text to log file
local function log(text)
local logFile = fs.open("logs/craftingServer.log", "a")
if type(text) == "string" then
logFile.writeLine(os.date("%A/%d/%B/%Y %I:%M%p") .. ", " .. text)
else
logFile.writeLine(os.date("%A/%d/%B/%Y %I:%M%p") .. ", " .. textutils.serialise(text))
end
logFile.close()
end
-- Logs text only if debug mode is enabled
local function debugLog(text)
if settings.get("debug") then
local logFile = fs.open("logs/craftingServerDebug.log", "a")
if type(text) == "string" then
logFile.writeLine(os.date("%A/%d/%B/%Y %I:%M%p") .. ", " .. text)
else
logFile.writeLine(os.date("%A/%d/%B/%Y %I:%M%p") .. ", " .. textutils.serialise(text))
end
logFile.close()
end
end
-- fixes tags entry in recipe causing textutils.serialise to throw error
local function cleanRecipe(table)
local arr = {}
-- print("size: " .. tostring(#table))
for k, v in pairs(table) do
local tab = {}
tab.recipeType = v.recipeType
tab.name = v.name
tab.count = v.count
tab.recipeName = v.recipeName
tab.recipe = v.recipe
tab.recipeInput = v.recipeInput
tab.displayName = v.displayName
-- tab.tags = v.tags
-- No idea why this works
local tag = textutils.serialize(v.tags)
tab.tags = textutils.unserialise(tag)
arr[#arr + 1] = tab
-- print(tostring(k))
-- debugLog("k: " .. tostring(k) .. " dump: " .. dump(tab))
-- debugLog(textutils.serialize(tab))
end
return arr
end
-- These set of global functions are used when importing recipes
-- MUST be global
function addShaped(recipeName, name, arg3, arg4)
-- print("name: " .. name)
-- print("itemOutput: " .. itemOutput)
local tab = {}
local outputNumber = 1
local recipe
if arg4 then
-- print("number of output: " .. tostring(arg3))
-- print("recipe: " .. dump(arg4))
outputNumber = arg3
recipe = arg4
else
-- print("recipe: " .. dump(arg3))
recipe = arg3
end
name = string.match(name, 'item:(.+)')
tab["name"] = name
tab["recipeName"] = recipeName
tab["count"] = outputNumber
tab["recipeType"] = "shaped"
if type(recipe[1][1]) == "table" then
tab["recipeInput"] = "variable"
tab["recipe"] = recipe
else
tab["recipeInput"] = "static"
-- Convert to variable recipe format
for i = 1, #recipe, 1 do
for j = 1, #recipe[i], 1 do
recipe[i][j] = {recipe[i][j]}
end
end
tab["recipe"] = recipe
end
recipes[#recipes + 1] = tab
end
-- MUST be global
function addShapeless(recipeName, name, arg3, arg4)
local tab = {}
local outputNumber = 1
local recipe
if arg4 then
outputNumber = arg3
recipe = arg4
else
recipe = arg3
end
name = string.match(name, 'item:(.+)')
tab["name"] = name
tab["recipeName"] = recipeName
tab["count"] = outputNumber
-- tab["recipe"] = recipe
tab["recipeType"] = "shapeless"
local isVar = false
for i = 1, #recipe, 1 do
if type(recipe[i]) == "table" then
isVar = true
end
end
if isVar then
tab["recipeInput"] = "variable"
recipe = recipe[1]
-- Put every item into a table to have a uniform recipe
for i = 1, #recipe, 1 do
if type(recipe[i]) ~= "table" then
recipe[i] = {recipe[i]}
end
end
else
tab["recipeInput"] = "static"
end
-- Convert to universal shaped variable recipe format
local convertedRecipe = {{}, {}, {}}
for row = 1, 3, 1 do
for slot = 1, 3, 1 do
if type(recipe[((row - 1) * 3) + slot]) == "nil" then
convertedRecipe[row][slot] = {"none"}
elseif isVar then
convertedRecipe[row][slot] = recipe[((row - 1) * 3) + slot]
else
convertedRecipe[row][slot] = {recipe[((row - 1) * 3) + slot]}
end
end
end
tab["recipe"] = convertedRecipe
if recipeName == "byg:fire_charge_from_byg_coals" then
debugLog(textutils.serialise(tab))
end
recipes[#recipes + 1] = tab
end
-- MUST be global
craftingTable = {
addShaped = addShaped,
addShapeless = addShapeless
}
-- MUST be global
function getInstance()
return "none"
end
-- MUST be global
IIngredientEmpty = {
getInstance = getInstance
}
-- MUST be GLOBAL so that threads can see updates
-- Using a local variable would cause thread to have a stale copy
craftingQueue = {}
craftingQueue.first = 0
craftingQueue.last = -1
function craftingQueue.pushleft(value)
local first = craftingQueue.first - 1
craftingQueue.first = first
craftingQueue[first] = value
end
function craftingQueue.pushright(value)
debugLog("=== QUEUE: pushright called, old last=" .. tostring(craftingQueue.last) .. " ===")
local last = craftingQueue.last + 1
craftingQueue.last = last
craftingQueue[last] = value
debugLog("=== QUEUE: pushright done, new last=" .. tostring(craftingQueue.last) .. " ===")
end
function craftingQueue.popleft()
debugLog("=== QUEUE: popleft called, first=" .. tostring(craftingQueue.first) .. ", last=" .. tostring(craftingQueue.last) .. " ===")
local first = craftingQueue.first
if first > craftingQueue.last then
error("craftingQueue is empty")
end
local value = craftingQueue[first]
craftingQueue[first] = nil -- to allow garbage collection
craftingQueue.first = first + 1
debugLog("=== QUEUE: popleft returning item, new first=" .. tostring(craftingQueue.first) .. " ===")
return value
end
function craftingQueue.popright()
local last = craftingQueue.last
if craftingQueue.first > last then
error("craftingQueue is empty")
end
local value = craftingQueue[last]
craftingQueue[last] = nil -- to allow garbage collection
craftingQueue.last = last - 1
return value
end
function craftingQueue.dumpItems()
-- This allows us to send the queue without socket information
local last = craftingQueue.last
local first = craftingQueue.first
local tab = {}
-- debugLog("craftingQueue.dump()")
if craftingQueue.first > last then
-- Still check for RS queue even if crafting queue is empty
else
for i = first, last, 1 do
local tmp = {}
tmp.name = craftingQueue[i].name
tmp.displayName = craftingQueue[i].displayName
tmp.amount = craftingQueue[i].amount
tmp.count = craftingQueue[i].count
tmp.recipeType = craftingQueue[i].recipeType
tmp.recipeInput = craftingQueue[i].recipeInput
tmp.recipe = craftingQueue[i].recipe
tmp.recipeName = craftingQueue[i].recipeName
table.insert(tab, tmp)
end
end
debugLog("craftingQueue dump: " .. dump(tab))
return tab
end
-- Deduplication tracking for autoCraftItem messages
-- Prevents duplicate craft requests from being processed twice
local recentCraftRequests = {}
local function trackCraftRequest(itemName, amount, recipeName)
local key = itemName .. ":" .. tostring(amount) .. ":" .. tostring(recipeName)
local currentTime = os.epoch("utc") / 1000
recentCraftRequests[key] = currentTime
-- Clean up old entries (older than 2 seconds)
for k, v in pairs(recentCraftRequests) do
if currentTime - v > 2 then
recentCraftRequests[k] = nil
end
end
end
local function isDuplicateCraftRequest(itemName, amount, recipeName)
local key = itemName .. ":" .. tostring(amount) .. ":" .. tostring(recipeName)
if recentCraftRequests[key] then
return true
end
return false
end
local function isRequestAlreadyQueued(itemName, recipeName)
-- Check if the same item/recipe is already at the front of the queue
if craftingQueue.first <= craftingQueue.last then
local frontRequest = craftingQueue[craftingQueue.first]
if frontRequest and frontRequest.name == itemName and frontRequest.recipe.recipeName == recipeName then
return true
end
end
return false
end
-- Throttle inventory refresh requests to avoid event spam
local lastInventoryRefreshTime = 0
local INVENTORY_REFRESH_THROTTLE = 1 -- Wait at least 1 second between refresh events
local function shouldQueueInventoryRefresh()
local now = os.epoch("utc") / 1000
if now - lastInventoryRefreshTime >= INVENTORY_REFRESH_THROTTLE then
lastInventoryRefreshTime = now
return true
end
return false
end
local function logError(err)
-- Format a timestamp if you have an in-game day or real-world time via os.epoch
local timeStr = textutils.formatTime(os.time(), true)
local logMsg = string.format("[%s] CRASH: %s\n", timeStr, tostring(err))
-- Append the crash message to an error log file
local file = fs.open("logs/crash.log", "a")
if file then
file.write(logMsg)
file.close()
else
print("Failed to write to log file!")
end
end
local function findInTable(arr, element)
for i, value in pairs(arr) do
if value.name == element.name and value.nbt == element.nbt then
return i
end
end
return nil
end
local function inTable(arr, element) -- function to check if something is in an table
for _, value in pairs(arr) do
if value.name == element.name and value.nbt == element.nbt then
return true
end
end
return false -- if no element was found, return false
end
-- MUST be global
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
local itemTagCache = {}
local tagIndex = {}
local function getItemTagCache(itemName)
local cached = itemTagCache[itemName]
if cached ~= nil then
return cached
end
local tagsForItem = {}
for tagName, nameTable in pairs(tags or {}) do
if type(nameTable) == "table" then
for _, name in pairs(nameTable) do
if name == itemName then
tagsForItem[tagName] = true
break
end
end
end
end
itemTagCache[itemName] = tagsForItem
return tagsForItem
end
-- Creates a tab table using the tabs db, use this to avoid costly peripheral lookups
local function reconstructTags(itemName)
local tab = {}
tab.tags = {}
local tagsForItem = getItemTagCache(itemName)
for tagName in pairs(tagsForItem) do
tab.tags[tagName] = true
end
return tab
end
-- Check if item name is in tag db
local function inTags(itemName)
-- debugLog("inTags called for: " .. tostring(itemName))
if type(itemName) == "nil" then
return nil
end
local tagsForItem = getItemTagCache(itemName)
return next(tagsForItem) ~= nil
end
local function saveTagDB()
-- print("Updated tags.db: " .. tostring(countTags) .. " tags, " .. tostring(countItems) .. " items")
if fs.exists("tags.db") then
fs.delete("tags.db")
end
local tagsFile = fs.open("tags.db", "w")
tagsFile.write(textutils.serialise(tags))
tagsFile.close()
end
-- Mantain tags lookup
local function addTag(item)
-- print("addTag for: " .. item.name)
-- Maintain tags count
local countTags
if type(tags.count) ~= "number" then
countTags = 0
else
countTags = tags.count
end
-- Maintain item count
local countItems
if type(tags.countItems) ~= "number" then
countItems = 0
else
countItems = tags.countItems
end
local initCountTags = countTags
local initCountItems = countItems
local itemName = item.name
local itemTags = itemTagCache[itemName]
if itemTags == nil then
itemTags = {}
itemTagCache[itemName] = itemTags
end
-- Get the tags which are keys in table item.details.tags
if type(item.details) == "nil" then
item.details = peripheral.wrap(item.chestName).getItemDetail(item.slot)
end
if type(item.details) ~= "nil" and type(item.details.tags) == "table" then
-- debugLog(textutils.serialise(item.details.tags))
for key, value in pairs(item.details.tags) do
-- If it's a map, the key is the string. If it's an array, the value is the string.
local rawTagName = (type(key) == "string") and key or value
-- Strip out "minecraft:item/" or "minecraft:block/" if present
-- Note the %: used to escape the colon character in Lua patterns
local tagName = string.gsub(rawTagName, "^minecraft:%w+/", "")
if not itemTags[tagName] then
itemTags[tagName] = true
local tagMembers = tagIndex[tagName]
if tagMembers == nil then
tagMembers = {}
tagIndex[tagName] = tagMembers
local existingTagItems = tags[tagName]
if type(existingTagItems) == "table" then
for _, existingItemName in pairs(existingTagItems) do
tagMembers[existingItemName] = true
end
end
end
if not tagMembers[itemName] then
tagMembers[itemName] = true
local tagItems = tags[tagName]
if type(tagItems) == "nil" then
print("Found new tag: " .. tagName .. " for item: " .. itemName)
-- print("Found new item: " .. itemName)
debugLog("Found new tag: " .. tagName .. " for item: " .. itemName)
tags[tagName] = {itemName}
countTags = countTags + 1
countItems = countItems + 1
else
print("Found new item: " .. itemName)
debugLog("Found new item: " .. itemName)
tagItems[#tagItems + 1] = itemName
countItems = countItems + 1
end
end
end
end
end
tags.count = countTags
tags.countItems = countItems
end
local function rebuildItemCaches()
local nameIndex = {}
local tagIndex = {}
-- Ensure we filter unique slots right from the core items payload
local uniqueSlots = {}
local sanitizedItems = {}
for _, entry in pairs(items or {}) do
if entry ~= nil and entry.name ~= nil then
-- Create a true physical tracking signature (using slot/count or name/slot combination)
local physicalKey = entry.name .. "_slot_" .. tostring(entry.slot or 0)
-- Prevent tracking identical overlapping items across messy storage updates
if not uniqueSlots[physicalKey] then
uniqueSlots[physicalKey] = true
sanitizedItems[#sanitizedItems + 1] = entry
local name = entry.name
local list = nameIndex[name]
if list == nil then
list = {}
nameIndex[name] = list
end
list[#list + 1] = entry
if entry.details == nil then
entry.details = reconstructTags(name)
end
if entry.details ~= nil and entry.details.tags ~= nil then
for tagKey, tagVal in pairs(entry.details.tags) do
local tag = (type(tagKey) == "string") and tagKey or tagVal
tag = string.gsub(tag, "^minecraft:%w+/", "")
local tagList = tagIndex[tag]
if tagList == nil then
tagList = {}
tagIndex[tag] = tagList
end
tagList[#tagList + 1] = entry
end
end
end
end
end
itemNameIndex = nameIndex
itemTagIndex = tagIndex
itemCacheDirty = false
end
local function ensureItemCaches()
if itemCacheDirty then
rebuildItemCaches()
end
end
-- Waits for a specific named event without dropping any other events that arrive in the
-- meantime. This whole program runs inside cryptoNet's single event loop, so a plain
-- filtered os.pullEvent(name) would discard raw network replies it doesn't care about -
-- including the exact one needed to eventually produce the event we're waiting for,
-- causing a permanent freeze. Re-queuing unmatched events doesn't work either: this
-- inner loop would just grab its own re-queued event again before cryptoNet's outer
-- loop ever gets a turn, spamming the same handful of messages forever. Instead, we
-- dispatch anything we don't want straight to the real handler ourselves, so normal
-- messages (watchCrafting, getItems responses, etc.) still get processed properly.
local function waitForEvent(name, timeout, reason)
timeout = timeout or 10
debugLog("waitForEvent: " .. tostring(name) .. " (reason: " .. tostring(reason) .. ")")
local timerId = os.startTimer(timeout)
while true do
local event = {os.pullEvent()}
if event[1] == name then
debugLog("waitForEvent: got " .. tostring(name))
return event[1]
elseif event[1] == "timer" and event[2] == timerId then
debugLog("waitForEvent: timeout waiting for " .. tostring(name) .. " (reason: " .. tostring(reason) .. ")")
if tostring(name) == "itemsUpdated" then
return "itemsUpdated"
end
return nil
elseif type(onCryptoNetEvent) == "function" then
onCryptoNetEvent(event)
end
end
end
-- Same as waitForEvent, but for callers that need the extra payload values a raw
-- os.pullEvent(name) would normally return (e.g. os.pullEvent("hashLogin") also
-- returns loginStatus and permissionLevel), not just the event name.
local function waitForEventFull(name, timeout)
timeout = timeout or 10
debugLog("waitForEventFull: " .. tostring(name))
local timerId = os.startTimer(timeout)
while true do
local event = {os.pullEvent()}
if event[1] == name then
debugLog("waitForEventFull: got " .. tostring(name))
return table.unpack(event)
elseif event[1] == "timer" and event[2] == timerId then
debugLog("waitForEventFull: timeout waiting for " .. tostring(name))
return nil
elseif type(onCryptoNetEvent) == "function" then
onCryptoNetEvent(event)
end
end
end
local itemsUpdateWaiting = false
local getItemsRequestSent = false
-- Blocks until "itemsUpdated" fires - but only if nobody else is already blocked on it.
-- Earlier attempts had reentrant/piggybacking callers also call os.pullEvent themselves
-- (directly or via a generation-counter loop), which just moved the "two listeners
-- competing for the same untagged event" bug one level deeper instead of removing it.
-- The only safe rule: exactly one call frame, ever, is allowed to actually pull events
-- for this. Anyone called re-entrantly (e.g. a databaseReload broadcast forwarded to us
-- while we're already nested inside another wait) just returns immediately - the outer
-- frame that's genuinely blocked will see the eventual itemsUpdated event and refresh
-- `items` before IT returns, which is all any nested caller actually needed.
-- Returns true if this call was the one that actually performed the wait.
local function blockForItemsUpdated(reason)
debugLog("blockForItemsUpdated CALLED with reason: " .. tostring(reason))
if itemsUpdateWaiting then
debugLog("blockForItemsUpdated: itemsUpdateWaiting already true, returning false")
return false
end
itemsUpdateWaiting = true
debugLog("blockForItemsUpdated: ABOUT TO CALL waitForEvent (THIS MAY BLOCK)")
waitForEvent("itemsUpdated", nil, reason)
debugLog("blockForItemsUpdated: RETURNED FROM waitForEvent")
itemsUpdateWaiting = false
getItemsRequestSent = false
return true
end
local function getDatabaseFromServer(reason)
if not getItemsRequestSent then
-- Only actually send the request if nobody else currently has one in flight.
getItemsRequestSent = true
cryptoNet.send(storageServerSocket, {"getItems"})
end
blockForItemsUpdated("getDatabaseFromServer" .. ": " .. tostring(reason))
end
local function getDetailDBFromServer()
cryptoNet.send(storageServerSocket, {"getDetailDB"})
waitForEvent("detailDBUpdated", nil, "getDetailDBFromServer")
local count = 0
if type(detailDB) ~= "table" then
print("detailDB is not a table, got: " .. tostring(detailDB))
return
end
for _ in pairs(detailDB) do
count = count + 1
end
print("Got " .. tostring(count) .. " items metadeta from storageserver")
-- sleep(5)
end
local function pingServer()
cryptoNet.send(storageServerSocket, {"ping"})
waitForEvent("storageServerAck", nil, "pingServer")
end
local function Split(s, delimiter)
local result = {};
for match in (s .. delimiter):gmatch("(.-)" .. delimiter) do
table.insert(result, match);
end
return result;
end
-- Grab recipe file from an http source in crafttweaker output format and covert it to lua code
local function getRecipes()
-- This whole thing is extremely jank to workaround limited CC storage
print("Loading recipes...")
print("Recipe URL set to: " .. settings.get("recipeURL"))
local contents = http.get(settings.get("recipeURL"))
local fileName = settings.get("recipeFile")
-- local file = fs.open(fileName, "r")
local lines = {}
while true do
-- local line = file.readLine()
local line = contents.readLine()
-- If line is nil then we've reached the end of the file and should stop
if not line then
break
end
lines[#lines + 1] = line
end
-- file.close()
-- deal with the recipes that have multiple possible item inputs
for i = 1, #lines, 1 do
local line = lines[i]
if string.find(line, '|') then
table.remove(lines, i)
local firstHalf = string.sub(line, 1, string.find(line, '%[') - 1)
local recipe = ""
if string.find(line, '%[%[') then
recipe = string.sub(line, string.find(line, '%[') + 1, string.find(line, ');') - 3)
else
recipe = string.sub(line, string.find(line, '%['), string.find(line, ');') - 2)
end
local row = Split(recipe, '],')
local newRecipes = {}
-- Convert the string recipe into an array
for k = 1, #row, 1 do
-- cut out the first char which is [
row[k] = string.sub(row[k], 2, #row[k])
newRecipes[k] = {}
local slot = Split(row[k], ',')
for m = 1, #slot, 1 do
local inputs = Split(slot[m], '|')
newRecipes[k][m] = {}
for j = 1, #inputs, 1 do
newRecipes[k][m][j] = inputs[j]:gsub(' ', '')
end
end
end
-- Rebuild the crafttweaker string with the new format
local newLine = firstHalf .. '['
for row2 = 1, #newRecipes, 1 do
newLine = newLine .. '['
for slot = 1, #newRecipes[row2], 1 do
if #newRecipes[row2][slot] == 1 then
if string.find(newRecipes[row2][slot][1], '%[') then
newRecipes[row2][slot][1] = '{' .. string.gsub(newRecipes[row2][slot][1], '%[', '') .. '}'
end
newLine = newLine .. newRecipes[row2][slot][1]
else
newLine = newLine .. '{'
for j = 1, #newRecipes[row2][slot] do
if string.find(newRecipes[row2][slot][j], '%[') then
newRecipes[row2][slot][j] = string.gsub(newRecipes[row2][slot][j], '%[', '')
end
newLine = newLine .. newRecipes[row2][slot][j]
if j ~= #newRecipes[row2][slot] then
newLine = newLine .. ','
end
end
newLine = newLine .. '}'
end
if slot ~= #newRecipes[row2] then
newLine = newLine .. ','
end
end
if row2 == #newRecipes then
newLine = newLine .. ']'
else
newLine = newLine .. '],'
end
end
newLine = newLine .. ']);'
--[[
if string.find(newLine, '"minecraft:torch"') then
print(newLine)
end
--]]
lines[#lines + 1] = newLine
end
lines[i] = line
end
-- Do a bunch of replacements to convert to lua code
for i = 1, #lines, 1 do
local line = lines[i]
-- ignore recipes that need a tag or damage value
if string.find(line, '|') or string.find(line, 'withTag') or string.find(line, 'withDamage') or
string.find(line, 'withJsonComponent') then
line = ""
else
line = string.gsub(line, "<", '"')
line = string.gsub(line, ">", '"')
line = string.gsub(line, '%[', '{')
line = string.gsub(line, '%]', '}')
line = string.gsub(line, ' %* ', ' ,')
line = string.gsub(line, ';', '\n')
end
lines[i] = line
end
-- The file might be larger than the filesystem, so do it in small chunks
local count = #lines
local fileNumber = 1
print("Number of lines " .. tostring(count))
while count > 0 do
local outFile = fs.open(tostring(fileNumber) .. fileName, "w")
for i = 1, 100, 1 do
if count > 0 then
outFile.writeLine(lines[count])
count = count - 1
end
end
outFile.close()
-- print(tostring(count))
-- print(fileNumber)
require(tostring(fileNumber) .. fileName)
fs.delete(tostring(fileNumber) .. fileName)
fileNumber = fileNumber + 1
end
-- Add the display name from detailDB we got from the storage server
if type(detailDB) ~= "nil" then
for i = 1, #recipes, 1 do
if detailDB[recipes[i].name] ~= nil then
recipes[i].displayName = detailDB[recipes[i].name].displayName
recipes[i].tags = detailDB[recipes[i].name].tags
elseif recipes[i].displayName == nil then
recipes[i].displayName = ""
end
end
end
print(tostring(#recipes) .. " recipes loaded!")
end
local function getTableSize(t)
local count = 0
for _ in pairs(t) do
count = count + 1
end
return count
end
local function getItemNameFromTag(tag)
debugLog("getItemNameFromTag called for: " .. tostring(tag))
-- Extract the tag name (remove "tag:" and "item:" prefixes)
local stringTag = string.gsub(tag, "^tag:", "")
stringTag = string.gsub(stringTag, "^item:", "")
debugLog("stringTag: " .. stringTag)
debugLog("#tags: " .. getTableSize(tags))
-- Look up in the tags table loaded from tags.db
if type(tags[stringTag]) == "table" and #tags[stringTag] > 0 then
local itemName = tags[stringTag][1]
debugLog("Found item " .. itemName .. " for tag: " .. stringTag)
return itemName
end
debugLog("No items found for tag: " .. tag)
return nil
end
local function searchForTag(searchString, InputTable, count, quick)
ensureItemCaches()
if type(searchString) == "table" then
for i = 1, #searchString do
local result, number, index = searchForTag(searchString[i], InputTable, count, quick)
if number >= (count or 1) then
return result, number, index
end
end
return nil, 0, nil
end
debugLog("searchForTag called for: " .. tostring(searchString) .. " count: " .. tostring(count))
local stringTag = string.gsub(searchString, "^tag:", "")
stringTag = string.gsub(stringTag, "^%w+:", "")
debugLog("stringTag: " .. tostring(stringTag))
local number = 0
local returnV = nil