Merge unstable into development (#2173)

* Remove more scene synchronized

* Fix worktop options not appearing

* Format code [skip actions]

* Fix delay with server tasks

* Format code [skip actions]

* Fully fix fairy clock (#2146)

* Fix scene transition

* fully fix fairy clock

* Re-add call to `Player#updatePlayerGameTime`

* Format code [skip actions]

* Initialize the script loader in `ResourceLoader#loadAll`

* Fix region removal checking

* Format code [skip actions]

* Use Lombok's `EqualsAndHashCode` for comparing scene regions

* Format code [skip actions]

* Move 'invalid gather object' to `trace`

* Add more information to the 'unknown condition handler' message

* Move invalid ability action to trace

* Make `KcpTunnel` public

* Validate the NPC being talked to

* Format code [skip actions]

* NPCs are not spawned server side; change logic to handle it

* Format code [skip actions]

* unload scene when there are no players (#2147)

* unload scene when there are no players

* Update src/main/java/emu/grasscutter/game/world/Scene.java

Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>

---------

Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>

* Check if a command should be copied or HTTP should be used

* Lint Code [skip actions]

* Fix character names rendering incorrectly

* Add basic troubleshooting command

* Implement handbook teleporting

also a few formatting changes and sort data by logical sense

* Fix listener `ConcurrentModificationException` issue

* Add color change to `Join the Community!`

* Lint Code [skip actions]

* Make clickable buttons appear clickable

* Remove 'Mechanicus' entities from the list of entities

* Format code [skip actions]

* Fix going back returning a blank screen

* Implement entity spawning

* Add setting level to entity card

* Add support for 'plain text' mode

* Make descriptions of objects scrollable

* Lint Code [skip actions]

* Format code [skip actions]

* Change the way existing hooks work

* Format code [skip actions]

* Upgrade Javalin to 5.5.0 & Fix project warnings

* Upgrade logging libraries

* Fix gacha mappings static file issue

* Add temporary backwards compatability for `ServerHelper`

* Format code [skip actions]

* Remove artifact signatures from VCS

* Fix forge queue data protocol definition

* Run `spotlessApply`

* Format code [skip actions]

* Download data required for building artifacts

* Add call for Facebook logins

* Add the wiki page as a submodule

* Format code [skip actions]

* Update translation (#2150)

* Update translation

* Update translation

* Separate the dispatch and game servers (pt. 1)

gacha is still broken, handbook still needs to be done

* Format code [skip actions]

* Separate the dispatch and game servers (pt. 2)

this commit fixes the gacha page

* Add description for '/troubleshoot'

* Set default avatar talent level to 10

* Separate the dispatch and game servers (pt. 3)

implement handbook across servers!

* Format code [skip actions]

* Update GitHub Actions to use 'download-file' over 'wget'

* Gm handbook lmao (#2149)

* Fix font issue

* Fix avatars

* Fix text overflow in commands

* Fix virtualized lists and items page 😭😭

* magix why 💀

* use hover style in all minicards

* button

* remove console.log

* lint

* Add icons

* magix asked

* Fix overflow padding issue

* Fix achievement text overflow

* remove icons from repo

* Change command icon

* Add the wiki page as a submodule

* total magix moment

* fix text overflow in commands

* Fix discord button

* Make text scale on Minicard

* import icons and font from another source

* Add hover effects to siebar buttons

* move font and readme to submodule repo

* Make data folder a submodule

* import icons and font from data submodule

* Update README.md

* total magix moment

* magix moment v2

* submodule change

* Import `.webp` files

* Resize `HomeButton`

* Fix 'Copy Command' reappearing after changing pages

---------

Co-authored-by: KingRainbow44 <kobedo11@gmail.com>

* Lint Code [skip actions]

* Download data for the build, not for the lint

* format imports

this is really just to see if build handbook works kek

* Implement proper handbook authentication (pt. 1)

* Implement proper handbook authentication (pt. 2)

* Format code [skip actions]

* Add quest data dumping for the handbook

* Change colors to fit _something suitable_

* Format code [skip actions]

* Fix force pushing to branches after linting

* Fix logic of `SetPlayerPropReq`

* Move more group loading to `trace`

* Add handbook IP authentication in hybrid mode

* Fix player level up not displaying on the client properly

* Format code [skip actions]

* Fix game time locking

* Format code [skip actions]

* Update player properties

* Format code [skip actions]

* Move `warn`s for groups to `debug`

* Fix player pausing

* Move more logs to `trace`

* Use `removeItemById` for deleting items via quests

* Clean up logger more

* Pause in-game time when the world is paused

* Format code [skip actions]

* More player property documentation

* Multi-threaded resource loading

* Format code [skip actions]

* Add quest widgets

* Add quests page (basic impl.)

* Add/fix colors

also fix tailwind

* Remove banned packets

client modifications already perform the job of blocking malicious packets from being executed, no point in having this if self-windy is wanted

* Re-add `BeginCameraSceneLookNotify`

* Fix being unable to attack (#2157)

* Add `PlayerOpenChestEvent`

* Add methods to get players from the server

* Add static methods to register an event handler

* Add `PlayerEnterDungeonEvent`

* Remove legacy documentation from `PlayerMoveEvent`

* Add `PlayerChatEvent`

* Add defaults to `Position`

* Clean up `.utils`

* Revert `Multi-threaded resource loading`

* Fix changing target UID when talking to the server

* Lint Code [skip actions]

* Format code [skip actions]

* fix NPC talk triggering main quest in 46101 (#2158)

Make it so that only talks where the param matches the talkId are checked.

* Format code [skip actions]

* Partially fix Chasing Shadows (#2159)

* Partially fix Chasing Shadows

* Go ahead and move it before the return before Magix tells me to.

* Format code [skip actions]

* Bring back period lol (#2160)

* Disable SNI for the HTTPS server

* Add `EntityCreationEvent`

* Add initial startup message

this is so the server appears like its preparing to start

* Format code [skip actions]

* Enable debug mode for plugin loggers if enabled for the primary logger

* Add documentation about `WorldAreaConfigData`

* Make more fields in excels accessible

* Remove deprecated fields from `GetShopRsp`

* Run `spotlessApply` on definitions

* Add `PlayerEnterAreaEvent`

* Optimize event calls

* Fix event invokes

* Format code [skip actions]

* Remove manual autofinish for main quests. (#2162)

* Add world areas to the textmap cache

* Format code [skip actions]

* Don't overdefine variables in extended classes (#2163)

* Add dumper for world areas

* Format code [skip actions]

* instantiate personalLineList (#2165)

* Fix protocol definitions

thank you Nazrin! (+ hiro for raw definitions)

* Fix the background color leaking from the character widget

* Change HTML spacing to 2 spaces

* Implement hiding widgets

* Change scrollbar to a vibrant color

* Add _some_ scaling to the home buttons and its text

* Build the handbook with Gradle

* Fix the 'finer details' with the handbook UI

* Lint Code [skip actions]

* Fix target destination for the Gradle-built handbook

* Implement fetching a player across servers & Add a chainable JsonObject

useful for plugins! might be used in grasscutter eventually

* Fix GitHub actions

* Fix event calling & canceling

* Run `spotlessApply`

* Rename fields (might be wrong)

* Add/update all/more protocol definitions

* Add/update all/more protocol definitions

* Remove outdated packet

* Fix protocol definitions

* Format code [skip actions]

* Implement some lua variables for less console spam (#2172)

* Implement some lua variables for less console spam

* Add GetHostQuestState

This fixes some chapter 3 stuff.

* Format code [skip actions]

* Fix merge import

* Format code [skip actions]

* Fully fix fairy clock for real this time (#2167)

* Fully fix fairy clock For real this time

* Make it so relogging keeps the time lock state.

* Refactor out questLockTime

* Per Hartie, the client packet needs to be changed too

* Update src/main/java/emu/grasscutter/game/world/World.java

Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>

* Update src/main/java/emu/grasscutter/server/packet/recv/HandlerClientLockGameTimeNotify.java

* Remove all code not needed to get clock working

---------

Co-authored-by: Magix <27646710+KingRainbow44@users.noreply.github.com>

* Implement a proper ability system (#2166)

* Apply fix `21dec2fe`

* Apply fix `89d01d5f`

* Apply fix `d900f154`

this one was already implemented; updated to use call from previous commit

* Ability changing commit

TODO: change info to debug

* Remove use of deprecated methods/fields

* Temp commit v2
(Adding LoseHP and some fixes)

* Oopsie

* Probably fix monster battle

* Fix issue with reflecting into fields

* Fix some things

* Fix ability names for 3.6 resources

* Improve logging

---------

Co-authored-by: StartForKiller <jesussanz2003@gmail.com>

* Format code [skip actions]

* Add system for sending messages between servers

* Format some code

* Remove protocol definitions from Spotless

* Default debug to false; enable with `-debug`

* Implement completely useless global value copying

* HACK: Return the avatar which holds the weapon when the weapon is referred to by ID

* Add properties to `AbilityModifier`

* Change the way HTML is served after authentication

* Use thread executors to speed up the database loading process

* Format code [skip actions]

* Add system for setting handbook address and port

* Lint Code [skip actions]

* Format code [skip actions]

* Fix game-related data not saving

* Format code [skip actions]

* Fix handbook server details

* Lint Code [skip actions]

* Format code [skip actions]

* Use the headers provided by a context to get the IP address

should acknowledge #1975

* Format code [skip actions]

* Move more logs to `trace`

* Format code [skip actions]

* more trace

* Fix something and implement weapon entities

* Format code [skip actions]

* Fix `EntityWeapon`

* Remove deprecated API & Fix resource checking

* Fix unnecessary warning for first-time setup

* Implement handbook request limiting

* Format code [skip actions]

* Fix new avatar weapons being null

* Format code [skip actions]

* Fix issue with 35303 being un-completable & Try to fix fulfilled quest conditions being met

* Load activity config on server startup

* Require plugins to specify an API version and match with the server

* Add default open state ignore list

* Format code [skip actions]

* Quick fix for questing, needs more investigation
This would make the questing work again

* Remove existing hack for 35303

* Fix ignored open states from being set

* Format code [skip actions]

* fix the stupidest bug ive ever seen

* Optimize player kicking on server close

* Format code [skip actions]

* Re-add hack to fix 35303

* Update GitHub actions

* Format code [skip actions]

* Potentially fix issues with regions

* Download additional handbook data

* Revert "Potentially fix issues with regions"

This reverts commit 84e3823695.

---------

Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: scooterboo <lewasite@yahoo.com>
Co-authored-by: Tesutarin <105267106+Tesutarin@users.noreply.github.com>
Co-authored-by: Scald <104459145+Arikatsu@users.noreply.github.com>
Co-authored-by: StartForKiller <jesussanz2003@gmail.com>
This commit is contained in:
Magix
2023-05-31 20:48:16 -07:00
committed by GitHub
parent f46fd372d2
commit 9e5b57a043
3839 changed files with 1841548 additions and 37533 deletions

View File

@@ -5,19 +5,18 @@ import dev.morphia.annotations.Id;
@Entity(value = "counters", useDiscriminator = false)
public class DatabaseCounter {
@Id
private String id;
private int count;
public DatabaseCounter() {}
public DatabaseCounter(String id) {
this.id = id;
this.count = 10000;
}
public int getNextId() {
int id = ++count;
return id;
}
@Id private String id;
private int count;
public DatabaseCounter() {}
public DatabaseCounter(String id) {
this.id = id;
this.count = 10000;
}
public int getNextId() {
int id = ++count;
return id;
}
}

View File

@@ -1,9 +1,6 @@
package emu.grasscutter.database;
import java.util.List;
import java.util.stream.Stream;
import com.mongodb.client.result.DeleteResult;
import static com.mongodb.client.model.Filters.eq;
import dev.morphia.query.FindOptions;
import dev.morphia.query.Sort;
@@ -23,10 +20,73 @@ import emu.grasscutter.game.inventory.GameItem;
import emu.grasscutter.game.mail.Mail;
import emu.grasscutter.game.player.Player;
import emu.grasscutter.game.quest.GameMainQuest;
import static com.mongodb.client.model.Filters.eq;
import emu.grasscutter.game.world.SceneGroupInstance;
import emu.grasscutter.utils.objects.Returnable;
import io.netty.util.concurrent.FastThreadLocalThread;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Stream;
public final class DatabaseHelper {
private static final ExecutorService eventExecutor =
new ThreadPoolExecutor(
6,
6,
60,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(),
FastThreadLocalThread::new,
new ThreadPoolExecutor.AbortPolicy());
/**
* Saves an object on the account datastore.
*
* @param object The object to save.
*/
public static void saveAccountAsync(Object object) {
DatabaseHelper.eventExecutor.submit(() -> DatabaseManager.getAccountDatastore().save(object));
}
/**
* Saves an object on the game datastore.
*
* @param object The object to save.
*/
public static void saveGameAsync(Object object) {
DatabaseHelper.eventExecutor.submit(() -> DatabaseManager.getGameDatastore().save(object));
}
/**
* Runs a runnable on the event executor. Should be limited to database-related operations.
*
* @param runnable The runnable to run.
*/
public static void asyncOperation(Runnable runnable) {
DatabaseHelper.eventExecutor.submit(runnable);
}
/**
* Fetches an object asynchronously.
*
* @param task The task to run.
* @return The future.
*/
public static <T> CompletableFuture<T> fetchAsync(Returnable<T> task) {
var future = new CompletableFuture<T>();
// Run the task on the event executor.
DatabaseHelper.eventExecutor.submit(
() -> {
try {
future.complete(task.invoke());
} catch (Exception e) {
future.completeExceptionally(e);
}
});
return future;
}
public static Account createAccount(String username) {
return createAccountWithUid(username, 0);
}
@@ -55,6 +115,7 @@ public final class DatabaseHelper {
}
// Account
@SuppressWarnings("deprecation")
Account account = new Account();
account.setUsername(username);
account.setId(Integer.toString(DatabaseManager.getNextId(account)));
@@ -85,43 +146,69 @@ public final class DatabaseHelper {
}
public static void saveAccount(Account account) {
DatabaseManager.getAccountDatastore().save(account);
DatabaseHelper.saveAccountAsync(account);
}
public static Account getAccountByName(String username) {
return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("username", username)).first();
return DatabaseManager.getAccountDatastore()
.find(Account.class)
.filter(Filters.eq("username", username))
.first();
}
public static Account getAccountByToken(String token) {
if (token == null) return null;
return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("token", token)).first();
return DatabaseManager.getAccountDatastore()
.find(Account.class)
.filter(Filters.eq("token", token))
.first();
}
public static Account getAccountBySessionKey(String sessionKey) {
if (sessionKey == null) return null;
return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("sessionKey", sessionKey)).first();
return DatabaseManager.getAccountDatastore()
.find(Account.class)
.filter(Filters.eq("sessionKey", sessionKey))
.first();
}
public static Account getAccountById(String uid) {
return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("_id", uid)).first();
return DatabaseManager.getAccountDatastore()
.find(Account.class)
.filter(Filters.eq("_id", uid))
.first();
}
public static Account getAccountByPlayerId(int playerId) {
return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("reservedPlayerId", playerId)).first();
return DatabaseManager.getAccountDatastore()
.find(Account.class)
.filter(Filters.eq("reservedPlayerId", playerId))
.first();
}
public static boolean checkIfAccountExists(String name) {
return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("username", name)).count() > 0;
return DatabaseManager.getAccountDatastore()
.find(Account.class)
.filter(Filters.eq("username", name))
.count()
> 0;
}
public static boolean checkIfAccountExists(int reservedUid) {
return DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("reservedPlayerId", reservedUid)).count() > 0;
return DatabaseManager.getAccountDatastore()
.find(Account.class)
.filter(Filters.eq("reservedPlayerId", reservedUid))
.count()
> 0;
}
public static synchronized 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 ...
// 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 ...
Player player = Grasscutter.getGameServer().getPlayerByAccountId(target.getId());
@@ -133,28 +220,46 @@ public final class DatabaseHelper {
if (player == null) return;
}
int uid = player.getUid();
// Delete data from collections
DatabaseManager.getGameDatabase().getCollection("achievements").deleteMany(eq("uid", uid));
DatabaseManager.getGameDatabase().getCollection("activities").deleteMany(eq("uid", uid));
DatabaseManager.getGameDatabase().getCollection("homes").deleteMany(eq("ownerUid", uid));
DatabaseManager.getGameDatabase().getCollection("mail").deleteMany(eq("ownerUid", uid));
DatabaseManager.getGameDatabase().getCollection("avatars").deleteMany(eq("ownerId", uid));
DatabaseManager.getGameDatabase().getCollection("gachas").deleteMany(eq("ownerId", uid));
DatabaseManager.getGameDatabase().getCollection("items").deleteMany(eq("ownerId", uid));
DatabaseManager.getGameDatabase().getCollection("quests").deleteMany(eq("ownerUid", uid));
DatabaseManager.getGameDatabase().getCollection("battlepass").deleteMany(eq("ownerUid", uid));
// 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", uid));
DatabaseManager.getGameDatabase().getCollection("friendships").deleteMany(eq("friendId", uid));
DatabaseHelper.asyncOperation(
() -> {
// Delete data from collections
DatabaseManager.getGameDatabase()
.getCollection("achievements")
.deleteMany(eq("uid", uid));
DatabaseManager.getGameDatabase().getCollection("activities").deleteMany(eq("uid", uid));
DatabaseManager.getGameDatabase().getCollection("homes").deleteMany(eq("ownerUid", uid));
DatabaseManager.getGameDatabase().getCollection("mail").deleteMany(eq("ownerUid", uid));
DatabaseManager.getGameDatabase().getCollection("avatars").deleteMany(eq("ownerId", uid));
DatabaseManager.getGameDatabase().getCollection("gachas").deleteMany(eq("ownerId", uid));
DatabaseManager.getGameDatabase().getCollection("items").deleteMany(eq("ownerId", uid));
DatabaseManager.getGameDatabase().getCollection("quests").deleteMany(eq("ownerUid", uid));
DatabaseManager.getGameDatabase()
.getCollection("battlepass")
.deleteMany(eq("ownerUid", uid));
// Delete the player last.
DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("id", uid)).delete();
// 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", uid));
DatabaseManager.getGameDatabase()
.getCollection("friendships")
.deleteMany(eq("friendId", uid));
// Finally, delete the account itself.
DatabaseManager.getAccountDatastore().find(Account.class).filter(Filters.eq("id", target.getId())).delete();
// Delete the player last.
DatabaseManager.getGameDatastore()
.find(Player.class)
.filter(Filters.eq("id", uid))
.delete();
// Finally, delete the account itself.
DatabaseManager.getAccountDatastore()
.find(Account.class)
.filter(Filters.eq("id", target.getId()))
.delete();
});
}
public static <T> Stream<T> getByGameClass(Class<T> classType) {
@@ -167,23 +272,50 @@ public final class DatabaseHelper {
}
public static Player getPlayerByUid(int id) {
return DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("_id", id)).first();
return DatabaseManager.getGameDatastore()
.find(Player.class)
.filter(Filters.eq("_id", id))
.first();
}
@Deprecated
public static Player getPlayerByAccount(Account account) {
return DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("accountId", account.getId())).first();
return DatabaseManager.getGameDatastore()
.find(Player.class)
.filter(Filters.eq("accountId", account.getId()))
.first();
}
public static Player getPlayerByAccount(Account account, Class<? extends Player> playerClass) {
return DatabaseManager.getGameDatastore().find(playerClass).filter(Filters.eq("accountId", account.getId())).first();
return DatabaseManager.getGameDatastore()
.find(playerClass)
.filter(Filters.eq("accountId", account.getId()))
.first();
}
/**
* Use {@link DatabaseHelper#getPlayerByAccount(Account, Class)} for creating a real player. This
* method is used for fetching the player's data.
*
* @param accountId The account's ID.
* @return The player.
*/
public static Player getPlayerByAccount(String accountId) {
return DatabaseManager.getGameDatastore()
.find(Player.class)
.filter(Filters.eq("accountId", accountId))
.first();
}
public static boolean checkIfPlayerExists(int uid) {
return DatabaseManager.getGameDatastore().find(Player.class).filter(Filters.eq("_id", uid)).count() > 0;
return DatabaseManager.getGameDatastore()
.find(Player.class)
.filter(Filters.eq("_id", uid))
.count()
> 0;
}
public static synchronized Player generatePlayerUid(Player character, int reservedId) {
public static synchronized void generatePlayerUid(Player character, int reservedId) {
// Check if reserved id
int id;
if (reservedId > 0 && !checkIfPlayerExists(reservedId)) {
@@ -192,13 +324,12 @@ public final class DatabaseHelper {
} else {
do {
id = DatabaseManager.getNextId(character);
}
while (checkIfPlayerExists(id));
} while (checkIfPlayerExists(id));
character.setUid(id);
}
// Save to database
DatabaseManager.getGameDatastore().save(character);
return character;
DatabaseHelper.saveGameAsync(character);
}
public static synchronized int getNextPlayerId(int reservedId) {
@@ -209,73 +340,104 @@ public final class DatabaseHelper {
} else {
do {
id = DatabaseManager.getNextId(Player.class);
}
while (checkIfPlayerExists(id));
} while (checkIfPlayerExists(id));
}
return id;
}
public static void savePlayer(Player character) {
DatabaseManager.getGameDatastore().save(character);
DatabaseHelper.saveGameAsync(character);
}
public static void saveAvatar(Avatar avatar) {
DatabaseManager.getGameDatastore().save(avatar);
DatabaseHelper.saveGameAsync(avatar);
}
/**
* Fetches all avatars of a player.
*
* @param player The player.
* @return The list of avatars.
*/
public static List<Avatar> getAvatars(Player player) {
return DatabaseManager.getGameDatastore().find(Avatar.class).filter(Filters.eq("ownerId", player.getUid())).stream().toList();
return DatabaseManager.getGameDatastore()
.find(Avatar.class)
.filter(Filters.eq("ownerId", player.getUid()))
.stream()
.toList();
}
public static void saveItem(GameItem item) {
DatabaseManager.getGameDatastore().save(item);
DatabaseHelper.saveGameAsync(item);
}
public static boolean deleteItem(GameItem item) {
DeleteResult result = DatabaseManager.getGameDatastore().delete(item);
return result.wasAcknowledged();
public static void deleteItem(GameItem item) {
DatabaseHelper.asyncOperation(() -> DatabaseManager.getGameDatastore().delete(item));
}
/**
* Fetches all items of a player.
*
* @param player The player.
* @return The list of items.
*/
public static List<GameItem> getInventoryItems(Player player) {
return DatabaseManager.getGameDatastore().find(GameItem.class).filter(Filters.eq("ownerId", player.getUid())).stream().toList();
return DatabaseManager.getGameDatastore()
.find(GameItem.class)
.filter(Filters.eq("ownerId", player.getUid()))
.stream()
.toList();
}
public static List<Friendship> getFriends(Player player) {
return DatabaseManager.getGameDatastore().find(Friendship.class).filter(Filters.eq("ownerId", player.getUid())).stream().toList();
return DatabaseManager.getGameDatastore()
.find(Friendship.class)
.filter(Filters.eq("ownerId", player.getUid()))
.stream()
.toList();
}
public static List<Friendship> getReverseFriends(Player player) {
return DatabaseManager.getGameDatastore().find(Friendship.class).filter(Filters.eq("friendId", player.getUid())).stream().toList();
return DatabaseManager.getGameDatastore()
.find(Friendship.class)
.filter(Filters.eq("friendId", player.getUid()))
.stream()
.toList();
}
public static void saveFriendship(Friendship friendship) {
DatabaseManager.getGameDatastore().save(friendship);
DatabaseHelper.saveGameAsync(friendship);
}
public static void deleteFriendship(Friendship friendship) {
DatabaseManager.getGameDatastore().delete(friendship);
DatabaseHelper.asyncOperation(() -> DatabaseManager.getGameDatastore().delete(friendship));
}
public static Friendship getReverseFriendship(Friendship friendship) {
return DatabaseManager.getGameDatastore().find(Friendship.class).filter(Filters.and(
Filters.eq("ownerId", friendship.getFriendId()),
Filters.eq("friendId", friendship.getOwnerId())
)).first();
return DatabaseManager.getGameDatastore()
.find(Friendship.class)
.filter(
Filters.and(
Filters.eq("ownerId", friendship.getFriendId()),
Filters.eq("friendId", friendship.getOwnerId())))
.first();
}
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) {
return DatabaseManager.getGameDatastore().find(GachaRecord.class).filter(
Filters.eq("ownerId", ownerId),
Filters.eq("gachaType", gachaType)
).iterator(new FindOptions()
.sort(Sort.descending("transactionDate"))
.skip(pageSize * page)
.limit(pageSize)
).toList();
public static List<GachaRecord> getGachaRecords(
int ownerId, int page, int gachaType, int pageSize) {
return DatabaseManager.getGameDatastore()
.find(GachaRecord.class)
.filter(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) {
@@ -283,52 +445,67 @@ public final class DatabaseHelper {
}
public static long getGachaRecordsMaxPage(int ownerId, int page, int gachaType, int pageSize) {
long count = DatabaseManager.getGameDatastore().find(GachaRecord.class).filter(
Filters.eq("ownerId", ownerId),
Filters.eq("gachaType", gachaType)
).count();
return count / 10 + (count % 10 > 0 ? 1 : 0 );
long count =
DatabaseManager.getGameDatastore()
.find(GachaRecord.class)
.filter(Filters.eq("ownerId", ownerId), Filters.eq("gachaType", gachaType))
.count();
return count / 10 + (count % 10 > 0 ? 1 : 0);
}
public static void saveGachaRecord(GachaRecord gachaRecord) {
DatabaseManager.getGameDatastore().save(gachaRecord);
DatabaseHelper.saveGameAsync(gachaRecord);
}
public static List<Mail> getAllMail(Player player) {
return DatabaseManager.getGameDatastore().find(Mail.class).filter(Filters.eq("ownerUid", player.getUid())).stream().toList();
return DatabaseManager.getGameDatastore()
.find(Mail.class)
.filter(Filters.eq("ownerUid", player.getUid()))
.stream()
.toList();
}
public static void saveMail(Mail mail) {
DatabaseManager.getGameDatastore().save(mail);
DatabaseHelper.saveGameAsync(mail);
}
public static boolean deleteMail(Mail mail) {
DeleteResult result = DatabaseManager.getGameDatastore().delete(mail);
return result.wasAcknowledged();
public static void deleteMail(Mail mail) {
DatabaseHelper.asyncOperation(() -> DatabaseManager.getGameDatastore().delete(mail));
}
public static List<GameMainQuest> getAllQuests(Player player) {
return DatabaseManager.getGameDatastore().find(GameMainQuest.class).filter(Filters.eq("ownerUid", player.getUid())).stream().toList();
return DatabaseManager.getGameDatastore()
.find(GameMainQuest.class)
.filter(Filters.eq("ownerUid", player.getUid()))
.stream()
.toList();
}
public static void saveQuest(GameMainQuest quest) {
DatabaseManager.getGameDatastore().save(quest);
DatabaseHelper.saveGameAsync(quest);
}
public static boolean deleteQuest(GameMainQuest quest) {
return DatabaseManager.getGameDatastore().delete(quest).wasAcknowledged();
public static void deleteQuest(GameMainQuest quest) {
DatabaseHelper.asyncOperation(() -> DatabaseManager.getGameDatastore().delete(quest));
}
public static GameHome getHomeByUid(int id) {
return DatabaseManager.getGameDatastore().find(GameHome.class).filter(Filters.eq("ownerUid", id)).first();
return DatabaseManager.getGameDatastore()
.find(GameHome.class)
.filter(Filters.eq("ownerUid", id))
.first();
}
public static void saveHome(GameHome gameHome) {
DatabaseManager.getGameDatastore().save(gameHome);
DatabaseHelper.saveGameAsync(gameHome);
}
public static BattlePassManager loadBattlePass(Player player) {
BattlePassManager manager = DatabaseManager.getGameDatastore().find(BattlePassManager.class).filter(Filters.eq("ownerUid", player.getUid())).first();
BattlePassManager manager =
DatabaseManager.getGameDatastore()
.find(BattlePassManager.class)
.filter(Filters.eq("ownerUid", player.getUid()))
.first();
if (manager == null) {
manager = new BattlePassManager(player);
manager.save();
@@ -339,36 +516,50 @@ public final class DatabaseHelper {
}
public static void saveBattlePass(BattlePassManager manager) {
DatabaseManager.getGameDatastore().save(manager);
DatabaseHelper.saveGameAsync(manager);
}
public static PlayerActivityData getPlayerActivityData(int uid, int activityId) {
return DatabaseManager.getGameDatastore().find(PlayerActivityData.class)
.filter(Filters.and(Filters.eq("uid", uid),Filters.eq("activityId", activityId)))
.first();
return DatabaseManager.getGameDatastore()
.find(PlayerActivityData.class)
.filter(Filters.and(Filters.eq("uid", uid), Filters.eq("activityId", activityId)))
.first();
}
public static void savePlayerActivityData(PlayerActivityData playerActivityData) {
DatabaseManager.getGameDatastore().save(playerActivityData);
DatabaseHelper.saveGameAsync(playerActivityData);
}
public static MusicGameBeatmap getMusicGameBeatmap(long musicShareId) {
return DatabaseManager.getGameDatastore().find(MusicGameBeatmap.class)
.filter(Filters.eq("musicShareId", musicShareId))
.first();
return DatabaseManager.getGameDatastore()
.find(MusicGameBeatmap.class)
.filter(Filters.eq("musicShareId", musicShareId))
.first();
}
public static void saveMusicGameBeatmap(MusicGameBeatmap musicGameBeatmap) {
DatabaseManager.getGameDatastore().save(musicGameBeatmap);
DatabaseHelper.saveGameAsync(musicGameBeatmap);
}
public static Achievements getAchievementData(int uid) {
return DatabaseManager.getGameDatastore().find(Achievements.class)
.filter(Filters.and(Filters.eq("uid", uid)))
.first();
return DatabaseManager.getGameDatastore()
.find(Achievements.class)
.filter(Filters.and(Filters.eq("uid", uid)))
.first();
}
public static void saveAchievementData(Achievements achievements) {
DatabaseManager.getGameDatastore().save(achievements);
DatabaseHelper.saveGameAsync(achievements);
}
public static void saveGroupInstance(SceneGroupInstance instance) {
DatabaseHelper.saveGameAsync(instance);
}
public static SceneGroupInstance loadGroupInstance(int groupId, Player owner) {
return DatabaseManager.getGameDatastore()
.find(SceneGroupInstance.class)
.filter(Filters.and(Filters.eq("ownerUid", owner.getUid()), Filters.eq("groupId", groupId)))
.first();
}
}

View File

@@ -1,24 +1,21 @@
package emu.grasscutter.database;
import static emu.grasscutter.config.Configuration.*;
import static emu.grasscutter.config.Configuration.DATABASE;
import com.mongodb.MongoCommandException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import dev.morphia.Datastore;
import dev.morphia.Morphia;
import dev.morphia.annotations.Entity;
import dev.morphia.mapping.Mapper;
import dev.morphia.mapping.MapperOptions;
import dev.morphia.query.experimental.filters.Filters;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.Grasscutter.ServerRunMode;
import emu.grasscutter.game.Account;
import org.reflections.Reflections;
public final class DatabaseManager {
@@ -29,18 +26,13 @@ public final class DatabaseManager {
return gameDatastore;
}
public static MongoDatabase getGameDatabase() {
return getGameDatastore().getDatabase();
public static Datastore getAccountDatastore() {
if (Grasscutter.getRunMode() == ServerRunMode.HYBRID) return gameDatastore;
else return dispatchDatastore;
}
// Yes. I very dislike this method. However, this will be good for now.
// TODO: Add dispatch routes for player account management
public static Datastore getAccountDatastore() {
if (SERVER.runMode == ServerRunMode.GAME_ONLY) {
return dispatchDatastore;
} else {
return gameDatastore;
}
public static MongoDatabase getGameDatabase() {
return getGameDatastore().getDatabase();
}
public static void initialize() {
@@ -48,31 +40,34 @@ public final class DatabaseManager {
MongoClient gameMongoClient = MongoClients.create(DATABASE.game.connectionUri);
// Set mapper options.
MapperOptions mapperOptions = MapperOptions.builder()
.storeEmpties(true).storeNulls(false).build();
MapperOptions mapperOptions =
MapperOptions.builder().storeEmpties(true).storeNulls(false).build();
// Create data store.
gameDatastore = Morphia.createDatastore(gameMongoClient, DATABASE.game.collection, mapperOptions);
gameDatastore =
Morphia.createDatastore(gameMongoClient, DATABASE.game.collection, mapperOptions);
// Map classes.
Class<?>[] entities = new Reflections(Grasscutter.class.getPackageName())
.getTypesAnnotatedWith(Entity.class)
.stream()
.filter(cls -> {
Entity e = cls.getAnnotation(Entity.class);
return e != null && !e.value().equals(Mapper.IGNORED_FIELDNAME);
})
.toArray(Class<?>[]::new);
Class<?>[] entities =
new Reflections(Grasscutter.class.getPackageName())
.getTypesAnnotatedWith(Entity.class).stream()
.filter(
cls -> {
Entity e = cls.getAnnotation(Entity.class);
return e != null && !e.value().equals(Mapper.IGNORED_FIELDNAME);
})
.toArray(Class<?>[]::new);
gameDatastore.getMapper().map(entities);
// Ensure indexes for the game datastore
ensureIndexes(gameDatastore);
if (SERVER.runMode == ServerRunMode.GAME_ONLY) {
if (Grasscutter.getRunMode() != ServerRunMode.HYBRID) {
MongoClient dispatchMongoClient = MongoClients.create(DATABASE.server.connectionUri);
dispatchDatastore = Morphia.createDatastore(dispatchMongoClient, DATABASE.server.collection, mapperOptions);
dispatchDatastore =
Morphia.createDatastore(dispatchMongoClient, DATABASE.server.collection, mapperOptions);
dispatchDatastore.getMapper().map(new Class<?>[] {DatabaseCounter.class, Account.class});
// Ensure indexes for dispatch datastore
@@ -82,6 +77,7 @@ public final class DatabaseManager {
/**
* Ensures the database indexes exist and rebuilds them if there is an error with them
*
* @param datastore The datastore to ensure indexes on
*/
private static void ensureIndexes(Datastore datastore) {
@@ -103,14 +99,19 @@ public final class DatabaseManager {
}
public static synchronized int getNextId(Class<?> c) {
DatabaseCounter counter = getGameDatastore().find(DatabaseCounter.class).filter(Filters.eq("_id", c.getSimpleName())).first();
DatabaseCounter counter =
getGameDatastore()
.find(DatabaseCounter.class)
.filter(Filters.eq("_id", c.getSimpleName()))
.first();
if (counter == null) {
counter = new DatabaseCounter(c.getSimpleName());
}
try {
return counter.getNextId();
} finally {
getGameDatastore().save(counter);
DatabaseHelper.saveGameAsync(counter);
}
}