Commit 243ad3ab authored by Melledy's avatar Melledy
Browse files

Refactor accounts to not use a player uid

parent 880d1770
......@@ -52,7 +52,7 @@ public final class AccountCommand implements CommandHandler {
account.addPermission("*");
account.save(); // Save account to database.
CommandHandler.sendMessage(null, translate(sender, "commands.account.create", Integer.toString(account.getPlayerUid())));
CommandHandler.sendMessage(null, translate(sender, "commands.account.create", Integer.toString(account.getReservedPlayerUid())));
}
return;
case "delete":
......@@ -66,7 +66,7 @@ public final class AccountCommand implements CommandHandler {
// Get the player for the account.
// If that player is currently online, we kick them before proceeding with the deletion.
Player player = Grasscutter.getGameServer().getPlayerByUid(toDelete.getPlayerUid());
Player player = Grasscutter.getGameServer().getPlayerByAccountId(toDelete.getId());
if (player != null) {
player.getSession().close();
}
......
......@@ -15,7 +15,7 @@ public final class KickCommand implements CommandHandler {
public void execute(Player sender, Player targetPlayer, List<String> args) {
if (sender != null) {
CommandHandler.sendMessage(sender, translate(sender, "commands.kick.player_kick_player",
Integer.toString(sender.getAccount().getPlayerUid()), sender.getAccount().getUsername(),
Integer.toString(sender.getUid()), sender.getAccount().getUsername(),
Integer.toString(targetPlayer.getUid()), targetPlayer.getAccount().getUsername()));
} else {
CommandHandler.sendMessage(null, translate(sender, "commands.kick.server_kick_player", Integer.toString(targetPlayer.getUid()), targetPlayer.getAccount().getUsername()));
......
......@@ -44,7 +44,7 @@ public final class SendMailCommand implements CommandHandler {
}
case "all" -> mailBuilder = new MailBuilder(true, new Mail());
default -> {
if (DatabaseHelper.getPlayerById(Integer.parseInt(args.get(0))) != null) {
if (DatabaseHelper.getPlayerByUid(Integer.parseInt(args.get(0))) != null) {
mailBuilder = new MailBuilder(Integer.parseInt(args.get(0)), new Mail());
} else {
CommandHandler.sendMessage(sender, translate(sender, "commands.sendMail.user_not_exist", args.get(0)));
......
......@@ -8,6 +8,7 @@ import dev.morphia.query.FindOptions;
import dev.morphia.query.Sort;
import dev.morphia.query.experimental.filters.Filters;
import emu.grasscutter.GameConstants;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.game.Account;
import emu.grasscutter.game.avatar.Avatar;
import emu.grasscutter.game.friends.Friendship;
......@@ -49,7 +50,7 @@ public final class DatabaseHelper {
account.setId(Integer.toString(DatabaseManager.getNextId(account)));
if (reservedId > 0) {
account.setPlayerId(reservedId);
account.setReservedPlayerUid(reservedId);
}
DatabaseHelper.saveAccount(account);
......@@ -104,25 +105,28 @@ public final class DatabaseHelper {
// 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 ...
// Delete Mail.class data
DatabaseManager.getGameDatabase().getCollection("mail").deleteMany(eq("ownerUid", target.getPlayerUid()));
// Delete Avatar.class data
DatabaseManager.getGameDatabase().getCollection("avatars").deleteMany(eq("ownerId", target.getPlayerUid()));
// Delete GachaRecord.class data
DatabaseManager.getGameDatabase().getCollection("gachas").deleteMany(eq("ownerId", target.getPlayerUid()));
// Delete GameItem.class data
DatabaseManager.getGameDatabase().getCollection("items").deleteMany(eq("ownerId", target.getPlayerUid()));
// Delete GameMainQuest.class data
DatabaseManager.getGameDatabase().getCollection("quests").deleteMany(eq("ownerUid", target.getPlayerUid()));
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", target.getPlayerUid()));
DatabaseManager.getGameDatabase().getCollection("friendships").deleteMany(eq("friendId", target.getPlayerUid()));
DatabaseManager.getGameDatabase().getCollection("friendships").deleteMany(eq("ownerId", player.getUid()));
DatabaseManager.getGameDatabase().getCollection("friendships").deleteMany(eq("friendId", player.getUid()));
// Delete the player.
DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("id", target.getPlayerUid())).delete();
// Delete the player last.
DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("id", player.getUid())).delete();
}
// Finally, delete the account itself.
DatabaseManager.getGameDatastore().find(Account.class).filter(Filters.eq("id", target.getId())).delete();
......@@ -132,15 +136,19 @@ public final class DatabaseHelper {
return DatabaseManager.getGameDatastore().find(Player.class).stream().toList();
}
public static Player getPlayerById(int id) {
public static Player getPlayerByUid(int id) {
return DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("_id", id)).first();
}
public static boolean checkPlayerExists(int id) {
return DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("_id", id)).first() != null;
public static Player getPlayerByAccount(Account account) {
return DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("accountId", account.getId())).first();
}
public static boolean checkPlayerExists(int uid) {
return DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("_id", uid)).count() > 0;
}
public static synchronized Player createPlayer(Player character, int reservedId) {
public static synchronized Player generatePlayerUid(Player character, int reservedId) {
// Check if reserved id
int id;
if (reservedId > 0 && !checkPlayerExists(reservedId)) {
......
......@@ -21,7 +21,7 @@ public class Account {
private String username;
private String password; // Unused for now
@AlsoLoad("playerUid") private int playerId;
private int reservedPlayerId;
private String email;
private String token;
......@@ -67,12 +67,12 @@ public class Account {
this.token = token;
}
public int getPlayerUid() {
return this.playerId;
public int getReservedPlayerUid() {
return this.reservedPlayerId;
}
public void setPlayerId(int playerId) {
this.playerId = playerId;
public void setReservedPlayerUid(int playerId) {
this.reservedPlayerId = playerId;
}
public String getEmail() {
......
......@@ -50,6 +50,7 @@ import emu.grasscutter.server.event.player.PlayerJoinEvent;
import emu.grasscutter.server.event.player.PlayerQuitEvent;
import emu.grasscutter.server.game.GameServer;
import emu.grasscutter.server.game.GameSession;
import emu.grasscutter.server.game.GameSession.SessionState;
import emu.grasscutter.server.packet.send.*;
import emu.grasscutter.utils.DateHelper;
import emu.grasscutter.utils.Position;
......@@ -247,7 +248,6 @@ public class Player {
public void setAccount(Account account) {
this.account = account;
this.account.setPlayerId(getUid());
}
public GameSession getSession() {
......@@ -1017,8 +1017,8 @@ public class Player {
}
}
} else {
List<Integer> showAvatarList = DatabaseHelper.getPlayerById(id).getShowAvatarList();
AvatarStorage avatars = DatabaseHelper.getPlayerById(id).getAvatars();
List<Integer> showAvatarList = DatabaseHelper.getPlayerByUid(id).getShowAvatarList();
AvatarStorage avatars = DatabaseHelper.getPlayerByUid(id).getAvatars();
avatars.loadFromDatabase();
if (showAvatarList != null) {
for (int avatarId : showAvatarList) {
......@@ -1058,7 +1058,7 @@ public class Player {
player = this;
shouldRecalc = false;
} else {
player = DatabaseHelper.getPlayerById(id);
player = DatabaseHelper.getPlayerByUid(id);
player.getAvatars().loadFromDatabase();
player.getInventory().loadFromDatabase();
shouldRecalc = true;
......@@ -1177,7 +1177,8 @@ public class Player {
DatabaseHelper.savePlayer(this);
}
public void onLogin() {
// Called from tokenrsp
public void loadFromDatabase() {
// Make sure these exist
if (this.getTeamManager() == null) {
this.teamManager = new TeamManager(this);
......@@ -1205,6 +1206,14 @@ public class Player {
this.getMailHandler().loadFromDatabase();
this.getQuestManager().loadFromDatabase();
// Add to gameserver (Always handle last)
if (getSession().isActive()) {
getServer().registerPlayer(this);
getProfile().setPlayer(this); // Set online
}
}
public void onLogin() {
// Quest - Commented out because a problem is caused if you log out while this quest is active
/*
if (getQuestManager().getMainQuestById(351) == null) {
......@@ -1224,12 +1233,6 @@ public class Player {
World world = new World(this);
world.addPlayer(this);
// Add to gameserver
if (getSession().isActive()) {
getServer().registerPlayer(this);
getProfile().setPlayer(this); // Set online
}
// Multiplayer setting
this.setProperty(PlayerProperty.PROP_PLAYER_MP_SETTING_TYPE, this.getMpSetting().getNumber());
this.setProperty(PlayerProperty.PROP_IS_MP_MODE_AVAILABLE, 1);
......@@ -1256,6 +1259,9 @@ public class Player {
// First notify packets sent
this.setHasSentAvatarDataNotify(true);
// Set session state
session.setState(SessionState.ACTIVE);
// Call join event.
PlayerJoinEvent event = new PlayerJoinEvent(this); event.call();
if(event.isCanceled()) // If event is not cancelled, continue.
......
......@@ -118,6 +118,7 @@ public final class GameServer extends KcpServer {
public ChatManagerHandler getChatManager() {
return chatManager;
}
public void setChatManager(ChatManagerHandler chatManager) {
this.chatManager = chatManager;
}
......@@ -189,12 +190,17 @@ public final class GameServer extends KcpServer {
// Check database if character isnt here
if (player == null) {
player = DatabaseHelper.getPlayerById(id);
player = DatabaseHelper.getPlayerByUid(id);
}
return player;
}
public Player getPlayerByAccountId(String accountId) {
Optional<Player> playerOpt = getPlayers().values().stream().filter(player -> player.getAccount().getId().equals(accountId)).findFirst();
return playerOpt.orElse(null);
}
public SocialDetail.Builder getSocialDetailByUid(int id) {
// Get from online players
Player player = this.getPlayerByUid(id, true);
......
......@@ -52,7 +52,7 @@ public final class GachaHandler implements Router {
response.status(403).send("Requested account was not found");
return;
}
Player player = Grasscutter.getGameServer().getPlayerByUid(account.getPlayerUid());
Player player = Grasscutter.getGameServer().getPlayerByAccountId(account.getId());
if (player == null) {
response.status(403).send("No player associated with requested account");
return;
......@@ -88,7 +88,7 @@ public final class GachaHandler implements Router {
response.status(403).send("Requested account was not found");
return;
}
Player player = Grasscutter.getGameServer().getPlayerByUid(account.getPlayerUid());
Player player = Grasscutter.getGameServer().getPlayerByAccountId(account.getId());
if (player == null) {
response.status(403).send("No player associated with requested account");
return;
......
package emu.grasscutter.server.packet.recv;
import static emu.grasscutter.Configuration.ACCOUNT;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.net.packet.Opcodes;
import emu.grasscutter.net.packet.PacketOpcodes;
import emu.grasscutter.net.proto.GetPlayerTokenReqOuterClass.GetPlayerTokenReq;
import emu.grasscutter.net.packet.PacketHandler;
import emu.grasscutter.server.event.game.PlayerCreationEvent;
import emu.grasscutter.server.game.GameSession;
import emu.grasscutter.server.game.GameSession.SessionState;
import emu.grasscutter.server.packet.send.PacketGetPlayerTokenRsp;
......@@ -15,6 +20,12 @@ public class HandlerGetPlayerTokenReq extends PacketHandler {
@Override
public void handle(GameSession session, byte[] header, byte[] payload) throws Exception {
// Max players limit
if (ACCOUNT.maxPlayer > -1 && Grasscutter.getGameServer().getPlayers().size() >= ACCOUNT.maxPlayer) {
session.close();
return;
}
GetPlayerTokenReq req = GetPlayerTokenReq.parseFrom(payload);
// Authenticate
......@@ -30,27 +41,35 @@ public class HandlerGetPlayerTokenReq extends PacketHandler {
// Set account
session.setAccount(account);
session.setUseSecretKey(true);
session.setState(SessionState.WAITING_FOR_LOGIN);
// Has character
boolean doesPlayerExist = false;
if (account.getPlayerUid() > 0) {
// Set flag for player existing
doesPlayerExist = DatabaseHelper.checkPlayerExists(account.getPlayerUid());
}
// Get player
Player player = DatabaseHelper.getPlayerByAccount(account);
// Set reserve player id if account doesnt exist
if (!doesPlayerExist) {
int id = DatabaseHelper.getNextPlayerId(session.getAccount().getPlayerUid());
if (id != session.getAccount().getPlayerUid()) {
session.getAccount().setPlayerId(id);
session.getAccount().save();
}
if (player == null) {
int nextPlayerUid = DatabaseHelper.getNextPlayerId(session.getAccount().getReservedPlayerUid());
// Call creation event.
PlayerCreationEvent event = new PlayerCreationEvent(session, Player.class); event.call();
// Create player instance from event.
player = event.getPlayerClass().getDeclaredConstructor(GameSession.class).newInstance(session);
// Save to db
DatabaseHelper.generatePlayerUid(player, nextPlayerUid);
}
// Set player object for session
session.setPlayer(player);
// Load player from database
player.loadFromDatabase();
// Set session state
session.setUseSecretKey(true);
session.setState(SessionState.WAITING_FOR_LOGIN);
// Send packet
session.send(new PacketGetPlayerTokenRsp(session, doesPlayerExist));
session.send(new PacketGetPlayerTokenRsp(session));
}
}
......@@ -22,11 +22,7 @@ public class HandlerPlayerLoginReq extends PacketHandler {
public void handle(GameSession session, byte[] header, byte[] payload) throws Exception {
// Check
if (session.getAccount() == null) {
return;
}
// Max players limit
if (ACCOUNT.maxPlayer > -1 && Grasscutter.getGameServer().getPlayers().size() >= ACCOUNT.maxPlayer) {
session.close();
return;
}
......@@ -35,23 +31,21 @@ public class HandlerPlayerLoginReq extends PacketHandler {
// Authenticate session
if (!req.getToken().equals(session.getAccount().getToken())) {
session.close();
return;
}
// Load character from db
Player player = DatabaseHelper.getPlayerById(session.getAccount().getPlayerUid());
Player player = session.getPlayer();
if (player == null) {
// Send packets
// Show opening cutscene if player has no avatars
if (player.getAvatars().getAvatarCount() == 0) {
// Pick character
session.setState(SessionState.PICKING_CHARACTER);
session.send(new BasePacket(PacketOpcodes.DoSetPlayerBornDataNotify));
} else {
// Set character
session.setPlayer(player);
// Login done
session.getPlayer().onLogin();
session.setState(SessionState.ACTIVE);
}
// Final packet to tell client logging in is done
......
......@@ -46,20 +46,8 @@ public class HandlerSetPlayerBornDataReq extends PacketHandler {
return;
}
String nickname = req.getNickName();
if (nickname == null) {
nickname = "Traveler";
}
// Call creation event.
PlayerCreationEvent event = new PlayerCreationEvent(session, Player.class); event.call();
// Create player instance from event.
Player player = event.getPlayerClass().getDeclaredConstructor(GameSession.class).newInstance(session);
player.setNickname(nickname);
try {
// Save to db
DatabaseHelper.createPlayer(player, session.getAccount().getPlayerUid());
// Get player object
Player player = session.getPlayer();
// Create avatar
if (player.getAvatars().getAvatarCount() == 0) {
......@@ -71,18 +59,12 @@ public class HandlerSetPlayerBornDataReq extends PacketHandler {
player.setHeadImage(avatarId);
player.getTeamManager().getCurrentSinglePlayerTeamInfo().getAvatars().add(mainCharacter.getAvatarId());
player.save(); // TODO save player team in different object
} else {
return;
}
// Save account
session.getAccount().setPlayerId(player.getUid());
session.getAccount().save();
// Set character
session.setPlayer(player);
// Login done
session.getPlayer().onLogin();
session.setState(SessionState.ACTIVE);
// Born resp packet
session.send(new BasePacket(PacketOpcodes.SetPlayerBornDataRsp));
......@@ -97,9 +79,5 @@ public class HandlerSetPlayerBornDataReq extends PacketHandler {
mailBuilder.mail.itemList.addAll(Arrays.asList(welcomeMail.items));
mailBuilder.mail.importance = 1;
player.sendMail(mailBuilder.mail);
} catch (Exception e) {
Grasscutter.getLogger().error("Error creating player object: ", e);
session.close();
}
}
}
......@@ -10,16 +10,16 @@ import emu.grasscutter.utils.Crypto;
public class PacketGetPlayerTokenRsp extends BasePacket {
public PacketGetPlayerTokenRsp(GameSession session, boolean doesPlayerExist) {
public PacketGetPlayerTokenRsp(GameSession session) {
super(PacketOpcodes.GetPlayerTokenRsp, true);
this.setUseDispatchKey(true);
GetPlayerTokenRsp p = GetPlayerTokenRsp.newBuilder()
.setUid(session.getAccount().getPlayerUid())
.setUid(session.getPlayer().getUid())
.setToken(session.getAccount().getToken())
.setAccountType(1)
.setIsProficientPlayer(doesPlayerExist) // Not sure where this goes
.setIsProficientPlayer(session.getPlayer().getAvatars().getAvatarCount() > 0) // Not sure where this goes
.setSecretKeySeed(Crypto.ENCRYPT_SEED)
.setSecurityCmdBuffer(ByteString.copyFrom(Crypto.ENCRYPT_SEED_BUFFER))
.setPlatformType(3)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment