DatabaseHelper.java 10.9 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;
Melledy's avatar
Melledy committed
14
import emu.grasscutter.game.friends.Friendship;
15
import emu.grasscutter.game.gacha.GachaRecord;
16
import emu.grasscutter.game.home.GameHome;
17
import emu.grasscutter.game.inventory.GameItem;
18
import emu.grasscutter.game.mail.Mail;
Melledy's avatar
Melledy committed
19
import emu.grasscutter.game.player.Player;
Melledy's avatar
Melledy committed
20
import emu.grasscutter.game.quest.GameMainQuest;
Melledy's avatar
Melledy committed
21

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

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

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

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

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

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

		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
72

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

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

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

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

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

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

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

116
117
118
119
	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 ...
120

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
		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();
        }
143
144

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

244
245
246
247
248
	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){
249
		return DatabaseManager.getGameDatastore().find(GachaRecord.class).filter(
250
251
252
253
254
255
256
257
258
259
260
261
262
263
			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){
264
		long count = DatabaseManager.getGameDatastore().find(GachaRecord.class).filter(
265
266
267
268
269
270
271
			Filters.eq("ownerId", ownerId),
			Filters.eq("gachaType", gachaType)
		).count();
		return count / 10 + (count % 10 > 0 ? 1 : 0 );
	}

	public static void saveGachaRecord(GachaRecord gachaRecord){
272
		DatabaseManager.getGameDatastore().save(gachaRecord);
273
	}
274
275
	
	public static List<Mail> getAllMail(Player player) {
276
		return DatabaseManager.getGameDatastore().find(Mail.class).filter(Filters.eq("ownerUid", player.getUid())).stream().toList();
277
278
279
	}
	
	public static void saveMail(Mail mail) {
280
		DatabaseManager.getGameDatastore().save(mail);
281
282
283
	}
	
	public static boolean deleteMail(Mail mail) {
284
		DeleteResult result = DatabaseManager.getGameDatastore().delete(mail);
285
286
		return result.wasAcknowledged();
	}
Melledy's avatar
Melledy committed
287
288
	
	public static List<GameMainQuest> getAllQuests(Player player) {
289
		return DatabaseManager.getGameDatastore().find(GameMainQuest.class).filter(Filters.eq("ownerUid", player.getUid())).stream().toList();
Melledy's avatar
Melledy committed
290
291
292
	}
	
	public static void saveQuest(GameMainQuest quest) {
293
		DatabaseManager.getGameDatastore().save(quest);
Melledy's avatar
Melledy committed
294
295
296
	}
	
	public static boolean deleteQuest(GameMainQuest quest) {
297
		return DatabaseManager.getGameDatastore().delete(quest).wasAcknowledged();
Melledy's avatar
Melledy committed
298
	}
299
300
301
302
303
304
	public static GameHome getHomeByUid(int id) {
		return DatabaseManager.getGameDatastore().find(GameHome.class).filter(Filters.eq("ownerUid", id)).first();
	}
	public static void saveHome(GameHome gameHome) {
		DatabaseManager.getGameDatastore().save(gameHome);
	}
Melledy's avatar
Melledy committed
305
}