-
Notifications
You must be signed in to change notification settings - Fork 1
/
storageCraftingServer.lua
2724 lines (2511 loc) · 105 KB
/
storageCraftingServer.lua
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
local serverLAN, serverWireless
local tags = {}
local clients = {}
local slaves = {}
local recipes = {}
local storageServerSocket, masterCraftingServerSocket
local cryptoNetURL = "https://raw.githubusercontent.com/SiliconSloth/CryptoNet/master/cryptoNet.lua"
local detailDB
local currentlyCrafting = {}
local craftingUpdateClients = {}
local speakers = {}
local serverBootTime = os.epoch("utc") / 1000
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"
})
-- 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 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("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) ~= "number" then
k = '"' .. k .. '"'
end
s = s .. "[" .. k .. "] = " .. dump(v) .. ","
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
}
local 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)
local last = craftingQueue.last + 1
craftingQueue.last = last
craftingQueue[last] = value
end
function craftingQueue.popleft()
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
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
return tab
end
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
debugLog(dump(tab))
return tab
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
-- Creates a tab table using the tabs db, use this to avoid costly peripheral lookups
local function reconstructTags(itemName)
local tab = {}
tab.tags = {}
for tag, nameTable in pairs(tags) do
if type(nameTable) == "table" then
for _, name in pairs(nameTable) do
if name == itemName then
tab.tags[tag] = true
end
end
end
end
return tab
end
-- Check if item name is in tag db
local function inTags(itemName)
for _, nameTable in pairs(tags) do
if type(nameTable) == "table" then
for _, name in pairs(nameTable) do
if name == itemName then
return true
end
end
end
end
return false
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
-- Get the tags which are keys in table item.details.tags
local keyset = {}
local n = 0
if type(item.details) == "nil" then
item.details = peripheral.wrap(item.chestName).getItemDetail(item.slot)
end
if type(item.details) ~= "nil" then
for k, v in pairs(item.details.tags) do
n = n + 1
keyset[n] = k
end
end
-- print(dump(keyset))
-- Add them to tags table if they dont exist, if they exist add the item name to the list
for i = 1, #keyset, 1 do
if type(tags[keyset[i]]) == "nil" then
print("Found new tag: " .. keyset[i])
print("Found new item: " .. item.name)
tags[keyset[i]] = {item.name}
countTags = countTags + 1
countItems = countItems + 1
elseif table.contains(tags[keyset[i]], item.name) == false then
print("Found new item: " .. item.name)
table.insert(tags[keyset[i]], item.name)
countItems = countItems + 1
end
end
tags.count = countTags
tags.countItems = countItems
end
local function getDatabaseFromServer()
cryptoNet.send(storageServerSocket, {"getItems"})
local event
repeat
event = os.pullEvent("itemsUpdated")
until event == "itemsUpdated"
end
local function getDetailDBFromServer()
cryptoNet.send(storageServerSocket, {"getDetailDB"})
local event
repeat
event = os.pullEvent("detailDBUpdated")
until event == "detailDBUpdated"
local count = 0
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"})
local event
repeat
event = os.pullEvent("storageServerAck")
until event == "storageServerAck"
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 searchForTag(string, InputTable, count)
local find = string.find
local match = string.match
local stringTag = match(string, 'tag:%w+:(.+)')
local number = 0
local returnV = nil
local returnK
for k, v in pairs(InputTable) do
if v.details then
if v.details.tags then
-- print(stringTag .. " == " .. tostring(find(dump(v.details.tags),stringTag)))
if v.details.tags[stringTag] then
number = number + v.count
end
if v.details.tags[stringTag] and v.count >= count then
returnV = v
returnK = k
end
end
end
end
return returnV, number, returnK
end
-- Returns matched item obj, total number in list and index of matched obj
local function search(searchTerm, InputTable, count)
if string.find(searchTerm, "tag:") then
return searchForTag(searchTerm, InputTable, count)
else
local stringSearch = string.match(searchTerm, 'item:(.+)')
local find = string.find
local number = 0
local returnV = nil
local returnK
-- print("need " .. tostring(count) .. " of " .. stringSearch)
for k, v in pairs(InputTable) do
if (v["name"]) == (stringSearch) then
number = number + v.count
if v.count >= count then
-- print("Found: " .. tostring(v.count) .. " of " .. v.name)
returnV = v
returnK = k
end
end
end
return returnV, number, returnK
end
end
local function searchForItemWithTag(string, InputTable)
local filteredTable = {}
local find = string.find
local match = string.match
local stringTag = match(string, 'tag:%w+:(.+)')
for k, v in pairs(InputTable) do
if v.details then
if v.details.tags then
if v.details.tags[stringTag] then
filteredTable[#filteredTable + 1] = v
end
end
end
end
if filteredTable == {} then
return {}
else
return filteredTable
end
end
local function updateClient(socket, message, messageToSend)
local table = {}
table.type = "craftingUpdate"
table.message = message
if message == "slotUpdate" then
table[1] = messageToSend[1]
table[2] = messageToSend[2]
table[3] = messageToSend[3]
currentlyCrafting.table[messageToSend[1]][messageToSend[2]] = messageToSend[3]
elseif message == "itemUpdate" or message == "logUpdate" then
table[1] = messageToSend
if message == "logUpdate" and currentlyCrafting.log ~= nil then
currentlyCrafting.log[#currentlyCrafting.log + 1] = messageToSend
elseif message == "itemUpdate" then
currentlyCrafting.nowCrafting = messageToSend
for row = 1, 3, 1 do
currentlyCrafting.table[row] = {}
for slot = 1, 3, 1 do
currentlyCrafting.table[row][slot] = 0
end
end
end
elseif type(message) == "boolean" then
currentlyCrafting = {}
end
cryptoNet.send(socket, {"craftingUpdate", table})
if message == "itemUpdate" or type(message) == "boolean" then
-- Update any clients subscribed to crafting updates
for k, v in pairs(craftingUpdateClients) do
cryptoNet.send(v, {"craftingUpdate", table})
cryptoNet.send(v, {"pushCurrentlyCrafting", currentlyCrafting})
cryptoNet.send(v, {"pushCraftingQueue", craftingQueue.dumpItems()})
end
end
end
-- Calculate number of each item needed.
local function calculateNumberOfItems(recipe, amount)
if type(amount) == "nil" then
amount = 1
end
if type(recipe) == "nil" then
return {}
end
local numNeeded = {}
for row = 1, #recipe do
for slot = 1, #recipe[row], 1 do
for itemSlot = 1, #recipe[row][slot], 1 do
if recipe[row][slot][itemSlot] ~= "none" and recipe[row][slot][itemSlot] ~= "item:minecraft:air" then
local recipeItemName = recipe[row][slot][itemSlot]
-- print(dump(recipeName))
if type(recipeItemName) ~= "nil" and recipeItemName ~= "nil" then
if type(numNeeded[recipeItemName]) == "nil" then
numNeeded[recipeItemName] = amount
else
numNeeded[recipeItemName] = numNeeded[recipeItemName] + amount
end
end
end
end
end
end
debugLog("calculateNumberOfItems: " .. dump(numNeeded))
return numNeeded
end
-- Checks if crafting materials are in system
local function haveCraftingMaterials(tableOfRecipes, amount, socket)
if type(socket) == "nil" then
socket = storageServerSocket
end
debugLog("haveCraftingMaterials")
-- debugLog(tableOfRecipes)
debugLog("amount:" .. tostring(amount))
if type(amount) == "nil" then
amount = 1
end
-- log(tableOfRecipes)
local recipeIsCraftable = {}
-- print("Found " .. tostring(#tableOfRecipes) .. " recipes")
-- print(dump(tableOfRecipes))
local num = 1
for _, tab in pairs(tableOfRecipes) do
local recipe = tab.recipe
-- print(textutils.serialise(recipe))
-- log(textutils.serialise(recipe))
-- sleep(5)
local craftable = true
debugLog("haveCraftingMaterials: numNeeded")
local numNeeded = calculateNumberOfItems(recipe, amount)
debugLog(dump(numNeeded))
-- print(textutils.serialise(numNeeded))
craftable = true
for i = 1, #recipe, 1 do -- row
local row = recipe[i]
for k = 1, #row, 1 do -- slot
local slot = row[k]
local craftable2 = false
for j = 1, #slot, 1 do -- item
local item = slot[j]
debugLog("item: " .. item)
debugLog("numNeeded[item]: " .. tostring(numNeeded[item]))
if type(numNeeded[item]) == "nil" then
return {}
end
if item == "none" or item == "item:minecraft:air" then
craftable2 = true
else
local result
local number = 0
if string.find(item, "tag:") then
result, number = searchForTag(item, items, numNeeded[item])
else
result, number = search(item, items, numNeeded[item])
end
debugLog("found " .. tostring(number) .. " need " .. tostring(numNeeded[item]))
-- If item with exact amount is found, or there is more than what we need
if number >= numNeeded[item] then
-- if "number" is >0 that means the item was found in the system
craftable2 = true
else
print(tostring(item:match(".+:(.+)")) .. ": Need: " .. tostring(numNeeded[item]) ..
" Found: " .. tostring(number))
updateClient(socket, "logUpdate", tostring(item:match(".+:(.+)")) .. ": " ..
tostring(number) .. "/" .. tostring(numNeeded[item]))
end
end
end
if not craftable2 then
craftable = false
end
end
end
if craftable then
recipeIsCraftable[num] = tab
num = num + 1
end
end
-- print(tostring(#recipeIsCraftable) .. " recipes are craftable")
return recipeIsCraftable
end
-- unused, may remove
local function isTagCraftable(searchTerm, inputTable)
local stringSearch = string.match(searchTerm, 'tag:%w+:(.+)')
local itemsTmp = {}
-- print("searchTerm: " .. searchTerm)
if type(tags[stringSearch]) ~= "nil" then
-- check tags database
-- print("Checking tags database")
for i, k in pairs(tags[stringSearch]) do
itemsTmp[#itemsTmp + 1] = {}
itemsTmp[#itemsTmp]["name"] = k
end
else
itemsTmp = searchForItemWithTag(searchTerm, inputTable)
end
if type(itemsTmp) == nil then
return false
end
-- print(dump(items))
-- sleep(5)
-- check if tag has crafting recipe
local tab = {}
for i = 1, #recipes, 1 do
for k = 1, #itemsTmp, 1 do
if (recipes[i].name == itemsTmp[k].name) then
-- return recipes[i].name
tab[#tab + 1] = recipes[i].name
end
end
end
if not next(tab) then
return false
else
return true
end
end
local function isCraftable(searchTerm)
local tab = {}
local stringSearch = string.match(searchTerm, 'item:(.+)')
for i = 1, #recipes, 1 do
if (recipes[i].name == stringSearch) then
tab[#tab + 1] = recipes[i].name
end
end
if not next(tab) then
return false
else
return true
end
end
local function reloadServerDatabase()
cryptoNet.send(storageServerSocket, {"reloadStorageDatabase"})
end
-- Note: Large performance hit on larger systems
local function reloadStorageDatabase()
debugLog("Reloading database..")
-- storage = getStorage()
-- write("..")
-- items, storageUsed = getList(storage)
-- pingServer()
reloadServerDatabase()
-- cryptoNet.send(storageServerSocket, { "reloadStorageDatabase" })
-- pingServer()
-- getDatabaseFromServer()
debugLog("wait for itemsUpdated")
local event
repeat
event = os.pullEvent("itemsUpdated")
until event == "itemsUpdated"
-- write("done\n")
-- write("Writing Tags Database....")
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()
-- write("done\n")
-- print("Items loaded: " .. tostring(storageUsed))
-- print("Tags loaded: " .. tostring(tags.count))
-- print("Tagged Items loaded: " .. tostring(tags.countItems))
end
-- Returns the totals number of an item in turtle inventory
local function numInTurtle(itemName)
local count = 0
for i = 1, 16, 1 do
local slotDetail = turtle.getItemDetail(i)
if type(slotDetail) ~= "nil" then
if slotDetail.name == itemName then
count = count + slotDetail.count
end
end
end
return count
end