DatabaseHelper.java 11.4 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
3
4
package emu.grasscutter.database;

import java.util.List;

KingRainbow44's avatar
KingRainbow44 committed
5
import com.mongodb.client.result.DeleteResult;
6

7
8
import dev.morphia.query.FindOptions;
import dev.morphia.query.Sort;
KingRainbow44's avatar
KingRainbow44 committed
9
import dev.morphia.query.experimental.filters.Filters;
10
import emu.grasscutter.GameConstants;
11
import emu.grasscutter.Grasscutter;
Melledy's avatar
Melledy committed
12
import emu.grasscutter.game.Account;
13
import emu.grasscutter.game.avatar.Avatar;
14
import emu.grasscutter.game.battlepass.BattlePassManager;
Melledy's avatar
Melledy committed
15
import emu.grasscutter.game.friends.Friendship;
16
import emu.grasscutter.game.gacha.GachaRecord;
17
import emu.grasscutter.game.home.GameHome;
18
import emu.grasscutter.game.inventory.GameItem;
19
import emu.grasscutter.game.mail.Mail;
Melledy's avatar
Melledy committed
20
import emu.grasscutter.game.player.Player;
Melledy's avatar
Melledy committed
21
import emu.grasscutter.game.quest.GameMainQuest;
Melledy's avatar
Melledy committed
22

23
24
import static com.mongodb.client.model.Filters.eq;

KingRainbow44's avatar
KingRainbow44 committed
25
public final class DatabaseHelper {
Melledy's avatar
Melledy committed
26
	public static Account createAccount(String username) {
27
		return createAccountWithUid(username, 0);
Melledy's avatar
Melledy committed
28
	}
KingRainbow44's avatar
KingRainbow44 committed
29

30
	public static Account createAccountWithUid(String username, int reservedUid) {
Melledy's avatar
Melledy committed
31
		// Unique names only
32
		if (DatabaseHelper.checkIfAccountExists(username)) {
Melledy's avatar
Melledy committed
33
34
			return null;
		}
KingRainbow44's avatar
KingRainbow44 committed
35

Melledy's avatar
Melledy committed
36
		// Make sure there are no id collisions
37
		if (reservedUid > 0) {
Melledy's avatar
Melledy committed
38
			// Cannot make account with the same uid as the server console
39
			if (reservedUid == GameConstants.SERVER_CONSOLE_UID) {
Melledy's avatar
Melledy committed
40
41
				return null;
			}
42
43
			
			if (DatabaseHelper.checkIfAccountExists(reservedUid)) {
Melledy's avatar
Melledy committed
44
45
				return null;
			}
46
			
47
			// Make sure no existing player already has this id.
48
			if (DatabaseHelper.checkIfPlayerExists(reservedUid)) {
49
50
				return null;
			}
Melledy's avatar
Melledy committed
51
52
53
54
55
56
		}

		// Account
		Account account = new Account();
		account.setUsername(username);
		account.setId(Integer.toString(DatabaseManager.getNextId(account)));
KingRainbow44's avatar
KingRainbow44 committed
57

58
59
		if (reservedUid > 0) {
			account.setReservedPlayerUid(reservedUid);
KingRainbow44's avatar
KingRainbow44 committed
60
		}
Melledy's avatar
Melledy committed
61
62
63
64
65
66
67
68
69
70
71
72

		DatabaseHelper.saveAccount(account);
		return account;
	}

	@Deprecated
	public static Account createAccountWithPassword(String username, String password) {
		// Unique names only
		Account exists = DatabaseHelper.getAccountByName(username);
		if (exists != null) {
			return null;
		}
KingRainbow44's avatar
KingRainbow44 committed
73

Melledy's avatar
Melledy committed
74
75
76
77
78
		// Account
		Account account = new Account();
		account.setId(Integer.toString(DatabaseManager.getNextId(account)));
		account.setUsername(username);
		account.setPassword(password);
KingRainbow44's avatar
KingRainbow44 committed
79
		DatabaseHelper.saveAccount(account);
Melledy's avatar
Melledy committed
80
81
82
83
		return account;
	}

	public static void saveAccount(Account account) {
84
		DatabaseManager.getAccountDatastore().save(account);
Melledy's avatar
Melledy committed
85
	}
KingRainbow44's avatar
KingRainbow44 committed
86

Melledy's avatar
Melledy committed
87
	public static Account getAccountByName(String username) {
yuyuko's avatar
yuyuko committed
88
		return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("username", username)).first();
Melledy's avatar
Melledy committed
89
	}
KingRainbow44's avatar
KingRainbow44 committed
90

Melledy's avatar
Melledy committed
91
	public static Account getAccountByToken(String token) {
KingRainbow44's avatar
KingRainbow44 committed
92
		if(token == null) return null;
yuyuko's avatar
yuyuko committed
93
		return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("token", token)).first();
Melledy's avatar
Melledy committed
94
	}
KingRainbow44's avatar
KingRainbow44 committed
95

96
97
	public static Account getAccountBySessionKey(String sessionKey) {
		if(sessionKey == null) return null;
yuyuko's avatar
yuyuko committed
98
		return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("sessionKey", sessionKey)).first();
99
100
	}

Melledy's avatar
Melledy committed
101
	public static Account getAccountById(String uid) {
yuyuko's avatar
yuyuko committed
102
		return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("_id", uid)).first();
Melledy's avatar
Melledy committed
103
	}
KingRainbow44's avatar
KingRainbow44 committed
104

105
	public static Account getAccountByPlayerId(int playerId) {
yuyuko's avatar
yuyuko committed
106
		return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("reservedPlayerId", playerId)).first();
Melledy's avatar
Melledy committed
107
	}
108
109
	
	public static boolean checkIfAccountExists(String name) {
yuyuko's avatar
yuyuko committed
110
		return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("username", name)).count() > 0;
111
112
113
	}
	
	public static boolean checkIfAccountExists(int reservedUid) {
yuyuko's avatar
yuyuko committed
114
		return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("reservedPlayerId", reservedUid)).count() > 0;
115
	}
KingRainbow44's avatar
KingRainbow44 committed
116

117
118
119
120
	public static void deleteAccount(Account target) {
		// To delete an account, we need to also delete all the other documents in the database that reference the account.
		// This should optimally be wrapped inside a transaction, to make sure an error thrown mid-way does not leave the
		// database in an inconsistent state, but unfortunately Mongo only supports that when we have a replica set ...
121

122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
		Player player = Grasscutter.getGameServer().getPlayerByAccountId(target.getId());
		
        if (player != null) {
        	// Close session first
            player.getSession().close();
            
            // Delete data from collections
    		DatabaseManager.getGameDatabase().getCollection("mail").deleteMany(eq("ownerUid", player.getUid()));
    		DatabaseManager.getGameDatabase().getCollection("avatars").deleteMany(eq("ownerId", player.getUid()));
    		DatabaseManager.getGameDatabase().getCollection("gachas").deleteMany(eq("ownerId", player.getUid()));
    		DatabaseManager.getGameDatabase().getCollection("items").deleteMany(eq("ownerId", player.getUid()));
    		DatabaseManager.getGameDatabase().getCollection("quests").deleteMany(eq("ownerUid", player.getUid()));

    		// Delete friendships.
    		// Here, we need to make sure to not only delete the deleted account's friendships,
    		// but also all friendship entries for that account's friends.
    		DatabaseManager.getGameDatabase().getCollection("friendships").deleteMany(eq("ownerId", player.getUid()));
    		DatabaseManager.getGameDatabase().getCollection("friendships").deleteMany(eq("friendId", player.getUid()));

    		// Delete the player last.
    		DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("id", player.getUid())).delete();
        }
144
145

		// Finally, delete the account itself.
yuyuko's avatar
yuyuko committed
146
		DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("id", target.getId())).delete();
Melledy's avatar
Melledy committed
147
	}
KingRainbow44's avatar
KingRainbow44 committed
148

149
	public static List<Player> getAllPlayers() {
150
		return DatabaseManager.getGameDatastore().find(Player.class).stream().toList();
Benjamin Elsdon's avatar
Benjamin Elsdon committed
151
152
	}

153
	public static Player getPlayerByUid(int id) {
154
		return DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("_id", id)).first();
Melledy's avatar
Melledy committed
155
	}
156
157
158
159
160
	
	public static Player getPlayerByAccount(Account account) {
		return DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("accountId", account.getId())).first();
	}
	
161
	public static boolean checkIfPlayerExists(int uid) {
162
		return DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("_id", uid)).count() > 0;
Melledy's avatar
Melledy committed
163
	}
KingRainbow44's avatar
KingRainbow44 committed
164

165
	public static synchronized Player generatePlayerUid(Player character, int reservedId) {
Melledy's avatar
Melledy committed
166
		// Check if reserved id
KingRainbow44's avatar
KingRainbow44 committed
167
		int id;
168
		if (reservedId > 0 && !checkIfPlayerExists(reservedId)) {
Melledy's avatar
Melledy committed
169
			id = reservedId;
170
			character.setUid(id);
Melledy's avatar
Melledy committed
171
172
173
174
		} else {
			do {
				id = DatabaseManager.getNextId(character);
			}
175
			while (checkIfPlayerExists(id));
176
			character.setUid(id);
Melledy's avatar
Melledy committed
177
178
		}
		// Save to database
179
		DatabaseManager.getGameDatastore().save(character);
Melledy's avatar
Melledy committed
180
181
		return character;
	}
KingRainbow44's avatar
KingRainbow44 committed
182

Melledy's avatar
Melledy committed
183
184
	public static synchronized int getNextPlayerId(int reservedId) {
		// Check if reserved id
KingRainbow44's avatar
KingRainbow44 committed
185
		int id;
186
		if (reservedId > 0 && !checkIfPlayerExists(reservedId)) {
Melledy's avatar
Melledy committed
187
188
189
			id = reservedId;
		} else {
			do {
190
				id = DatabaseManager.getNextId(Player.class);
Melledy's avatar
Melledy committed
191
			}
192
			while (checkIfPlayerExists(id));
Melledy's avatar
Melledy committed
193
194
195
		}
		return id;
	}
KingRainbow44's avatar
KingRainbow44 committed
196

197
	public static void savePlayer(Player character) {
198
		DatabaseManager.getGameDatastore().save(character);
Melledy's avatar
Melledy committed
199
	}
KingRainbow44's avatar
KingRainbow44 committed
200

201
	public static void saveAvatar(Avatar avatar) {
202
		DatabaseManager.getGameDatastore().save(avatar);
Melledy's avatar
Melledy committed
203
	}
KingRainbow44's avatar
KingRainbow44 committed
204

205
	public static List<Avatar> getAvatars(Player player) {
206
		return DatabaseManager.getGameDatastore().find(Avatar.class).filter(Filters.eq("ownerId", player.getUid())).stream().toList();
Melledy's avatar
Melledy committed
207
	}
KingRainbow44's avatar
KingRainbow44 committed
208

209
	public static void saveItem(GameItem item) {
210
		DatabaseManager.getGameDatastore().save(item);
Melledy's avatar
Melledy committed
211
	}
KingRainbow44's avatar
KingRainbow44 committed
212

213
	public static boolean deleteItem(GameItem item) {
214
		DeleteResult result = DatabaseManager.getGameDatastore().delete(item);
Melledy's avatar
Melledy committed
215
216
		return result.wasAcknowledged();
	}
KingRainbow44's avatar
KingRainbow44 committed
217

218
	public static List<GameItem> getInventoryItems(Player player) {
219
		return DatabaseManager.getGameDatastore().find(GameItem.class).filter(Filters.eq("ownerId", player.getUid())).stream().toList();
Melledy's avatar
Melledy committed
220
	}
221
	
222
	public static List<Friendship> getFriends(Player player) {
223
		return DatabaseManager.getGameDatastore().find(Friendship.class).filter(Filters.eq("ownerId", player.getUid())).stream().toList();
Melledy's avatar
Melledy committed
224
	}
KingRainbow44's avatar
KingRainbow44 committed
225

226
	public static List<Friendship> getReverseFriends(Player player) {
227
		return DatabaseManager.getGameDatastore().find(Friendship.class).filter(Filters.eq("friendId", player.getUid())).stream().toList();
Melledy's avatar
Melledy committed
228
229
230
	}

	public static void saveFriendship(Friendship friendship) {
231
		DatabaseManager.getGameDatastore().save(friendship);
Melledy's avatar
Melledy committed
232
233
234
	}

	public static void deleteFriendship(Friendship friendship) {
235
		DatabaseManager.getGameDatastore().delete(friendship);
Melledy's avatar
Melledy committed
236
237
238
	}

	public static Friendship getReverseFriendship(Friendship friendship) {
239
		return DatabaseManager.getGameDatastore().find(Friendship.class).filter(Filters.and(
KingRainbow44's avatar
KingRainbow44 committed
240
241
242
				Filters.eq("ownerId", friendship.getFriendId()),
				Filters.eq("friendId", friendship.getOwnerId())
		)).first();
Melledy's avatar
Melledy committed
243
	}
memetrollsXD's avatar
memetrollsXD committed
244

245
246
247
248
249
	public static List<GachaRecord> getGachaRecords(int ownerId, int page, int gachaType){
		return getGachaRecords(ownerId, page, gachaType, 10);
	}

	public static List<GachaRecord> getGachaRecords(int ownerId, int page, int gachaType, int pageSize){
250
		return DatabaseManager.getGameDatastore().find(GachaRecord.class).filter(
251
252
253
254
255
256
257
258
259
260
261
262
263
264
			Filters.eq("ownerId", ownerId),
			Filters.eq("gachaType", gachaType)
		).iterator(new FindOptions()
				.sort(Sort.descending("transactionDate"))
				.skip(pageSize * page)
				.limit(pageSize)
		).toList();
	}

	public static long getGachaRecordsMaxPage(int ownerId, int page, int gachaType){
		return getGachaRecordsMaxPage(ownerId, page, gachaType, 10);
	}

	public static long getGachaRecordsMaxPage(int ownerId, int page, int gachaType, int pageSize){
265
		long count = DatabaseManager.getGameDatastore().find(GachaRecord.class).filter(
266
267
268
269
270
271
272
			Filters.eq("ownerId", ownerId),
			Filters.eq("gachaType", gachaType)
		).count();
		return count / 10 + (count % 10 > 0 ? 1 : 0 );
	}

	public static void saveGachaRecord(GachaRecord gachaRecord){
273
		DatabaseManager.getGameDatastore().save(gachaRecord);
274
	}
275
276
	
	public static List<Mail> getAllMail(Player player) {
277
		return DatabaseManager.getGameDatastore().find(Mail.class).filter(Filters.eq("ownerUid", player.getUid())).stream().toList();
278
279
280
	}
	
	public static void saveMail(Mail mail) {
281
		DatabaseManager.getGameDatastore().save(mail);
282
283
284
	}
	
	public static boolean deleteMail(Mail mail) {
285
		DeleteResult result = DatabaseManager.getGameDatastore().delete(mail);
286
287
		return result.wasAcknowledged();
	}
Melledy's avatar
Melledy committed
288
289
	
	public static List<GameMainQuest> getAllQuests(Player player) {
290
		return DatabaseManager.getGameDatastore().find(GameMainQuest.class).filter(Filters.eq("ownerUid", player.getUid())).stream().toList();
Melledy's avatar
Melledy committed
291
292
293
	}
	
	public static void saveQuest(GameMainQuest quest) {
294
		DatabaseManager.getGameDatastore().save(quest);
Melledy's avatar
Melledy committed
295
296
297
	}
	
	public static boolean deleteQuest(GameMainQuest quest) {
298
		return DatabaseManager.getGameDatastore().delete(quest).wasAcknowledged();
Melledy's avatar
Melledy committed
299
	}
300
	
301
302
303
	public static GameHome getHomeByUid(int id) {
		return DatabaseManager.getGameDatastore().find(GameHome.class).filter(Filters.eq("ownerUid", id)).first();
	}
304
	
305
306
307
	public static void saveHome(GameHome gameHome) {
		DatabaseManager.getGameDatastore().save(gameHome);
	}
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
	
	public static BattlePassManager loadBattlePass(Player player) {
		BattlePassManager manager = DatabaseManager.getGameDatastore().find(BattlePassManager.class).filter(Filters.eq("ownerUid", player.getUid())).first();
		if (manager == null) {
			manager = new BattlePassManager(player);
			manager.save();
		} else {
			manager.setPlayer(player);
		}
		return manager;
	}
	
	public static void saveBattlePass(BattlePassManager manager) {
		DatabaseManager.getGameDatastore().save(manager);
	}
Melledy's avatar
Melledy committed
323
}