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
|
#include "StarPlayerStorage.hpp"
#include "StarFile.hpp"
#include "StarLogging.hpp"
#include "StarIterator.hpp"
#include "StarTime.hpp"
#include "StarConfiguration.hpp"
#include "StarPlayer.hpp"
#include "StarAssets.hpp"
#include "StarEntityFactory.hpp"
#include "StarRoot.hpp"
#include "StarText.hpp"
namespace Star {
PlayerStorage::PlayerStorage(String const& storageDir) {
m_storageDirectory = storageDir;
m_backupDirectory = File::relativeTo(m_storageDirectory, "backup");
if (!File::isDirectory(m_storageDirectory)) {
Logger::info("Creating player storage directory");
File::makeDirectory(m_storageDirectory);
return;
}
auto configuration = Root::singleton().configuration();
if (configuration->get("clearPlayerFiles").toBool()) {
Logger::info("Clearing all player files");
for (auto file : File::dirList(m_storageDirectory)) {
if (!file.second)
File::remove(File::relativeTo(m_storageDirectory, file.first));
}
} else {
auto versioningDatabase = Root::singleton().versioningDatabase();
auto entityFactory = Root::singleton().entityFactory();
for (auto file : File::dirList(m_storageDirectory)) {
if (file.second)
continue;
String filename = File::relativeTo(m_storageDirectory, file.first);
if (filename.endsWith(".player")) {
try {
auto json = VersionedJson::readFile(filename);
Uuid uuid(json.content.getString("uuid"));
if (m_playerFileNames.insert(uuid, file.first.rsplit('.', 1).at(0))) {
auto& playerCacheData = m_savedPlayersCache[uuid];
playerCacheData = entityFactory->loadVersionedJson(json, EntityType::Player);
} else {
Logger::warn("Duplicate player? Skipping player file {} because it has the same UUID as {}.player ({})", file.first, m_playerFileNames.getRight(uuid), uuid.hex());
}
} catch (std::exception const& e) {
Logger::error("Error loading player file, ignoring! {} : {}", filename, outputException(e, false));
}
}
}
// Remove all the player entries that are missing player data or fail to
// load.
auto it = makeSMutableMapIterator(m_savedPlayersCache);
while (it.hasNext()) {
auto& entry = it.next();
if (entry.second.isNull()) {
it.remove();
} else {
try {
auto entityFactory = Root::singleton().entityFactory();
auto player = as<Player>(entityFactory->diskLoadEntity(EntityType::Player, entry.second));
if (player->uuid() != entry.first)
throw PlayerException(strf("Uuid mismatch in loaded player with filename uuid '{}'", entry.first.hex()));
} catch (StarException const& e) {
auto& fileName = uuidFileName(entry.first);
String uuidHex = entry.first.hex();
if (uuidHex == fileName)
Logger::error("Failed to validate player with uuid {} : {}", uuidHex, outputException(e, true));
else
Logger::error("Failed to validate player with uuid {} ({}.player) : {}", uuidHex, fileName, outputException(e, true));
it.remove();
}
}
}
}
try {
String filename = File::relativeTo(m_storageDirectory, "metadata");
m_metadata = Json::parseJson(File::readFileString(filename)).toObject();
if (auto order = m_metadata.value("order")) {
for (auto const& jUuid : order.iterateArray()) {
auto entry = m_savedPlayersCache.find(Uuid(jUuid.toString()));
if (entry != m_savedPlayersCache.end())
m_savedPlayersCache.toBack(entry);
}
}
} catch (std::exception const& e) {
Logger::warn("Error loading player storage metadata file, resetting: {}", outputException(e, false));
}
}
PlayerStorage::~PlayerStorage() {
writeMetadata();
}
size_t PlayerStorage::playerCount() const {
RecursiveMutexLocker locker(m_mutex);
return m_savedPlayersCache.size();
}
Maybe<Uuid> PlayerStorage::playerUuidAt(size_t index) {
RecursiveMutexLocker locker(m_mutex);
if (index < m_savedPlayersCache.size())
return m_savedPlayersCache.keyAt(index);
else
return {};
}
Maybe<Uuid> PlayerStorage::playerUuidByName(String const& name, Maybe<Uuid> except) {
String cleanMatch = Text::stripEscapeCodes(name).toLower();
Maybe<Uuid> uuid;
RecursiveMutexLocker locker(m_mutex);
size_t longest = std::numeric_limits<size_t>::max();
for (auto& cache : m_savedPlayersCache) {
if (except && *except == cache.first)
continue;
else if (auto name = cache.second.optQueryString("identity.name")) {
auto cleanName = Text::stripEscapeCodes(*name).toLower();
auto len = cleanName.size();
if (len < longest && cleanName.utf8().rfind(cleanMatch.utf8()) == 0) {
longest = len;
uuid = cache.first;
}
}
}
return uuid;
}
List<Uuid> PlayerStorage::playerUuidListByName(String const& name, Maybe<Uuid> except) {
String cleanMatch = Text::stripEscapeCodes(name).toLower();
List<Uuid> list = {};
RecursiveMutexLocker locker(m_mutex);
for (auto& cache : m_savedPlayersCache) {
if (except && *except == cache.first)
continue;
else if (auto name = cache.second.optQueryString("identity.name")) {
auto cleanName = Text::stripEscapeCodes(*name).toLower();
if (cleanMatch == "" || cleanName.utf8().rfind(cleanMatch.utf8()) != NPos) {
list.append(cache.first);
}
}
}
return list;
}
Json PlayerStorage::savePlayer(PlayerPtr const& player) {
auto entityFactory = Root::singleton().entityFactory();
auto versioningDatabase = Root::singleton().versioningDatabase();
RecursiveMutexLocker locker(m_mutex);
auto uuid = player->uuid();
auto& playerCacheData = m_savedPlayersCache[uuid];
if (!m_playerFileNames.hasLeftValue(uuid))
m_playerFileNames.insert(uuid, uuid.hex());
auto newPlayerData = player->diskStore();
if (playerCacheData != newPlayerData) {
playerCacheData = newPlayerData;
VersionedJson versionedJson = entityFactory->storeVersionedJson(EntityType::Player, playerCacheData);
auto fileName = strf("{}.player", uuidFileName(uuid));
VersionedJson::writeFile(versionedJson, File::relativeTo(m_storageDirectory, fileName));
Logger::debug("Saved player {} to {}", Text::stripEscapeCodes(player->name()), fileName);
}
return newPlayerData;
}
Maybe<Json> PlayerStorage::maybeGetPlayerData(Uuid const& uuid) {
RecursiveMutexLocker locker(m_mutex);
if (auto cache = m_savedPlayersCache.ptr(uuid))
return *cache;
else
return {};
}
Json PlayerStorage::getPlayerData(Uuid const& uuid) {
auto data = maybeGetPlayerData(uuid);
if (!data)
throw PlayerException(strf("No such stored player with uuid '{}'", uuid.hex()));
else
return *data;
}
PlayerPtr PlayerStorage::loadPlayer(Uuid const& uuid) {
auto playerCacheData = getPlayerData(uuid);
auto entityFactory = Root::singleton().entityFactory();
try {
auto player = convert<Player>(entityFactory->diskLoadEntity(EntityType::Player, playerCacheData));
if (player->uuid() != uuid)
throw PlayerException(strf("Uuid mismatch in loaded player with filename uuid '{}'", uuid.hex()));
return player;
} catch (std::exception const& e) {
Logger::error("Error loading player file, ignoring! {}", outputException(e, false));
RecursiveMutexLocker locker(m_mutex);
m_savedPlayersCache.remove(uuid);
return {};
}
}
void PlayerStorage::deletePlayer(Uuid const& uuid) {
RecursiveMutexLocker locker(m_mutex);
if (!m_savedPlayersCache.contains(uuid))
throw PlayerException(strf("No such stored player with uuid '{}'", uuid.hex()));
m_savedPlayersCache.remove(uuid);
auto uuidHex = uuid.hex();
auto storagePrefix = File::relativeTo(m_storageDirectory, uuidHex);
auto backupPrefix = File::relativeTo(m_backupDirectory, uuidHex);
auto removeIfExists = [](String const& prefix, String const& suffix) {
if (File::exists(prefix + suffix)) {
File::remove(prefix + suffix);
}
};
removeIfExists(storagePrefix, ".player");
removeIfExists(storagePrefix, ".shipworld");
auto configuration = Root::singleton().configuration();
unsigned playerBackupFileCount = configuration->get("playerBackupFileCount").toUInt();
for (unsigned i = 1; i <= playerBackupFileCount; ++i) {
removeIfExists(backupPrefix, strf(".player.bak{}", i));
removeIfExists(backupPrefix, strf(".shipworld.bak{}", i));
}
}
WorldChunks PlayerStorage::loadShipData(Uuid const& uuid) {
RecursiveMutexLocker locker(m_mutex);
if (!m_savedPlayersCache.contains(uuid))
throw PlayerException(strf("No such stored player with uuid '{}'", uuid.hex()));
String filename = File::relativeTo(m_storageDirectory, strf("{}.shipworld", uuidFileName(uuid)));
try {
if (File::exists(filename))
return WorldStorage::getWorldChunksFromFile(filename);
} catch (StarException const& e) {
Logger::error("Failed to load shipworld file, removing {} : {}", filename, outputException(e, false));
File::remove(filename);
}
return {};
}
void PlayerStorage::applyShipUpdates(Uuid const& uuid, WorldChunks const& updates) {
RecursiveMutexLocker locker(m_mutex);
if (!m_savedPlayersCache.contains(uuid))
throw PlayerException(strf("No such stored player with uuid '{}'", uuid.hex()));
if (updates.empty())
return;
String filePath = File::relativeTo(m_storageDirectory, strf("{}.shipworld", uuidFileName(uuid)));
WorldStorage::applyWorldChunksUpdateToFile(filePath, updates);
}
void PlayerStorage::moveToFront(Uuid const& uuid) {
m_savedPlayersCache.toFront(uuid);
writeMetadata();
}
void PlayerStorage::backupCycle(Uuid const& uuid) {
RecursiveMutexLocker locker(m_mutex);
auto configuration = Root::singleton().configuration();
unsigned playerBackupFileCount = configuration->get("playerBackupFileCount").toUInt();
auto& fileName = uuidFileName(uuid);
auto path = [&](String const& dir, String const& extension) {
return File::relativeTo(dir, strf("{}.{}", fileName, extension));
};
if (!File::isDirectory(m_backupDirectory))
File::makeDirectory(m_backupDirectory);
File::backupFileInSequence(path(m_storageDirectory, "player"), path(m_backupDirectory, "player"), playerBackupFileCount, ".bak");
File::backupFileInSequence(path(m_storageDirectory, "shipworld"), path(m_backupDirectory, "shipworld"), playerBackupFileCount, ".bak");
File::backupFileInSequence(path(m_storageDirectory, "metadata"), path(m_backupDirectory, "metadata"), playerBackupFileCount, ".bak");
}
void PlayerStorage::setMetadata(String key, Json value) {
auto& val = m_metadata[std::move(key)];
if (val != value) {
val = std::move(value);
writeMetadata();
}
}
Json PlayerStorage::getMetadata(String const& key) {
return m_metadata.value(key);
}
String const& PlayerStorage::uuidFileName(Uuid const& uuid) {
if (auto fileName = m_playerFileNames.rightPtr(uuid))
return *fileName;
else {
m_playerFileNames.insert(uuid, uuid.hex());
return *m_playerFileNames.rightPtr(uuid);
}
}
void PlayerStorage::writeMetadata() {
JsonArray order;
for (auto const& p : m_savedPlayersCache)
order.append(p.first.hex());
m_metadata["order"] = std::move(order);
String filename = File::relativeTo(m_storageDirectory, "metadata");
File::overwriteFileWithRename(Json(m_metadata).printJson(0), filename);
}
}
|