Repository navigation
Expand file tree
/
Copy pathstorageServer.lua
More file actions
1984 lines (1854 loc) · 79.7 KB
/
Copy pathstorageServer.lua
File metadata and controls
1984 lines (1854 loc) · 79.7 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() + (7 * os.getComputerID()))
local cryptoNetURL = "https://raw.githubusercontent.com/SiliconSloth/CryptoNet/master/cryptoNet.lua"
local clients = {}
local serverLAN, serverWireless
local items = {}
local detailDB = {}
local storageUsed = 0
local storageMaxSize = 0
local storageSize = 0
local storageFreeSlots = 0
local storageTotalSlots = 0
local storages
local monitors = {}
local mainCraftingServer
local craftingEnabled = false
local currentlyCrafting = {}
local craftingQueue = {}
local serverBootTime = os.epoch("utc") / 1000
local excludedChestLookup = {}
local freeSlotRefreshCounter = 0
local detailLookupCache = {}
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("exportChests", {
description = "The peripheral name of the export chest",
{"minecraft:chest_0"},
type = "table"
})
settings.define("importChests", {
description = "The peripheral name of the import chests",
default = {"minecraft:chest_2"},
type = "table"
})
settings.define("craftingChests", {
description = "The peripheral name of the crafting chests that are above the turtle(s)",
{"minecraft:chest_3"},
type = "table"
})
settings.define("serverName", {
description = "The hostname of this server",
"StorageServer" .. tostring(os.getComputerID()),
type = "string"
})
settings.define("requireLogin", {
description = "require a login for LAN clients",
default = "false",
type = "boolean"
})
-- Settings fails to load
if settings.load() == false then
print("No settings have been found! Default values will be used!")
settings.set("serverName", "StorageServer" .. tostring(os.getComputerID()))
settings.set("debug", false)
settings.set("requireLogin", false)
settings.set("exportChests", {"minecraft:chest_0"})
settings.set("importChests", {"minecraft:chest_2"})
settings.set("craftingChests", {"minecraft:chest_3"})
print("Stop the server and edit .settings file with correct settings")
settings.save()
sleep(5)
end
-- Table of all wired modems
--[[
local modems = {peripheral.find("modem", function(name, modem)
if modem.isWireless() then
return false
else
return true
end
end)}
]] --
-- CC: tweaked changed wired modems to peripheral_hub
local modems = peripheral.find("peripheral_hub")
local function rebuildExcludedChestLookup()
local lookup = {}
local exportChests = settings.get("exportChests") or {}
local importChests = settings.get("importChests") or {}
local craftingChests = settings.get("craftingChests") or {}
for _, chest in pairs(exportChests) do
lookup[chest] = true
end
for _, chest in pairs(importChests) do
lookup[chest] = true
end
for _, chest in pairs(craftingChests) do
lookup[chest] = true
end
excludedChestLookup = lookup
end
rebuildExcludedChestLookup()
if type(modems[1]) == "nil" then
local tmpTable = {}
tmpTable[1] = modems
modems = tmpTable
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
local function log(text)
local logFile = fs.open("logs/server.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
local function debugLog(text)
if settings.get("debug") then
local logFile = fs.open("logs/serverDebug.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
local function dumpItems()
for k, v in pairs(items) do
debugLog("k: " .. tostring(k) .. " v: " .. textutils.serialize(v))
end
end
local function getInputStorage()
local storage = {}
local peripherals = {}
local importChests = settings.get("importChests")
for _, modem in pairs(modems) do
-- local remote = modem.getNamesRemote()
-- peripherals[#peripherals + 1] = remote
-- for i in pairs(remote) do
for k, chest in pairs(importChests) do
-- if chest == remote[i] then
if modem.isPresentRemote(chest) then
-- storage[#storage + 1] = peripheral.wrap(remote[i])
storage[#storage + 1] = peripheral.wrap(chest)
end
-- end
end
-- end
end
-- print("getInputStorage: " .. dump(storage))
return storage
end
local function getExportChests()
local output = {}
local exportChests = settings.get("exportChests")
for i, chest in pairs(exportChests) do
output[#output + 1] = peripheral.wrap(chest)
end
return output
end
local function inExportChests(search)
local exportChests = settings.get("exportChests")
for _, chest in pairs(exportChests) do
if chest == search then
return true
end
end
return false
end
local function inImportChests(search)
local importChests = settings.get("importChests")
for _, chest in pairs(importChests) do
if chest == search then
return true
end
end
return false
end
local function inCraftingChests(search)
local importChests = settings.get("craftingChests")
for _, chest in pairs(importChests) do
if chest == search then
return true
end
end
return false
end
-- Returns list of storage peripherals excluding import and export chests
local function getStorage()
local time = os.epoch("utc") / 1000
local storage = {}
local wrap = peripheral.wrap
for _, modem in pairs(modems) do
local remote = modem.getNamesRemote()
for i = 1, #remote, 1 do
local chestName = remote[i]
if modem.hasTypeRemote(chestName, "inventory") and not excludedChestLookup[chestName] then
storage[#storage + 1] = wrap(chestName)
end
end
end
local speed = (os.epoch("utc") / 1000) - time
print("Getting storages took " .. tostring(("%.3g"):format(speed) .. " seconds"))
debugLog("getStorage took " .. tostring(speed) .. " seconds")
return storage
end
-- Use this to avoid costly peripheral lookups
local function reconstructDetails(itemName)
if type(detailDB[itemName]) ~= "nil" then
return detailDB[itemName]
end
return nil
end
-- Convert integer to a Roman numeral for enchantment display
local function intToRoman(num)
local romans = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV",
"XVI", "XVII", "XVIII", "XIX", "XX"}
return romans[num] or tostring(num)
end
local function titleCase(s)
local parts = {}
for part in string.gmatch(s, "[^_%s]+") do
parts[#parts + 1] = string.upper(string.sub(part, 1, 1)) .. string.sub(part, 2)
end
return table.concat(parts, " ")
end
local function formatEnchantmentDisplay(name, level)
local short = string.match(name, ":(.+)$") or name
short = titleCase(short)
return short .. " " .. intToRoman(level)
end
local function buildDetailsFromRS(item)
-- Try to reconstruct previously saved details first
local saved = reconstructDetails(item.name)
if saved then
return saved
end
local details = {}
details.name = item.name
details.displayName = item.displayName or item.name
details.nbt = item.nbt or item.fingerprint
details.itemGroups = item.itemGroups or {}
details.tags = item.tags or {}
details.maxCount = item.maxStackSize or item.maxCount
details.count = item.count or 0
details.damage = item.damage
details.maxDamage = item.maxDamage
-- Map components -> enchantments if present
details.enchantments = nil
if type(item.components) == "table" and type(item.components["minecraft:enchantments"]) == "table" then
local levels = item.components["minecraft:enchantments"].levels
if type(levels) == "table" then
details.enchantments = {}
for ename, lvl in pairs(levels) do
details.enchantments[#details.enchantments + 1] = {
level = lvl,
name = ename,
displayName = formatEnchantmentDisplay(ename, lvl)
}
end
end
end
return details
end
-- Mantain details lookup
local function addDetailsDB(item)
-- print("addTag for: " .. item.name)
-- Maintain number of details stored
local countDetails
if type(detailDB.count) ~= "number" then
countDetails = 0
else
countDetails = detailDB.count
end
-- Maintain item count
local countItems
if type(detailDB.countItems) ~= "number" then
countItems = 0
else
countItems = detailDB.countItems
end
-- Add them to details db if they dont exist
if type(detailDB[item.name]) == "nil" and type(item.details) ~= "nil" then
-- print("Found new item: " .. item.name)
-- print("Found new detail: " .. item.details.displayName)
detailDB[item.name] = item.details
countDetails = countDetails + 1
countItems = countItems + 1
end
detailDB.count = countDetails
detailDB.countItems = countItems
end
local function normalizeRSItems(list)
if type(list) ~= "table" then
return list
end
local out = {}
for k, v in pairs(list) do
if type(v) == "table" then
if v.details == nil then
local d = buildDetailsFromRS(v)
if d then
v.details = d
if v.nbt == nil and d.nbt ~= nil then
v.nbt = d.nbt
end
addDetailsDB({
name = v.name,
details = d
})
end
end
end
out[#out + 1] = v
end
return out
end
-- Check if item name is in tag db
local function inDetailsDB(itemName)
if type(detailDB) ~= "nil" then
if type(detailDB[itemName]) ~= "nil" then
return true
end
end
return false
end
local function getCachedItemDetails(chest, slot, itemName)
if type(itemName) == "nil" or itemName == "" then
return nil
end
local cachedState = detailLookupCache[itemName]
if cachedState == false then
return nil
end
local cachedDetails = detailDB[itemName]
if type(cachedDetails) ~= "nil" then
return cachedDetails
end
local details = chest.getItemDetail(slot)
if type(details) ~= "nil" then
detailLookupCache[itemName] = true
addDetailsDB({
name = itemName,
details = details
})
return details
end
detailLookupCache[itemName] = false
return nil
end
local function calcFreeSlots()
local freeSlots = 0
for _, chest in pairs(storages) do
local chestList = chest.list()
if chestList == nil then
print("chest.list() failed")
storages = getStorage()
return calcFreeSlots()
end
local numberOfSlots = 0
for _ in pairs(chestList) do
numberOfSlots = numberOfSlots + 1
end
freeSlots = freeSlots + (chest.size() - numberOfSlots)
end
return freeSlots
end
-- gets the contents of a table of chests
local function getList(storage)
local time = os.epoch("utc") / 1000
local list = {}
local itemCount = 0
local getName = peripheral.getName
local freeSlots = 0
local total = 0
for _, chest in pairs(storage) do
local name = getName(chest)
local chestList = chest.list()
local numberOfSlots = 0
local chestSize = chest.size()
total = total + chestSize
for slot, item in pairs(chestList) do
if type(item) == "table" then
item["slot"] = slot
item["chestName"] = name
numberOfSlots = numberOfSlots + 1
if item.details == nil and item.nbt == nil then
local details = getCachedItemDetails(chest, slot, item.name)
if type(details) ~= "nil" then
item["details"] = details
end
end
itemCount = itemCount + item.count
list[#list + 1] = item
end
end
freeSlots = freeSlots + (chestSize - numberOfSlots)
end
local speed = (os.epoch("utc") / 1000) - time
print("Getting chest contents took " .. tostring(("%.3g"):format(speed) .. " seconds"))
debugLog("getList took " .. tostring(speed) .. " seconds")
return list, itemCount, freeSlots, total
end
local function getUserList()
local filename = settings.get("serverName") .. "_users.tbl"
if fs.exists(filename) then
local file = fs.open(filename, "r")
local contents = file.readAll()
file.close()
local decoded = textutils.unserialize(contents)
local tab = {}
if type(decoded) ~= "nil" then
for k, v in pairs(decoded) do
local tmp = {}
tmp.username = k
tmp.permissionLevel = v[2]
tab[#tab + 1] = tmp
end
return tab
else
return nil
end
end
end
local function average(t)
local sum = 0
for _, v in pairs(t) do -- Get the sum of all numbers in t
sum = sum + v
end
return sum / #t
end
-- loops all chests, adding together the number of slots and storage size of each. Note: MASSIVE performance hit on larger systems
local function getStorageSize(storage)
-- use local var for performance
local workingStorage = storage
local floor = math.floor
local epoch = os.epoch
local setCursorPos = term.setCursorPos
local slots = 0
local total = 0
local free = 0
local totalSlots = 0
for i = 1, #workingStorage, 1 do
local size = workingStorage[i].size()
totalSlots = totalSlots + size
end
-- If the number of chests slots is unchanged from last db refresh, skip max storage calc
if totalSlots == storageSize then
return storageSize, storageMaxSize, storageFreeSlots, storageTotalSlots
end
if storageSize ~= 0 then
print("")
print("Storage change detected")
print("")
end
print("")
print("")
local x, y = term.getSize()
setCursorPos(1, y - 1)
write("Progress: of " .. tostring(#storage) .. " storages processed")
local time = epoch("utc") / 1000
local speedHistory = {}
-- for _, chest in pairs(workingStorage) do
for i = 1, #workingStorage, 1 do
setCursorPos(11, y - 1)
write(tostring(i))
local size = workingStorage[i].size()
slots = slots + size
local getItemLimit = workingStorage[i].getItemLimit
local getItemDetail = workingStorage[i].getItemDetail
local chestList = workingStorage[i].list()
for k = 1, size do
setCursorPos(1, y)
write("Processing slot: " .. tostring(k) .. "/" .. tostring(size))
-- getItemLimit is broken on cc-restitched
-- total = total + getItemLimit(k)
if type(chestList[slot]) ~= "nil" then
local slotItem = getItemDetail(k)
if type(slotItem) ~= "nil" then
total = total + slotItem.maxCount
else
total = total + 64
free = free + 1
end
else
total = total + 64
free = free + 1
end
end
local speed = (epoch("utc") / 1000) - time
speedHistory[#speedHistory + 1] = speed
setCursorPos(1, y - 2)
term.write(floor(speed * 1000) / 1000 .. " seconds per storage ETA: " ..
(floor((#storage - i) * average(speedHistory))) ..
" seconds left ")
time = epoch("utc") / 1000
end
return slots, total, free, totalSlots
end
local function printClients()
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
local count = 0
for _ in pairs(clients) do
count = count + 1
end
print("Clients: " .. tostring(count))
for i in pairs(clients) do
print(tostring(clients[i].username) .. ":" .. string.sub(tostring(clients[i].target), 1, 5) .. ":" ..
tostring(clients[i].sender))
end
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
end
local function pingClients(message)
-- log(textutils.serialise(clients))
for k, v in pairs(clients) do
cryptoNet.send(v, {message})
end
if mainCraftingServer ~= nil then
cryptoNet.send(mainCraftingServer, {message})
end
end
-- Note: Large performance hit on larger systems
local function reloadStorageDatabase(reason)
print("Reloading database..")
if reason ~= nil then
print("Reason: " .. reason)
debugLog("Reloading database due to: " .. reason)
end
local time = os.epoch("utc") / 1000
if peripheral.find("rs_bridge") == nil then
-- Refined Storage is not present, use the normal method to get the item list
storages = getStorage()
-- This part is slow
items, storageUsed, storageFreeSlots, storageTotalSlots = getList(storages)
-- log("storageFreeSlots:" .. tostring(storageFreeSlots) .. " storageTotalSlots:" .. tostring(storageTotalSlots))
local speed = (os.epoch("utc") / 1000) - time
-- print("Getting item list took " .. tostring(speed) .. " seconds")
debugLog("Getting item list took " .. tostring(speed) .. " seconds")
local timeWrittingdb = os.epoch("utc") / 1000
-- print("Writing storage database....")
-- if fs.exists("storage.db") then
-- fs.delete("storage.db")
-- end
local decoded = {}
decoded.detailDB = detailDB
decoded.storageMaxSize = storageMaxSize
decoded.storageSize = storageSize
decoded.storageFreeSlots = storageFreeSlots
decoded.storageTotalSlots = storageTotalSlots
-- local storageFile = fs.open("storage.db", "w")
-- storageFile.write(textutils.serialise(decoded, {
-- allow_repetitions = true
-- }))
-- storageFile.close()
-- local speedWrittingdb = (os.epoch("utc") / 1000) - timeWrittingdb
-- print("Writting storage database took " .. tostring(speedWrittingdb) .. " seconds")
-- debugLog("Writting storage database took " .. tostring(speedWrittingdb) .. " seconds")
else
-- Refined Storage is present, use it to get the item list
items = peripheral.find("rs_bridge").getItems()
-- Ensure each item has a `details` key expected by clients
items = normalizeRSItems(items)
-- Remove the duplicate tags table to avoid serialization issues
for i, item in ipairs(items) do
if item.details then
item.tags = nil
end
item.maxCount = item.maxStackSize
item.maxStackSize = nil
end
storageUsed = peripheral.find("rs_bridge").getUsedItemStorage()
storageTotalSlots = peripheral.find("rs_bridge").getTotalItemStorage()
storageFreeSlots = storageTotalSlots - storageUsed
storageMaxSize = storageTotalSlots
debugLog("storageUsed:" .. tostring(storageUsed) .. " storageTotalSlots:" .. tostring(storageTotalSlots) ..
" storageFreeSlots:" .. tostring(storageFreeSlots))
end
pingClients("databaseReload")
os.queueEvent("databaseReloaded")
print("Database reload complete")
speed = (os.epoch("utc") / 1000) - time
print("Database reload took " .. tostring(("%.3g"):format(speed) .. " seconds total"))
log("Database reload took " .. tostring(speed) .. " seconds total")
end
local function threadedStorageDatabaseReload(reason)
-- os.startThread(reloadStorageDatabase
reloadStorageDatabase(reason)
-- local event
-- repeat
-- event = os.pullEvent("databaseReloaded")
-- until event == "databaseReloaded"
end
-- Avoid costly database reload by patching database in memory
local function patchStorageDatabase(inputItem, count, chest, slot, reason)
if reason == nil then
reason = "unknown"
end
print("patchStorageDatabase called for " .. tostring(reason))
debugLog("patchStorageDatabase called for " .. tostring(reason))
if peripheral.find("rs_bridge") ~= nil then
-- The item to find and the new count
local targetName = inputItem.name
local newCount = count
-- Loop through the table to find and edit the count
for index, item in ipairs(items) do
if item.name == targetName then
item.count = item.count + newCount
print("Updated " .. item.displayName .. " count to #" .. item.count)
debugLog("Updated " .. item.displayName .. " count to #" .. item.count)
if item.count < 1 then
-- If there is 0 items, delete from list
table.remove(items, index)
end
pingClients("databaseReload")
return true
end
end
return false
end
if count == 0 or inputItem == nil or ((chest == nil or slot == nil) and peripheral.find("rs_bridge") == nil) then
return false
end
local itemName = inputItem.name
-- print("Patching database item:" .. itemName .. " by #" .. tostring(count) .. " chest:" .. chest .. " slot:" .. tostring(slot))
debugLog("Patching database item:" .. itemName .. " by #" .. tostring(count) .. " chest:" .. tostring(chest) ..
" slot:" .. tostring(slot))
local stringSearch
-- Strip out the item: from the front of the item name
if string.find(itemName, 'item:(.+)') then
stringSearch = string.match(itemName, 'item:(.+)')
else
stringSearch = itemName
end
if type(stringSearch) == "nil" then
stringSearch = itemName
end
local savedDetails = {}
for k, v in pairs(items) do
if v.name == stringSearch then
if v.chestName == chest then
if v.slot == slot then
if v.nbt == inputItem.nbt then
-- handler for techreborn storage_units
if (string.find(chest, "techreborn:") and string.find(tostring(chest), "storage_unit")) then
local slotDetails = peripheral.wrap(chest).getItemDetail(slot)
if slotDetails ~= nil then
items[k].count = slotDetails.count
else
items[k].count = 0
end
-- storageUsed = storageUsed + (slotDetails.count - count)
else
items[k].count = items[k].count + count
storageUsed = storageUsed + count
end
if items[k].count < 1 then
-- If there is 0 items, delete from list
table.remove(items, k)
end
pingClients("databaseReload")
return true
end
end
end
if not next(savedDetails) and v.details ~= nil and v.nbt == inputItem.nbt then
savedDetails = v.details
end
end
end
-- If we managed to capture details from other slots, create new entry in list
if next(savedDetails) then
local tmp = {}
tmp.count = count
tmp.slot = slot
tmp.details = savedDetails
tmp.name = itemName
tmp.chestName = chest
tmp.nbt = savedDetails.nbt
table.insert(items, tmp)
storageUsed = storageUsed + count
pingClients("databaseReload")
return true
else
-- if all else fails, reach out to chest to get details
if chest ~= nil and slot ~= nil then
print("chest: " .. tostring(chest) .. " slot: " .. tostring(slot))
debugLog("chest: " .. tostring(chest) .. " slot: " .. tostring(slot))
local chestP = peripheral.wrap(chest)
if chestP ~= nil then
local chestSize = chestP.size()
if chestSize ~= nil and slot <= chestSize then
local slotDetails = chestP.getItemDetail(slot)
if slotDetails ~= nil then
local tmp = {}
tmp.count = slotDetails.count
tmp.slot = slot
tmp.details = slotDetails
tmp.name = itemName
tmp.chestName = chest
tmp.nbt = slotDetails.nbt
table.insert(items, tmp)
storageUsed = storageUsed + count
pingClients("databaseReload")
return true
end
else
print("chestSize of " .. tostring(chestSize) .. " but tried to index slot " .. tostring(slot))
debugLog("chestSize of " .. tostring(chestSize) .. " but tried to index slot " .. tostring(slot))
end
end
end
end
-- Patching failed, fallback to full reload
print("Patching database failed, reloading full database")
reloadStorageDatabase(tostring(reason) .. ", patchStorageDatabase failed")
return false
end
local function search(string, InputTable)
local filteredTable = {}
local find = string.find
local lower = string.lower
for k, v in pairs(InputTable) do
if lower(v["name"]) == lower(string) then
filteredTable[#filteredTable + 1] = v
end
end
if filteredTable == {} then
return nil
else
return filteredTable
end
end
-- Looks for an item in a given table
local function searchForItem(item, InputTable)
local filteredTable = {}
-- for k, v in pairs(InputTable) do
for i = 1, #InputTable, 1 do
if (item["name"] == InputTable[i]["name"]) then
-- if the item has NBT, dont mix it with the same item that does not have an NBT
if (item["nbt"] ~= nil) and (InputTable[i]["nbt"] ~= nil) then
if item["nbt"] == InputTable[i]["nbt"] then
filteredTable[#filteredTable + 1] = InputTable[i]
end
else
filteredTable[#filteredTable + 1] = InputTable[i]
end
end
end
if not next(filteredTable) then
return nil
else
return filteredTable
end
end
local function cleanTable(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.chestName = v.chestName
tab.slot = v.slot
tab.nbt = v.nbt
-- 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
-- Finds next free space in system of an item
local function findFreeSpace(item, storage)
local localStorage = storage
local filteredTable = searchForItem(item, items)
local getName = peripheral.getName
local wrap = peripheral.wrap
local find = string.find
if filteredTable == nil then
-- debugLog("Item not found in system")
-- Item not found in system
-- Find first chest with a free slot
for k, chest in pairs(localStorage) do
if chest ~= nil then
local list = chest.list()
local size = chest.size()
-- skip full chests
if list ~= nil and #list < size then
local chestName = getName(chest)
-- print("checking chest #" .. tostring(k) .. " Name: " .. getName(chest) .. " slot1 is: " .. tostring(list[1]))
-- Do not use techreborn storage_units
if not (find(chestName, "techreborn:") and find(chestName, "storage_unit")) then
local index
-- workaround for storage drawers mod. slot 1 has the size of each slot but only slots 2..n can hold items so loop should start at 2
if find(chestName, "storagedrawers:") then
-- print("applying storage drawers mod workaround")
index = 2
else -- otherwise slots should start at 1
index = 1
end
-- Find a slot that has nothing
for i = index, size, 1 do
if list[i] == nil then
-- print("Found free slot at chest: " .. chestName .. " Slot: " .. tostring(i))
-- debugLog("Found free slot at chest: " .. chestName .. " Slot: " .. tostring(i))
-- local test = wrap(chestName).getItemDetail(i)
-- debugLog("slot info:" ..textutils.serialize(test))
return chestName, i
end
end
end
end
end
end
else
local clean = cleanTable(filteredTable)
debugLog("findFreeSpace filteredTable: " .. textutils.serialize(clean))
-- debugLog("Item was found in the system")
-- Item was found in the system
-- print("Item was found in the system")
local limit
for k, v in pairs(filteredTable) do
-- text = v["name"] .. " #" .. v["count"]
-- print(v["name"] .. " #" .. v["count"] .. " " .. v["chestName"] .. " " .. v["slot"])
-- workaround for storage drawers mod. slot 1 reports the true item limit, slots 2..n report 0
if limit == nil then
if find(v["chestName"], "storagedrawers:") then
-- getItemLimit is broken on cc-restitched
-- limit = wrap(v["chestName"]).getItemLimit(1)
local slotItem = wrap(v["chestName"]).getItemDetail(1)
if type(slotItem) ~= "nil" then
limit = slotItem.maxCount - slotItem.count
else
limit = 64
end
else
-- limit = wrap(v["chestName"]).getItemLimit(v["slot"])
-- workaround for getItemLimit being broken on cc-restitched as of ver 1.101.2
local slotItem = wrap(v["chestName"]).getItemDetail(v["slot"])
if type(slotItem) ~= "nil" then
limit = slotItem.maxCount - slotItem.count
else
limit = 64
end
end
end
if (find(v.chestName, "techreborn:") and find(v.chestName, "storage_unit")) then
debugLog("found techreborn: " .. v.chestName)
-- storage_units can only input from slot 1, if slot 1 is full then the storage unit is full
local slotItem = wrap(v["chestName"]).getItemDetail(1)
if slotItem == nil then
return v["chestName"], 1
end
limit = slotItem.maxCount - slotItem.count
if v["count"] <= limit and item.nbt == v.nbt then
return v["chestName"], 1
end
else
-- if the slot is not full, then it has free space
-- print("limit: " .. tostring(limit) .. " count: " .. tostring(v["count"]))
if v["count"] <= limit and item.nbt == v.nbt then
return v["chestName"], v["slot"]
end
end
end
-- Find first chest with a free slot
-- print("Find first chest with a free slot")