summaryrefslogtreecommitdiff
path: root/src/data.lua
blob: 27ae5e3064838eb94cd2e9be4854e5f3fcf57848 (plain)
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

local storage = minetest.get_mod_storage()
local __player_data

-- Table Save Load Functions
function awards.save()
	storage:set_string("player_data", minetest.write_json(__player_data))
end

local function convert_data()
	minetest.log("warning", "Importing awards data from previous version")

	local old_players = __player_data
	__player_data = {}
	for name, data in pairs(old_players) do
		while name.name do
			name = name.name
		end
		data.name = name
		print("Converting data for " .. name)

		-- Just rename counted
		local counted = {
			chats  = "chat",
			deaths = "death",
			joins  = "join",
		}
		for from, to in pairs(counted) do
			data[to]   = data[from]
			data[from] = nil
		end

		data.death = {
			unknown = data.death,
			__total = data.death,
		}

		-- Convert item db to new format
		local counted_items = {
			count = "dig",
			place = "place",
			craft = "craft",
		}
		for from, to in pairs(counted_items) do
			local ret = {}

			local count = 0
			if data[from] then
				for modname, items in pairs(data[from]) do
					for itemname, value in pairs(items) do
						itemname = modname .. ":" .. itemname
						local key = minetest.registered_aliases[itemname] or itemname
						ret[key] = value
						count = count + value
					end
				end
			end

			ret.__total = count
			data[from] = nil
			data[to] = ret
		end

		__player_data[name] = data
	end
end

function awards.load()
	local old_save_path = minetest.get_worldpath().."/awards.txt"
	local file = io.open(old_save_path, "r")
	if file then
		local table = minetest.deserialize(file:read("*all"))
		if type(table) == "table" then
			__player_data = table
			convert_data()
		else
			__player_data = {}
		end
		file:close()
		os.rename(old_save_path, minetest.get_worldpath().."/awards.bk.txt")
		awards.save()
	else
		__player_data = minetest.parse_json(storage:get_string("player_data")) or {}
	end
end

function awards.player(name)
	assert(type(name) == "string")
	local data = __player_data[name] or {}
	__player_data[name] = data

	data.name     = data.name or name
	data.unlocked = data.unlocked or {}
	return data
end

function awards.player_or_nil(name)
	return __player_data[name]
end

function awards.enable(name)
	awards.player(name).disabled = nil
end

function awards.disable(name)
	awards.player(name).disabled = true
end

function awards.clear_player(name)
	__player_data[name] = {}
end