Commit a8293102 authored by Melledy's avatar Melledy Committed by GitHub
Browse files

Merge branch 'development' into stable

parents 304b9cb8 ecf7a81a
......@@ -25,6 +25,16 @@ jobs:
with:
distribution: temurin
java-version: '17'
- name: Cache gradle files
uses: actions/cache@v2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
./.gradle/loom-cache
key: ${{ runner.os }}-gradle-${{ hashFiles('*.gradle', 'gradle.properties', '**/*.accesswidener') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Run Gradle
run: ./gradlew && ./gradlew jar
- name: Upload build
......
......@@ -17,7 +17,7 @@
*.nar
*.ear
*.zip
*.tar.gz
*.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
......@@ -52,20 +52,30 @@ tmp/
.vscode
# Grasscutter
resources/
logs/
plugins/
data/AbilityEmbryos.json
data/OpenConfig.json
/resources
/logs
/plugins
/data
/keys
/language
/languages
/src/generated
/*.jar
/*.sh
GM Handbook.txt
config.json
mitmdump.exe
*.jar
!lib/*.jar
mongod.exe
/src/generated/
/*.sh
language/
languages/
gacha-mapping.js
data/gacha_mappings.js
mappings.js
BuildConfig.java
# lombok
/.apt_generated/
# macOS
.DS_Store
data/hk4e/announcement/
......@@ -67,7 +67,7 @@ EN | [中文](README_zh-CN.md)
2. Set network proxy to `127.0.0.1:8080` or the proxy port you specified.
**you can also use `start.cmd` to start servers and proxy daemons automatically**
**you can also use `start.cmd` to start servers and proxy daemons automatically, but you have to set up JAVA_HOME enviroment**
### Building
......@@ -98,61 +98,11 @@ chmod +x gradlew
You can find the output jar in the root of the project folder.
## Commands
You might want to use this command (`java -jar grasscutter.jar -handbook`) in a cmd that is in the grasscutter folder. It will create a handbook file (GM Handbook.txt) where you can find the item IDs for stuff you want.
You may want to use this command (`java -jar grasscutter.jar -gachamap`) to generate a mapping file for the gacha record subsystem. The file will be generated to `GRASSCUTTER_RESOURCE/gcstatic` folder. Otherwise you may only see number IDs in the gacha record page.
There is a dummy user named "Server" in every player's friends list that you can message to use commands. Commands also work in other chat rooms, such as private/team chats. to run commands ingame, you need to add prefix `/` or `!` such as `/pos`
| Commands | Usage | Permission node | Availability | description | Alias |
| -------------- | ------------------------------------------------- | ------------------------- | ------------ | ------------------------------------------------------------ | ----------------------------------------------- |
| account | account <create\|delete> \<username> [UID] | | Server only | Creates an account with the specified username and the in-game UID for that account. The UID will be auto generated if not set. | |
| broadcast | broadcast \<message> | server.broadcast | Both side | Sends a message to all the players. | b |
| coop | coop \<playerId> \<target playerId> | server.coop | Both side | Forces someone to join the world of others. | |
| changescene | changescene \<scene id> | player.changescene | Client only | Switch scenes by scene ID. | scene |
| clear | clear <all\|wp\|art\|mat> [UID] | player.clearinv | Client only | Deletes all unequipped and unlocked level 0 artifacts(art)/weapons(wp)/material(all) or all, including 5-star rarity ones from your inventory. | clear |
| drop | drop <itemID\|itemName> [amount] | server.drop | Client only | Drops an item around you. | `d` `dropitem` |
| enterdungeon | enterdungeon \<dungeon id> | player.enterdungeon | Client only | Enter a dungeon by dungeon ID | |
| give | give [player] <itemId\|itemName> [amount] [level] [finement] | player.give | Both side | Gives item(s) to you or the specified player. (finement option only weapon.) | `g` `item` `giveitem` |
| givechar | givechar \<uid> \<avatarId> | player.givechar | Both side | Gives the player a specified character. | givec |
| giveart | giveart [player] \<artifactId> \<mainPropId> [\<appendPropId>[,\<times>]]... [level] | player.giveart | Both side | Gives the player a specified artifact. | gart |
| giveall | giveall [uid] [amount] | player.giveall | Both side | Gives all items. | givea |
| godmode | godmode [uid] | player.godmode | Client only | Prevents you from taking damage. | |
| heal | heal | player.heal | Client only | Heals all characters in your current team. | h |
| help | help [command] | | Both side | Sends the help message or shows information about a specified command. | |
| kick | kick \<player> | server.kick | Both side | Kicks the specified player from the server. (WIP) | k |
| killall | killall [playerUid] [sceneId] | server.killall | Both side | Kills all entities in the current scene or specified scene of the corresponding player. | |
| list | list | | Both side | Lists online players. | |
| permission | permission <add\|remove> \<UID> \<permission> | * | Both side | Grants or removes a permission for a user. | |
| position | position | | Client only | Sends your current coordinates. | pos |
| reload | reload | server.reload | Both side | Reloads the server config | |
| resetconst | resetconst [all] | player.resetconstellation | Client only | Resets the constellation level on your currently selected character, will need to relog after using the command to see any changes. | resetconstellation |
| restart | | | Both side | Restarts the current session | |
| say | say \<player> \<message> | server.sendmessage | Both side | Sends a message to a player as the server | `sendservmsg` `sendservermessage` `sendmessage` |
| setfetterlevel | setfetterlevel \<level> | player.setfetterlevel | Client only | Sets the friendship level for your currently selected character | setfetterlvl |
| setstats | setstats \<stat> \<value> | player.setstats | Client only | Sets a stat for your currently selected character | stats |
| setworldlevel | setworldlevel \<level> | player.setworldlevel | Client only | Sets your world level (Relog to see proper effects) | setworldlvl |
| spawn | spawn \<entityId> [amount] [level(monster only)] | server.spawn | Client only | Spawns some entities around you | |
| stop | stop | server.stop | Both side | Stops the server | |
| talent | talent \<talentID> \<value> | player.settalent | Client only | Sets talent level for your currently selected character | |
| teleport | teleport [@playerUid] \<x> \<y> \<z> [sceneId] | player.teleport | Both side | Change the player's position. | tp |
| tpall | | player.tpall | Client only | Teleports all players in your world to your position | |
| weather | weather \<weatherID> \<climateID> | player.weather | Client only | Changes the weather | w |
### Bonus
- Teleporting
- When you want to teleport somewhere, use the in-game marking function on the map.
- Mark a point on the map using the fish hook marking (the last one.)
- (Optional) rename the map marker to a number to override the default Y coordinate (height, default 300.)
- Confirm and close the map.
- You will see your character falling from a very high destination, exact location that you marked.
### Commands have moved to the [wiki](https://github.com/Grasscutters/Grasscutter/wiki/Commands)!
# Quick Troubleshooting
* If compiling wasn't successful, please check your JDK installation (JDK 17 and validated JDK's bin PATH variable)
* My client doesn't connect, doesn't login, 4206, etc... - Your proxy daemon setup is most likely *the issue*, if you are using Fiddler, make sure it running on another port other than 8888
* Startup sequence: Mongodb > Grasscutter > Proxy daemon (mitmdump, fiddler, etc.) > Game
* My client doesn't connect, doesn't login, 4206, etc... - Mostly your proxy daemon setup is *the issue*, if using
Fiddler make sure it running on another port except 8888
* Startup sequence: MongoDB > Grasscutter > Proxy daemon (mitmdump, fiddler, etc.) > Game
......@@ -123,11 +123,13 @@ chmod +x gradlew
| godmode | godmode [uid] | player.godmode | 仅客户端 | 保护你不受到任何伤害(依然会被击退) | |
| heal | heal | player.heal | 仅客户端 | 治疗队伍中所有角色 | h |
| help | help [命令] | | 均可使用 | 显示帮助或展示指定命令的帮助 | |
| join | join [多个角色id] | player.join | 仅客户端 | 强制入队角色,跟config.json中的avatarLimits有关(跟队内角色数量上限有关)。用法:`join 10000021 10000022` | |
| kick | kick \<uid> | server.kick | 均可使用 | 从服务器中踢出指定玩家 (WIP) | k |
| killall | killall [uid] [场景ID] | server.killall | 均可使用 | 杀死指定玩家世界中所在或指定场景的全部生物 | |
| list | list | | 均可使用 | 列出在线玩家 | |
| permission | permission <add\|remove> <UID> <权限节点> | * | 均可使用 | 添加或移除玩家的权限 | |
| position | position | | 仅客户端 | 获取当前坐标 | pos |
| remove | remove [多个角色在队伍中的序号] | player.remove | 仅客户端 | 强制将某个角色从当前队伍中移除。例如`remove 1 2`表示将1号和2号角色移除 | |
| reload | reload | server.reload | 均可使用 | 重载服务器配置 | |
| resetconst | resetconst [all] | player.resetconstellation | 仅客户端 | 重置当前角色的命座,重新登录即可生效 | resetconstellation |
| restart | restart | | 均可使用 | 重启服务端 | |
......@@ -140,6 +142,7 @@ chmod +x gradlew
| talent | talent <天赋ID> <等级> | player.settalent | 仅客户端 | 设置当前角色的天赋等级 | |
| teleport | teleport [@playerUid] \<x> \<y> \<z> [sceneId] | player.teleport | 均可使用 | 传送玩家到指定坐标 | tp |
| tpall | | player.tpall | 仅客户端 | 传送多人世界中所有的玩家到自身地点 | |
| unlocktower | | player.tower | 仅客户端 | 解锁深渊全部层 | ut |
| weather | weather <天气ID> <气候ID> | player.weather | 仅客户端 | 改变天气 | w |
### 额外功能
......
......@@ -43,7 +43,8 @@ sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
group = 'xyz.grasscutters'
version = '1.1.0'
version = '1.1.2-dev'
sourceCompatibility = 17
targetCompatibility = 17
......@@ -86,6 +87,9 @@ dependencies {
implementation group: 'org.luaj', name: 'luaj-jse', version: '3.0.1'
protobuf files('proto/')
compileOnly 'org.projectlombok:lombok:1.18.24'
annotationProcessor 'org.projectlombok:lombok:1.18.24'
}
configurations.all {
......@@ -97,12 +101,14 @@ application {
mainClassName = 'emu.grasscutter.Grasscutter'
}
jar {
manifest {
attributes 'Main-Class': 'emu.grasscutter.Grasscutter'
}
jar.baseName = 'grasscutter'
jar.archiveName = project.hasProperty('jarFilename') ? "${jarFilename}.${extension}" : archiveName
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
......@@ -226,6 +232,23 @@ javadoc {
}
}
task injectGitHash {
def gitCommitHash = {
try {
return 'git rev-parse --verify --short HEAD'.execute().text.trim()
} catch (e) {
return "GIT_NOT_FOUND"
}
}
new File(projectDir, "src/main/java/emu/grasscutter/BuildConfig.java").text = """
package emu.grasscutter;
public class BuildConfig {
public static final String VERSION = \"${version}\";
public static final String GIT_HASH = \"${gitCommitHash()}\";
}
"""
}
processResources {
dependsOn "generateProto"
}
{
"list": [
{
"ann_id": 1,
"title": "<b>Welcome to Grasscutter!</b>",
"subtitle": "<b>Welcome</b>",
"banner": "https://uploadstatic-sea.mihoyo.com/announcement/2020/09/17/f4aa42d505822805eebf4a55d72a78d8_2755691727027973637.jpg",
"content": "Hi there!<br>First of all, welcome to Grasscutter. If you have any issues, please let us know so that Lawnmower can help you! Check out our:<br><div><p style=\"white-space: pre-wrap;\"><strong>¡þDiscord¡þ</strong></p><p style=\"white-space: pre-wrap;\"><a href=\"https://discord.gg/T5vZU6UyeG\">https://discord.gg/T5vZU6UyeG</a></p><p style=\"white-space: pre-wrap;\"><strong>¡þGitHub¡þ</strong></p><p style=\"white-space: pre-wrap;\"><a href=\"https://github.com/Grasscutters/Grasscutter\">https://github.com/Grasscutters/Grasscutter</a></p></div>",
"lang": "es-es"
},
{
"ann_id": 2,
"title": "<b>How to use announcements</b>",
"subtitle": "<b>How to use</b>",
"banner": "https://uploadstatic-sea.mihoyo.com/announcement/2020/09/17/f4aa42d505822805eebf4a55d72a78d8_2755691727027973637.jpg",
"content": "<strong>Tips<br></strong>>How to use announcements<br><br>>Announcement content can use HTML<br><br>>The specific content of the announcement is stored in the program directory<code>data/GameAnnouncement.json</code>, while<code>GameAnnouncementList.json</code> stores the announcement list data<br><br><strong>How to use</strong><br>>In <code>GameAnnouncement</code><table><thead><thead><tr><th>Parameters</th><th>Description</th></thead></thead><thbody><thead><tr><th>ann_Id</th><th>Announcement unique id</th></thead><thead><tr><th>title</th><th>Show at the top of the content</th></thead><thead><tr><th>subtitle</th><th>title shown on the left</th></thead><thead><tr><th>banner</th><th>Display between content and title</th></thead><thead><tr><th>content</th><th>as u see</th></thead><thead><tr><th>lang</th><th>display language</th></thead><thead><tr><th>total</th><th>Announcement quantity</th></thead></thbody></table><br><br>>In <code>GameAnnouncementList</code><br>If you want to add an annouement, please add the list data in the announcement type corresponding to GameAnnouncementList, and finally add the announcement content in GameAnnouncement",
"lang": "es-es"
},
{
"ann_id": 3,
"title": "<b>ÕâÊǻ¹«¸æ--This is the event announcement</b>",
"subtitle": "<b>Welcome</b>",
"banner":"https://uploadstatic-sea.mihoyo.com/announcement/2020/09/22/7d85f19b152d218e73224d7c138a0fd0_5818585260283672899.jpg",
"content": "Welcome",
"lang": "es-es"
}
],
"total": 3
}
\ No newline at end of file
{
"t": "System.currentTimeMillis()",
"list": [
{
"list": [
{
"ann_id": 1,
"title": "<b>Welcome to Grasscutter!</b>",
"subtitle": "<b>Welcome</b>",
"banner": "https://uploadstatic-sea.mihoyo.com/announcement/2020/09/22/7d85f19b152d218e73224d7c138a0fd0_5818585260283672899.jpg",
"content": "",
"type_label": "Juego",
"tag_label": "1",
"tag_icon": "https://uploadstatic-sea.mihoyo.com/announcement/2020/03/05/a2588f1a51faee9fa8dfe9aead649dd6_7237021399135895303.png",
"login_alert": 1,
"lang": "es-es",
"start_time": "2020-09-25 04:05:30",
"end_time": "2023-10-30 11:00:00",
"type": 2,
"remind": 0,
"alert": 0,
"tag_start_time": "2000-01-02 15:04:05",
"tag_end_time": "2030-01-02 15:04:05",
"remind_ver": 1,
"has_content": true,
"extra_remind": 0
},
{
"ann_id": 2,
"title": "<b>这是游戏公告 -- This is the game announcement</b>",
"subtitle": "<b>This is the game announcement</b>",
"banner": "https://uploadstatic-sea.mihoyo.com/announcement/2020/09/17/85b7163c95745a76d49b3d163d893592_6487108933004985049.jpg",
"content": "",
"type_label": "Juego",
"tag_label": "1",
"tag_icon": "https://uploadstatic-sea.mihoyo.com/announcement/2020/03/05/a2588f1a51faee9fa8dfe9aead649dd6_7237021399135895303.png",
"login_alert": 1,
"lang": "es-es",
"start_time": "2020-09-25 15:12:09",
"end_time": "2030-10-30 11:00:00",
"type": 2,
"remind": 0,
"alert": 0,
"tag_start_time": "2000-01-02 08:04:05",
"tag_end_time": "2030-01-02 08:04:05",
"remind_ver": 1,
"has_content": true,
"extra_remind": 0
}
],
"type_id": 2,
"type_label": "Juego"
},
{
"list": [
{
"ann_id": 3,
"title": "<b>这是活动公告--This is the event announcement</b>",
"subtitle": "<b>Welcome</b>",
"banner": "https://uploadstatic-sea.mihoyo.com/announcement/2020/09/22/7d85f19b152d218e73224d7c138a0fd0_5818585260283672899.jpg",
"content": "",
"type_label": "Eventos",
"tag_label": "1",
"tag_icon": "https://uploadstatic-sea.mihoyo.com/announcement/2020/03/05/a2588f1a51faee9fa8dfe9aead649dd6_7237021399135895303.png",
"login_alert": 1,
"lang": "es-es",
"start_time": "2020-09-25 04:05:30",
"end_time": "2022-05-02 00:51:00",
"type": 2,
"remind": 0,
"alert": 0,
"tag_start_time": "2000-01-02 15:04:05",
"tag_end_time": "2022-05-02 00:51:00",
"remind_ver": 1,
"has_content": true,
"extra_remind": 0
}
],
"type_id": 1,
"type_label": "Eventos"
},
{
"list": [
{}
],
"type_id": 3,
"type_label": "Others"
}
],
"total": 3,
"type_list": [
{
"id": 2,
"name": "游戏系统公告",
"mi18n_name": "Juego"
},
{
"id": 1,
"name": "活动公告",
"mi18n_name": "Eventos"
},
{
"id": 3,
"name": "其他",
"mi18n_name": "Others"
}
],
"alert": true,
"alert_id": 2,
"timezone": -5,
"pic_list": [
],
"pic_total": 0,
"pic_type_list": [
],
"pic_alert": false,
"pic_alert_id": 0,
"static_sign": ""
}
\ No newline at end of file
GpgdCgo4LjIwOS42Ni4xENWsARosaHR0cHM6Ly9vc2V1cm9vYXNlcnZlci55dWFuc2hlbi5jb20vcmVjaGFyZ2U6BGV1cm9COWh0dHBzOi8vYXV0b3BhdGNoaGsueXVhbnNoZW4uY29tL2NsaWVudF9nYW1lX3Jlcy8yLjZfbGl2ZUo8aHR0cHM6Ly9hdXRvcGF0Y2hoay55dWFuc2hlbi5jb20vY2xpZW50X2Rlc2lnbl9kYXRhLzIuNl9saXZlUpIBaHR0cHM6Ly93ZWJzdGF0aWMtc2VhLmhveW92ZXJzZS5jb20veXMvZXZlbnQvaW0tc2VydmljZS9pbmRleC5odG1sP2ltX291dD1mYWxzZSZzaWduX3R5cGU9MiZhdXRoX2FwcGlkPWltX2NjcyZhdXRoa2V5X3Zlcj0xJndpbl9kaXJlY3Rpb249cG9ydHJhaXRiCDIuNl9saXZlcNnsmgOQAdnsmgOaAVx7InJlbW90ZU5hbWUiOiAiZGF0YV92ZXJzaW9ucyIsICJtZDUiOiAiMWE0NDVhZTQ4ZmJkYmUwMzgzMTJiZTg2OGYyODEzZDIiLCAiZmlsZVNpemUiOiA0NDE1faIBW3sicmVtb3RlTmFtZSI6ICJkYXRhX3ZlcnNpb25zIiwgIm1kNSI6ICIxNzU0MmM3YmJhYzQ5YjkxMWRlMjlhOTYyNzU0YmQ2MSIsICJmaWxlU2l6ZSI6IDUxNH2yAYEGCL23mQMa4AV7InJlbW90ZU5hbWUiOiAicmVzX3ZlcnNpb25zX2V4dGVybmFsIiwgIm1kNSI6ICI5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9YHZeyPpZkYc6DkJWCRYbFfmczNIs133KB9rlfug40w/hHa8pXyRyLaKQUMIUYEvt3Y4AQ==
\ No newline at end of file
#!/usr/bin/env bash
# Grasscutter install script for linux
# Made by TurtleIdiot
# Stops the installer if any command has a non-zero exit status
set -e
# Checks for root
if [ $EUID != 0 ]; then
echo "Please run the installer as root!"
exit
fi
is_command() {
# Checks if a given command is available
local check_command="$1"
command -v "${check_command}" > /dev/null 2>&1
}
# IP validation
valid_ip() {
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS="."
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
# Checks for supported installer(s) (only apt-get and pacman right now, might add more in the future)
if is_command apt-get ; then
echo -e "Supported package manager found (apt-get)\n"
GC_DEPS="mongodb openjdk-17-jre"
INSTALLER_DEPS="wget openssl unzip git"
SYSTEM="deb" # Debian-based (debian, ubuntu)
elif is_command pacman ; then
echo -e "supported package manager found (pacman)\n"
GC_DEPS="jre17-openjdk"
INSTALLER_DEPS="curl wget openssl unzip git base-devel" # curl is still a dependency here in order to successfully build mongodb
SYSTEM="arch" # Arch for the elitists :P
else
echo "No supported package manager found"
exit
fi
BRANCH="stable" # Stable by default
# Allows choice between stable and dev branch
echo "Please select the branch you wish to install"
echo -e "!!NOTE!!: stable is the recommended branch.\nDo *NOT* use development unless you have a reason to and know what you're doing"
select branch in "stable" "development" ; do
case $branch in
stable )
BRANCH="stable"
break;;
development )
BRANCH="development"
break;;
esac
done
echo "The following packages will have to be installed in order to INSTALL grasscutter:"
echo -e "$INSTALLER_DEPS \n"
echo "The following packages will have to be installed to RUN grasscutter:"
echo -e "$GC_DEPS \n"
echo "Do you wish to proceed and install grasscutter?"
select yn in "Yes" "No" ; do
case $yn in
Yes ) break;;
No ) exit;;
esac
done
echo "Updating package cache..."
case $SYSTEM in # More concise than if
deb ) apt-get update -qq;;
arch ) pacman -Syy;;
esac
# Starts installing dependencies
echo "Installing setup dependencies..."
case $SYSTEM in # These are one-liners anyways
deb ) apt-get -qq install $INSTALLER_DEPS -y;;
arch ) pacman -Sq --noconfirm --needed $INSTALLER_DEPS > /dev/null;;
esac
echo "Done"
echo "Installing grasscutter dependencies..."
case $SYSTEM in
deb) apt-get -qq install $GC_DEPS -y > /dev/null;;
arch ) pacman -Sq --noconfirm --needed $GC_DEPS > /dev/null;;
esac
# *sighs* here we go...
INST_ARCH_MONGO="no"
if [ $SYSTEM = "arch" ]; then
echo -e "-=-=-=-=-=--- !! IMPORTANT !! ---=-=-=-=-=-\n"
echo -e " Due to licensing issues with mongodb,\n it is no longer available on the official arch repositiries."
echo -e " In order to install mongodb,\n it needs to be fetched from the Arch User Repository.\n"
echo -e " As this script is running as root,\n a temporary user will need to be created to run makepkg."
echo -e " The temporary user will be deleted once\n makepkg has finished.\n"
echo -e " This will be handled automatically.\n"
echo -e "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"
echo -e "!!NOTE!!: Only select \"Skip\" if mongodb is already installed on this system"
echo "Do you want to continue?"
select yn in "Yes" "Skip" "No" ; do
case $yn in
Yes )
INST_ARCH_MONGO="yes"
break;;
No ) exit;;
Skip )
INST_ARCH_MONGO="no"
break;;
esac
done
fi
if [ $INST_ARCH_MONGO = "yes" ]; then
DIR=$(pwd)
# Make temp user
echo "Creating temporary user..."
TEMPUSER="gctempuser"
TEMPHOME="/home/$TEMPUSER"
useradd -m $TEMPUSER
cd $TEMPHOME
# Do the actual makepkg shenanigans
echo "Building mongodb... (this will take a moment)"
su $TEMPUSER<<EOF
mkdir temp
cd temp
git clone https://aur.archlinux.org/mongodb-bin.git -q
cd mongodb-bin
makepkg -s > /dev/null
exit
EOF
mv "$(find -name "mongodb-bin*.pkg.tar.zst" -type f)" ./mongodb-bin.pkg.tar.zst
cd $DIR
# Snatch the file to current working directory
mv "$TEMPHOME/mongodb-bin.pkg.tar.zst" ./mongodb-bin.pkg.tar.zst
chown root ./mongodb-bin.pkg.tar.zst
chgrp root ./mongodb-bin.pkg.tar.zst
chmod 775 ./mongodb-bin.pkg.tar.zst
echo "Installing mongodb..."
pacman -U mongodb-bin.pkg.tar.zst --noconfirm > /dev/null
rm mongodb-bin.pkg.tar.zst
echo "Starting mongodb..."
systemctl enable mongodb
systemctl start mongodb
echo "Removing temporary account..."
userdel -r $TEMPUSER
fi
echo "Done"
echo "Getting grasscutter..."
# Download and rename jar
wget -q --show-progress "https://nightly.link/Grasscutters/Grasscutter/workflows/build/$BRANCH/Grasscutter.zip"
echo "unzipping"
unzip -qq Grasscutter.zip
mv $(find -name "grasscutter*.jar" -type f) grasscutter.jar
# Download resources
echo "Downloading resources... (this will take a moment)"
wget -q --show-progress https://github.com/Koko-boya/Grasscutter_Resources/archive/refs/heads/main.zip -O resources.zip
echo "Extracting..."
unzip -qq resources.zip
mv ./Grasscutter_Resources-main/Resources ./resources
# Here we do a sparse checkout to only pull /data and /keys
echo "Downloading keys and data..."
mkdir repo
cd repo
git init -q
git remote add origin https://github.com/Grasscutters/Grasscutter.git
git fetch -q
git config core.sparseCheckout true
echo "data/" >> .git/info/sparse-checkout
echo "keys/" >> .git/info/sparse-checkout
git pull origin stable -q
cd ../
mv ./repo/data ./data
mv ./repo/keys ./keys
# Generate handbook/config
echo "Please enter language when *NEXT* prompted (press enter/return to continue to language select)"
read
java -jar grasscutter.jar -handbook
# Prompt IP address for config.json and for generating new keystore.p12 file
echo "Please enter the IP address that will be used to connect to the server"
echo "This can be a local or a public IP address"
echo "This IP address will be used to generate SSL certificates so it is important it is correct"
while : ; do
read -p "Enter IP: " SERVER_IP
if valid_ip $SERVER_IP; then
break;
else
echo "Invalid IP address. Try again."
fi
done
# Replaces "127.0.0.1" with given IP
sed -i "s/127.0.0.1/$SERVER_IP/g" config.json
# Generates new keystore.p12 with the server's IP address
# This is done to prevent a "Connection Timed Out" error from appearing
# after clicking to enter the door in the main menu/title screen
# This issue only exists when connecting to a server *other* than localhost
# since the default keystore.p12 has only been made for localhost
mkdir certs
cd certs
echo "Generating CA key and certificate pair..."
openssl req -x509 -nodes -days 25202 -newkey rsa:2048 -subj "/C=GB/ST=Essex/L=London/O=Grasscutters/OU=Grasscutters/CN=$SERVER_IP" -keyout CAkey.key -out CAcert.crt
echo "Generating SSL key and certificate pair..."
openssl genpkey -out ssl.key -algorithm rsa
# Creates a conf file in order to generate a csr
cat > csr.conf <<EOF
[ req ]
default_bits = 2048
prompt = no
default_md = sha256
req_extensions = req_ext
distinguished_name = dn
[ dn ]
C = GB
ST = Essex
L = London
O = Grasscutters
OU = Grasscutters
CN = $SERVER_IP
[ req_ext ]
subjectAltName = @alt_names
[ alt_names ]
IP.1 = $SERVER_IP
EOF
# Creates csr using key and conf
openssl req -new -key ssl.key -out ssl.csr -config csr.conf
# Creates conf to finalise creation of certificate
cat > cert.conf <<EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, keyAgreement, dataEncipherment
subjectAltName = @alt_names
[alt_names]
IP.1 = $SERVER_IP
EOF
# Creates ssl cert
openssl x509 -req -in ssl.csr -CA CAcert.crt -CAkey CAkey.key -CAcreateserial -out ssl.crt -days 25202 -sha256 -extfile cert.conf
echo "Generating keystore.p12 from key and certificate..."
openssl pkcs12 -export -out keystore.p12 -inkey ssl.key -in ssl.crt -certfile CAcert.crt -passout pass:123456
cd ../
mv ./certs/keystore.p12 ./keystore.p12
echo "Done"
echo -e "Asking Noelle to clean up...\n"
rm -rf Grasscutter.zip resources.zip ./certs ./Grasscutter_Resources-main ./repo
echo -e "All done!\n"
echo -e "You can now uninstall the following packages if you wish:\n$INSTALLER_DEPS"
echo -e "-=-=-=-=-=--- !! IMPORTANT !! ---=-=-=-=-=-\n"
echo "Please make sure that ports 443 and 22102 are OPEN (both tcp and udp)"
echo -e "In order to run the server, run the following command:\nsudo java -jar grasscutter.jar"
echo "You must run it using sudo as port 443 is a privileged port"
echo "To play, use the IP you provided earlier ($SERVER_IP) via GrassClipper or Fiddler"
exit
No preview for this file type
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "JSON schema for a Grasscutter Plugin",
"type": "object",
"additionalProperties": true,
"definitions": {
"plugin-name": {
"type": "string",
"pattern": "^[A-Za-z\\d_.-]+$"
}
},
"required": [ "name", "description", "mainClass" ],
"properties": {
"name": {
"description": "The unique name of plugin.",
"$ref": "#/definitions/plugin-name"
},
"mainClass": {
"description": "The plugin's initial class file.",
"type": "string",
"pattern": "^(?!org\\.bukkit\\.)([a-zA-Z_$][a-zA-Z\\d_$]*\\.)*[a-zA-Z_$][a-zA-Z\\d_$]*$"
},
"version": {
"description": "A plugin revision identifier.",
"type": [ "string", "number" ]
},
"description": {
"description": "Human readable plugin summary.",
"type": "string"
},
"author": {
"description": "The plugin author.",
"type": "string"
},
"authors": {
"description": "The plugin contributors.",
"type": "array",
"items": {
"type": "string"
}
},
"website": {
"title": "Website",
"description": "The URL to the plugin's site",
"type": "string",
"format": "uri"
}
}
}
\ No newline at end of file
package emu.grasscutter;
import java.util.Locale;
import emu.grasscutter.Grasscutter.ServerDebugMode;
import emu.grasscutter.Grasscutter.ServerRunMode;
import emu.grasscutter.game.mail.Mail;
public final class Config {
public String DatabaseUrl = "mongodb://localhost:27017";
public String DatabaseCollection = "grasscutter";
public String RESOURCE_FOLDER = "./resources/";
public String DATA_FOLDER = "./data/";
public String PACKETS_FOLDER = "./packets/";
public String DUMPS_FOLDER = "./dumps/";
public String KEY_FOLDER = "./keys/";
public String SCRIPTS_FOLDER = "./resources/Scripts/";
public String PLUGINS_FOLDER = "./plugins/";
public ServerDebugMode DebugMode = ServerDebugMode.NONE; // ALL, MISSING, NONE
public ServerRunMode RunMode = ServerRunMode.HYBRID; // HYBRID, DISPATCH_ONLY, GAME_ONLY
public GameServerOptions GameServer = new GameServerOptions();
public DispatchServerOptions DispatchServer = new DispatchServerOptions();
public Locale LocaleLanguage = Locale.getDefault();
public Locale DefaultLanguage = Locale.ENGLISH;
public Boolean OpenStamina = true;
public GameServerOptions getGameServerOptions() {
return GameServer;
}
public DispatchServerOptions getDispatchOptions() { return DispatchServer; }
public static class DispatchServerOptions {
public String Ip = "0.0.0.0";
public String PublicIp = "127.0.0.1";
public int Port = 443;
public int PublicPort = 0;
public String KeystorePath = "./keystore.p12";
public String KeystorePassword = "123456";
public Boolean UseSSL = true;
public Boolean FrontHTTPS = true;
public Boolean CORS = false;
public String[] CORSAllowedOrigins = new String[] { "*" };
public boolean AutomaticallyCreateAccounts = false;
public String[] defaultPermissions = new String[] { "" };
public RegionInfo[] GameServers = {};
public RegionInfo[] getGameServers() {
return GameServers;
}
public static class RegionInfo {
public String Name = "os_usa";
public String Title = "Test";
public String Ip = "127.0.0.1";
public int Port = 22102;
}
}
public static class GameServerOptions {
public String Name = "Test";
public String Ip = "0.0.0.0";
public String PublicIp = "127.0.0.1";
public int Port = 22102;
public int PublicPort = 0;
public String DispatchServerDatabaseUrl = "mongodb://localhost:27017";
public String DispatchServerDatabaseCollection = "grasscutter";
public int InventoryLimitWeapon = 2000;
public int InventoryLimitRelic = 2000;
public int InventoryLimitMaterial = 2000;
public int InventoryLimitFurniture = 2000;
public int InventoryLimitAll = 30000;
public int MaxAvatarsInTeam = 4;
public int MaxAvatarsInTeamMultiplayer = 4;
public int MaxEntityLimit = 1000; // Max entity limit per world. // TODO: Enforce later.
public boolean WatchGacha = false;
public String ServerNickname = "Server";
public int ServerAvatarId = 10000007;
public int ServerNameCardId = 210001;
public int ServerLevel = 1;
public int ServerWorldLevel = 1;
public String ServerSignature = "Server Signature";
public int[] WelcomeEmotes = {2007, 1002, 4010};
public String WelcomeMotd = "Welcome to Grasscutter emu";
public String WelcomeMailTitle = "Welcome to Grasscutter!";
public String WelcomeMailSender = "Lawnmower";
public String WelcomeMailContent = "Hi there!\r\nFirst of all, welcome to Grasscutter. If you have any issues, please let us know so that Lawnmower can help you! \r\n\r\nCheck out our:\r\n<type=\"browser\" text=\"Discord\" href=\"https://discord.gg/T5vZU6UyeG\"/>";
public Mail.MailItem[] WelcomeMailItems = {
new Mail.MailItem(13509, 1, 1),
new Mail.MailItem(201, 10000, 1),
};
public boolean EnableOfficialShop = true;
public GameRates Game = new GameRates();
public GameRates getGameRates() { return Game; }
public static class GameRates {
public float ADVENTURE_EXP_RATE = 1.0f;
public float MORA_RATE = 1.0f;
public float DOMAIN_DROP_RATE = 1.0f;
}
}
}
package emu.grasscutter;
import emu.grasscutter.utils.ConfigContainer;
import emu.grasscutter.utils.ConfigContainer.*;
import java.util.Locale;
import java.nio.file.Paths;
import static emu.grasscutter.Grasscutter.config;
/**
* A data container for the server's configuration.
*
* Use `import static emu.grasscutter.Configuration.*;`
* to import all configuration constants.
*/
public final class Configuration extends ConfigContainer {
/*
* Constants
*/
// 'c' is short for 'config' and makes code look 'cleaner'.
public static final ConfigContainer c = config;
public static final Locale LANGUAGE = config.language.language;
public static final Locale FALLBACK_LANGUAGE = config.language.fallback;
public static final String DOCUMENT_LANGUAGE = config.language.document;
private static final String DATA_FOLDER = config.folderStructure.data;
private static final String RESOURCES_FOLDER = config.folderStructure.resources;
private static final String PLUGINS_FOLDER = config.folderStructure.plugins;
private static final String SCRIPTS_FOLDER = config.folderStructure.scripts;
private static final String PACKETS_FOLDER = config.folderStructure.packets;
public static final Server SERVER = config.server;
public static final Database DATABASE = config.databaseInfo;
public static final Account ACCOUNT = config.account;
public static final HTTP HTTP_INFO = config.server.http;
public static final Game GAME_INFO = config.server.game;
public static final Dispatch DISPATCH_INFO = config.server.dispatch;
public static final Encryption HTTP_ENCRYPTION = config.server.http.encryption;
public static final Policies HTTP_POLICIES = config.server.http.policies;
public static final Files HTTP_STATIC_FILES = config.server.http.files;
public static final GameOptions GAME_OPTIONS = config.server.game.gameOptions;
public static final GameOptions.InventoryLimits INVENTORY_LIMITS = config.server.game.gameOptions.inventoryLimits;
/*
* Utilities
*/
public static String DATA() {
return DATA_FOLDER;
}
public static String DATA(String path) {
return Paths.get(DATA_FOLDER, path).toString();
}
public static String RESOURCE(String path) {
return Paths.get(RESOURCES_FOLDER, path).toString();
}
public static String PLUGIN() {
return PLUGINS_FOLDER;
}
public static String PLUGIN(String path) {
return Paths.get(PLUGINS_FOLDER, path).toString();
}
public static String SCRIPT(String path) {
return Paths.get(SCRIPTS_FOLDER, path).toString();
}
public static String PACKET(String path) {
return Paths.get(PACKETS_FOLDER, path).toString();
}
/**
* Fallback method.
* @param left Attempt to use.
* @param right Use if left is undefined.
* @return Left or right.
*/
public static <T> T lr(T left, T right) {
return left == null ? right : left;
}
/**
* {@link Configuration#lr(Object, Object)} for {@link String}s.
* @param left Attempt to use.
* @param right Use if left is empty.
* @return Left or right.
*/
public static String lr(String left, String right) {
return left.isEmpty() ? right : left;
}
/**
* {@link Configuration#lr(Object, Object)} for {@link Integer}s.
* @param left Attempt to use.
* @param right Use if left is 0.
* @return Left or right.
*/
public static int lr(int left, int right) {
return left == 0 ? right : left;
}
}
......@@ -6,7 +6,7 @@ import emu.grasscutter.utils.Position;
import emu.grasscutter.utils.Utils;
public final class GameConstants {
public static String VERSION = "2.6.0";
public static String VERSION = "2.7.0";
public static final int MAX_TEAMS = 4;
public static final int MAIN_CHARACTER_MALE = 10000005;
......
package emu.grasscutter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOError;
import java.io.*;
import java.util.Calendar;
import emu.grasscutter.auth.AuthenticationSystem;
import emu.grasscutter.auth.DefaultAuthentication;
import emu.grasscutter.command.CommandMap;
import emu.grasscutter.game.managers.EnergyManager.EnergyManager;
import emu.grasscutter.game.managers.StaminaManager.StaminaManager;
import emu.grasscutter.plugin.PluginManager;
import emu.grasscutter.plugin.api.ServerHook;
import emu.grasscutter.scripts.ScriptLoader;
import emu.grasscutter.server.http.HttpServer;
import emu.grasscutter.server.http.dispatch.DispatchHandler;
import emu.grasscutter.server.http.handlers.*;
import emu.grasscutter.server.http.dispatch.RegionHandler;
import emu.grasscutter.server.http.documentation.DocumentationServerHandler;
import emu.grasscutter.utils.ConfigContainer;
import emu.grasscutter.utils.Utils;
import org.jline.reader.EndOfFileException;
import org.jline.reader.LineReader;
......@@ -27,30 +34,33 @@ import ch.qos.logback.classic.Logger;
import emu.grasscutter.data.ResourceLoader;
import emu.grasscutter.database.DatabaseManager;
import emu.grasscutter.utils.Language;
import emu.grasscutter.server.dispatch.DispatchServer;
import emu.grasscutter.server.game.GameServer;
import emu.grasscutter.tools.Tools;
import emu.grasscutter.utils.Crypto;
import javax.annotation.Nullable;
import static emu.grasscutter.utils.Language.translate;
import static emu.grasscutter.Configuration.*;
public final class Grasscutter {
private static final Logger log = (Logger) LoggerFactory.getLogger(Grasscutter.class);
private static LineReader consoleLineReader = null;
private static Config config;
private static Language language;
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private static final File configFile = new File("./config.json");
public static final File configFile = new File("./config.json");
private static int day; // Current day of week.
private static DispatchServer dispatchServer;
private static HttpServer httpServer;
private static GameServer gameServer;
private static PluginManager pluginManager;
private static AuthenticationSystem authenticationSystem;
public static final Reflections reflector = new Reflections("emu.grasscutter");
public static ConfigContainer config;
static {
// Declare logback configuration.
......@@ -58,6 +68,8 @@ public final class Grasscutter {
// Load server configuration.
Grasscutter.loadConfig();
// Attempt to update configuration.
ConfigContainer.updateConfig();
// Load translation files.
Grasscutter.loadLanguage();
......@@ -66,9 +78,9 @@ public final class Grasscutter {
Utils.startupCheck();
}
public static void main(String[] args) throws Exception {
Crypto.loadKeys(); // Load keys from buffers.
public static void main(String[] args) throws Exception {
Crypto.loadKeys(); // Load keys from buffers.
// Parse arguments.
boolean exitEarly = false;
for (String arg : args) {
......@@ -77,57 +89,81 @@ public final class Grasscutter {
Tools.createGmHandbook(); exitEarly = true;
}
case "-gachamap" -> {
Tools.createGachaMapping(Grasscutter.getConfig().DATA_FOLDER + "/gacha_mappings.js"); exitEarly = true;
Tools.createGachaMapping(DATA("gacha_mappings.js")); exitEarly = true;
}
case "-version" -> {
System.out.println("Grasscutter version: " + BuildConfig.VERSION + "-" + BuildConfig.GIT_HASH); exitEarly = true;
}
}
}
// Exit early if argument sets it.
if(exitEarly) System.exit(0);
// Initialize server.
Grasscutter.getLogger().info(translate("messages.status.starting"));
Grasscutter.getLogger().info(translate("messages.status.game_version", GameConstants.VERSION));
Grasscutter.getLogger().info(translate("messages.status.version", BuildConfig.VERSION, BuildConfig.GIT_HASH));
// Load all resources.
Grasscutter.updateDayOfWeek();
ResourceLoader.loadAll();
ScriptLoader.init();
EnergyManager.initialize();
// Initialize database.
DatabaseManager.initialize();
// Initialize the default authentication system.
authenticationSystem = new DefaultAuthentication();
// Create server instances.
dispatchServer = new DispatchServer();
httpServer = new HttpServer();
gameServer = new GameServer();
// Create a server hook instance with both servers.
new ServerHook(gameServer, dispatchServer);
new ServerHook(gameServer, httpServer);
// Create plugin manager instance.
pluginManager = new PluginManager();
// Add HTTP routes after loading plugins.
httpServer.addRouter(HttpServer.UnhandledRequestRouter.class);
httpServer.addRouter(HttpServer.DefaultRequestRouter.class);
httpServer.addRouter(RegionHandler.class);
httpServer.addRouter(LogHandler.class);
httpServer.addRouter(GenericHandler.class);
httpServer.addRouter(AnnouncementsHandler.class);
httpServer.addRouter(DispatchHandler.class);
httpServer.addRouter(GachaHandler.class);
httpServer.addRouter(DocumentationServerHandler.class);
// TODO: find a better place?
StaminaManager.initialize();
// Start servers.
if (getConfig().RunMode == ServerRunMode.HYBRID) {
dispatchServer.start();
var runMode = SERVER.runMode;
if (runMode == ServerRunMode.HYBRID) {
httpServer.start();
gameServer.start();
} else if (getConfig().RunMode == ServerRunMode.DISPATCH_ONLY) {
dispatchServer.start();
} else if (getConfig().RunMode == ServerRunMode.GAME_ONLY) {
} else if (runMode == ServerRunMode.DISPATCH_ONLY) {
httpServer.start();
} else if (runMode == ServerRunMode.GAME_ONLY) {
gameServer.start();
} else {
getLogger().error(translate("messages.status.run_mode_error", getConfig().RunMode));
getLogger().error(translate("messages.status.run_mode_error", runMode));
getLogger().error(translate("messages.status.run_mode_help"));
getLogger().error(translate("messages.status.shutdown"));
System.exit(1);
}
// Enable all plugins.
pluginManager.enablePlugins();
// Hook into shutdown event.
Runtime.getRuntime().addShutdownHook(new Thread(Grasscutter::onShutdown));
// Open console.
startConsole();
}
}
/**
* Server shutdown event.
......@@ -137,75 +173,61 @@ public final class Grasscutter {
pluginManager.disablePlugins();
}
/*
* Methods for the language system component.
*/
public static void loadLanguage() {
var locale = config.language.language;
language = Language.getLanguage(Utils.getLanguageCode(locale));
}
/*
* Methods for the configuration system component.
*/
/**
* Attempts to load the configuration from a file.
*/
public static void loadConfig() {
// Check if config.json exists. If not, we generate a new config.
if (!configFile.exists()) {
getLogger().info("config.json could not be found. Generating a default configuration ...");
config = new ConfigContainer();
Grasscutter.saveConfig(config);
return;
}
// If the file already exists, we attempt to load it.
try (FileReader file = new FileReader(configFile)) {
config = gson.fromJson(file, Config.class);
saveConfig();
} catch (Exception e) {
Grasscutter.config = new Config();
saveConfig();
}
config = gson.fromJson(file, ConfigContainer.class);
} catch (Exception exception) {
getLogger().error("There was an error while trying to load the configuration from config.json. Please make sure that there are no syntax errors. If you want to start with a default configuration, delete your existing config.json.");
System.exit(1);
}
}
public static void loadLanguage() {
var locale = config.LocaleLanguage;
var languageTag = locale.toLanguageTag();
/**
* Saves the provided server configuration.
* @param config The configuration to save, or null for a new one.
*/
public static void saveConfig(@Nullable ConfigContainer config) {
if(config == null) config = new ConfigContainer();
if (languageTag.equals("und")) {
Grasscutter.getLogger().error("Illegal locale language, using 'en-US' instead.");
language = Language.getLanguage("en-US");
} else {
language = Language.getLanguage(languageTag);
}
}
public static void saveConfig() {
try (FileWriter file = new FileWriter(configFile)) {
file.write(gson.toJson(config));
} catch (IOException ignored) {
Grasscutter.getLogger().error("Unable to write to config file.");
} catch (Exception e) {
Grasscutter.getLogger().error("Unable to save config file.");
Grasscutter.getLogger().error("Unable to save config file.", e);
}
}
public static void startConsole() {
// Console should not start in dispatch only mode.
if (getConfig().RunMode == ServerRunMode.DISPATCH_ONLY) {
getLogger().info(translate("messages.dispatch.no_commands_error"));
return;
}
getLogger().info(translate("messages.status.done"));
String input = null;
boolean isLastInterrupted = false;
while (true) {
try {
input = consoleLineReader.readLine("> ");
} catch (UserInterruptException e) {
if (!isLastInterrupted) {
isLastInterrupted = true;
Grasscutter.getLogger().info("Press Ctrl-C again to shutdown.");
continue;
} else {
Runtime.getRuntime().exit(0);
}
} catch (EndOfFileException e) {
Grasscutter.getLogger().info("EOF detected.");
continue;
} catch (IOError e) {
Grasscutter.getLogger().error("An IO error occurred.", e);
continue;
}
isLastInterrupted = false;
try {
CommandMap.getInstance().invoke(null, null, input);
} catch (Exception e) {
Grasscutter.getLogger().error(translate("messages.game.command_error"), e);
}
}
}
public static Config getConfig() {
/*
* Getters for the various server components.
*/
public static ConfigContainer getConfig() {
return config;
}
......@@ -213,6 +235,14 @@ public final class Grasscutter {
return language;
}
public static void setLanguage(Language language) {
Grasscutter.language = language;
}
public static Language getLanguage(String langCode) {
return Language.getLanguage(langCode);
}
public static Logger getLogger() {
return log;
}
......@@ -241,8 +271,8 @@ public final class Grasscutter {
return gson;
}
public static DispatchServer getDispatchServer() {
return dispatchServer;
public static HttpServer getHttpServer() {
return httpServer;
}
public static GameServer getGameServer() {
......@@ -252,16 +282,74 @@ public final class Grasscutter {
public static PluginManager getPluginManager() {
return pluginManager;
}
public static AuthenticationSystem getAuthenticationSystem() {
return authenticationSystem;
}
public static int getCurrentDayOfWeek() {
return day;
}
/*
* Utility methods.
*/
public static void updateDayOfWeek() {
Calendar calendar = Calendar.getInstance();
day = calendar.get(Calendar.DAY_OF_WEEK);
}
public static int getCurrentDayOfWeek() {
return day;
public static void startConsole() {
// Console should not start in dispatch only mode.
if (SERVER.runMode == ServerRunMode.DISPATCH_ONLY) {
getLogger().info(translate("messages.dispatch.no_commands_error"));
return;
}
getLogger().info(translate("messages.status.done"));
String input = null;
boolean isLastInterrupted = false;
while (config.server.game.enableConsole) {
try {
input = consoleLineReader.readLine("> ");
} catch (UserInterruptException e) {
if (!isLastInterrupted) {
isLastInterrupted = true;
Grasscutter.getLogger().info("Press Ctrl-C again to shutdown.");
continue;
} else {
Runtime.getRuntime().exit(0);
}
} catch (EndOfFileException e) {
Grasscutter.getLogger().info("EOF detected.");
continue;
} catch (IOError e) {
Grasscutter.getLogger().error("An IO error occurred.", e);
continue;
}
isLastInterrupted = false;
try {
CommandMap.getInstance().invoke(null, null, input);
} catch (Exception e) {
Grasscutter.getLogger().error(translate("messages.game.command_error"), e);
}
}
}
/**
* Sets the authentication system for the server.
* @param authenticationSystem The authentication system to use.
*/
public static void setAuthenticationSystem(AuthenticationSystem authenticationSystem) {
Grasscutter.authenticationSystem = authenticationSystem;
}
/*
* Enums for the configuration.
*/
public enum ServerRunMode {
HYBRID, DISPATCH_ONLY, GAME_ONLY
}
......
package emu.grasscutter.auth;
import emu.grasscutter.game.Account;
import emu.grasscutter.server.http.objects.*;
import express.http.Request;
import express.http.Response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import javax.annotation.Nullable;
/**
* Defines an authenticator for the server.
* Can be changed by plugins.
*/
public interface AuthenticationSystem {
/**
* Called when a user requests to make an account.
* @param username The provided username.
* @param password The provided password. (SHA-256'ed)
*/
void createAccount(String username, String password);
/**
* Called when a user requests to reset their password.
* @param username The username of the account to reset.
*/
void resetPassword(String username);
/**
* Called by plugins to internally verify a user's identity.
* @param details A unique identifier to identify the user. (For example: a JWT token)
* @return The user's account if the verification was successful, null if the user was unable to be verified.
*/
Account verifyUser(String details);
/**
* This is the authenticator used for password authentication.
* @return An authenticator.
*/
Authenticator<LoginResultJson> getPasswordAuthenticator();
/**
* This is the authenticator used for token authentication.
* @return An authenticator.
*/
Authenticator<LoginResultJson> getTokenAuthenticator();
/**
* This is the authenticator used for session authentication.
* @return An authenticator.
*/
Authenticator<ComboTokenResJson> getSessionKeyAuthenticator();
/**
* This is the authenticator used for handling external authentication requests.
* @return An authenticator.
*/
ExternalAuthenticator getExternalAuthenticator();
/**
* This is the authenticator used for handling OAuth authentication requests.
* @return An authenticator.
*/
OAuthAuthenticator getOAuthAuthenticator();
/**
* A data container that holds relevant data for authenticating a client.
*/
@Builder @AllArgsConstructor @Getter
class AuthenticationRequest {
private final Request request;
@Nullable private final Response response;
@Nullable private final LoginAccountRequestJson passwordRequest;
@Nullable private final LoginTokenRequestJson tokenRequest;
@Nullable private final ComboTokenReqJson sessionKeyRequest;
@Nullable private final ComboTokenReqJson.LoginTokenData sessionKeyData;
}
/**
* Generates an authentication request from a {@link LoginAccountRequestJson} object.
* @param request The Express request.
* @param jsonData The JSON data.
* @return An authentication request.
*/
static AuthenticationRequest fromPasswordRequest(Request request, LoginAccountRequestJson jsonData) {
return AuthenticationRequest.builder()
.request(request)
.passwordRequest(jsonData)
.build();
}
/**
* Generates an authentication request from a {@link LoginTokenRequestJson} object.
* @param request The Express request.
* @param jsonData The JSON data.
* @return An authentication request.
*/
static AuthenticationRequest fromTokenRequest(Request request, LoginTokenRequestJson jsonData) {
return AuthenticationRequest.builder()
.request(request)
.tokenRequest(jsonData)
.build();
}
/**
* Generates an authentication request from a {@link ComboTokenReqJson} object.
* @param request The Express request.
* @param jsonData The JSON data.
* @return An authentication request.
*/
static AuthenticationRequest fromComboTokenRequest(Request request, ComboTokenReqJson jsonData,
ComboTokenReqJson.LoginTokenData tokenData) {
return AuthenticationRequest.builder()
.request(request)
.sessionKeyRequest(jsonData)
.sessionKeyData(tokenData)
.build();
}
/**
* Generates an authentication request from a {@link Response} object.
* @param request The Express request.
* @param response the Express response.
* @return An authentication request.
*/
static AuthenticationRequest fromExternalRequest(Request request, Response response) {
return AuthenticationRequest.builder().request(request)
.response(response).build();
}
}
package emu.grasscutter.auth;
import emu.grasscutter.server.http.objects.*;
/**
* Handles username/password authentication from the client.
* @param <T> The response object type. Should be {@link LoginResultJson} or {@link ComboTokenResJson}
*/
public interface Authenticator<T> {
/**
* Attempt to authenticate the client with the provided credentials.
* @param request The authentication request wrapped in a {@link AuthenticationSystem.AuthenticationRequest} object.
* @return The result of the login in an object.
*/
T authenticate(AuthenticationSystem.AuthenticationRequest request);
}
\ No newline at end of file
package emu.grasscutter.auth;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.auth.DefaultAuthenticators.*;
import emu.grasscutter.game.Account;
import emu.grasscutter.server.http.objects.ComboTokenResJson;
import emu.grasscutter.server.http.objects.LoginResultJson;
import static emu.grasscutter.utils.Language.translate;
/**
* The default Grasscutter authentication implementation.
* Allows all users to access any account.
*/
public final class DefaultAuthentication implements AuthenticationSystem {
private final Authenticator<LoginResultJson> passwordAuthenticator = new PasswordAuthenticator();
private final Authenticator<LoginResultJson> tokenAuthenticator = new TokenAuthenticator();
private final Authenticator<ComboTokenResJson> sessionKeyAuthenticator = new SessionKeyAuthenticator();
private final ExternalAuthenticator externalAuthenticator = new ExternalAuthentication();
private final OAuthAuthenticator oAuthAuthenticator = new OAuthAuthentication();
@Override
public void createAccount(String username, String password) {
// Unhandled. The default authenticator doesn't store passwords.
}
@Override
public void resetPassword(String username) {
// Unhandled. The default authenticator doesn't store passwords.
}
@Override
public Account verifyUser(String details) {
Grasscutter.getLogger().info(translate("dispatch.authentication.default_unable_to_verify"));
return null;
}
@Override
public Authenticator<LoginResultJson> getPasswordAuthenticator() {
return this.passwordAuthenticator;
}
@Override
public Authenticator<LoginResultJson> getTokenAuthenticator() {
return this.tokenAuthenticator;
}
@Override
public Authenticator<ComboTokenResJson> getSessionKeyAuthenticator() {
return this.sessionKeyAuthenticator;
}
@Override
public ExternalAuthenticator getExternalAuthenticator() {
return this.externalAuthenticator;
}
@Override
public OAuthAuthenticator getOAuthAuthenticator() {
return this.oAuthAuthenticator;
}
}
package emu.grasscutter.auth;
import emu.grasscutter.Grasscutter;
import emu.grasscutter.auth.AuthenticationSystem.AuthenticationRequest;
import emu.grasscutter.database.DatabaseHelper;
import emu.grasscutter.game.Account;
import emu.grasscutter.server.http.objects.*;
import static emu.grasscutter.Configuration.*;
import static emu.grasscutter.utils.Language.translate;
/**
* A class containing default authenticators.
*/
public final class DefaultAuthenticators {
/**
* Handles the authentication request from the username and password form.
*/
public static class PasswordAuthenticator implements Authenticator<LoginResultJson> {
@Override public LoginResultJson authenticate(AuthenticationRequest request) {
var response = new LoginResultJson();
var requestData = request.getPasswordRequest();
assert requestData != null; // This should never be null.
int playerCount = Grasscutter.getGameServer().getPlayers().size();
boolean successfulLogin = false;
String address = request.getRequest().ip();
String responseMessage = translate("messages.dispatch.account.username_error");
String loggerMessage = "";
// Get account from database.
Account account = DatabaseHelper.getAccountByName(requestData.account);
if (ACCOUNT.maxPlayer <= -1 || playerCount < ACCOUNT.maxPlayer) {
// Check if account exists.
if(account == null && ACCOUNT.autoCreate) {
// This account has been created AUTOMATICALLY. There will be no permissions added.
account = DatabaseHelper.createAccountWithUid(requestData.account, 0);
// Check if the account was created successfully.
if(account == null) {
responseMessage = translate("messages.dispatch.account.username_create_error");
Grasscutter.getLogger().info(translate("messages.dispatch.account.account_login_create_error", address));
} else {
// Continue with login.
successfulLogin = true;
// Log the creation.
Grasscutter.getLogger().info(translate("messages.dispatch.account.account_login_create_success", address, response.data.account.uid));
}
} else if(account != null)
successfulLogin = true;
else
loggerMessage = translate("messages.dispatch.account.account_login_exist_error", address);
} else {
responseMessage = translate("messages.dispatch.account.server_max_player_limit");
loggerMessage = translate("messages.dispatch.account.login_max_player_limit", address);
}
// Set response data.
if(successfulLogin) {
response.message = "OK";
response.data.account.uid = account.getId();
response.data.account.token = account.generateSessionKey();
response.data.account.email = account.getEmail();
loggerMessage = translate("messages.dispatch.account.login_success", address, account.getId());
} else {
response.retcode = -201;
response.message = responseMessage;
}
Grasscutter.getLogger().info(loggerMessage);
return response;
}
}
/**
* Handles the authentication request from the game when using a registry token.
*/
public static class TokenAuthenticator implements Authenticator<LoginResultJson> {
@Override public LoginResultJson authenticate(AuthenticationRequest request) {
var response = new LoginResultJson();
var requestData = request.getTokenRequest();
assert requestData != null;
boolean successfulLogin;
String address = request.getRequest().ip();
String loggerMessage;
int playerCount = Grasscutter.getGameServer().getPlayers().size();
// Log the attempt.
Grasscutter.getLogger().info(translate("messages.dispatch.account.login_token_attempt", address));
if (ACCOUNT.maxPlayer <= -1 || playerCount < ACCOUNT.maxPlayer) {
// Get account from database.
Account account = DatabaseHelper.getAccountById(requestData.uid);
// Check if account exists/token is valid.
successfulLogin = account != null && account.getSessionKey().equals(requestData.token);
// Set response data.
if(successfulLogin) {
response.message = "OK";
response.data.account.uid = account.getId();
response.data.account.token = account.getSessionKey();
response.data.account.email = account.getEmail();
// Log the login.
loggerMessage = translate("messages.dispatch.account.login_token_success", address, requestData.uid);
} else {
response.retcode = -201;
response.message = translate("messages.dispatch.account.account_cache_error");
// Log the failure.
loggerMessage = translate("messages.dispatch.account.login_token_error", address);
}
} else {
response.retcode = -201;
response.message = translate("messages.dispatch.account.server_max_player_limit");
loggerMessage = translate("messages.dispatch.account.login_max_player_limit", address);
}
Grasscutter.getLogger().info(loggerMessage);
return response;
}
}
/**
* Handles the authentication request from the game when using a combo token/session key.
*/
public static class SessionKeyAuthenticator implements Authenticator<ComboTokenResJson> {
@Override public ComboTokenResJson authenticate(AuthenticationRequest request) {
var response = new ComboTokenResJson();
var requestData = request.getSessionKeyRequest();
var loginData = request.getSessionKeyData();
assert requestData != null; assert loginData != null;
boolean successfulLogin;
String address = request.getRequest().ip();
String loggerMessage;
int playerCount = Grasscutter.getGameServer().getPlayers().size();
if (ACCOUNT.maxPlayer <= -1 || playerCount < ACCOUNT.maxPlayer) {
// Get account from database.
Account account = DatabaseHelper.getAccountById(loginData.uid);
// Check if account exists/token is valid.
successfulLogin = account != null && account.getSessionKey().equals(loginData.token);
// Set response data.
if(successfulLogin) {
response.message = "OK";
response.data.open_id = account.getId();
response.data.combo_id = "157795300";
response.data.combo_token = account.generateLoginToken();
// Log the login.
loggerMessage = translate("messages.dispatch.account.combo_token_success", address);
} else {
response.retcode = -201;
response.message = translate("messages.dispatch.account.session_key_error");
// Log the failure.
loggerMessage = translate("messages.dispatch.account.combo_token_error", address);
}
} else {
response.retcode = -201;
response.message = translate("messages.dispatch.account.server_max_player_limit");
loggerMessage = translate("messages.dispatch.account.login_max_player_limit", address);
}
Grasscutter.getLogger().info(loggerMessage);
return response;
}
}
/**
* Handles authentication requests from external sources.
*/
public static class ExternalAuthentication implements ExternalAuthenticator {
@Override public void handleLogin(AuthenticationRequest request) {
assert request.getResponse() != null;
request.getResponse().send("Authentication is not available with the default authentication method.");
}
@Override public void handleAccountCreation(AuthenticationRequest request) {
assert request.getResponse() != null;
request.getResponse().send("Authentication is not available with the default authentication method.");
}
@Override public void handlePasswordReset(AuthenticationRequest request) {
assert request.getResponse() != null;
request.getResponse().send("Authentication is not available with the default authentication method.");
}
}
/**
* Handles authentication requests from OAuth sources.
*/
public static class OAuthAuthentication implements OAuthAuthenticator {
@Override public void handleLogin(AuthenticationRequest request) {
assert request.getResponse() != null;
request.getResponse().send("Authentication is not available with the default authentication method.");
}
@Override public void handleRedirection(AuthenticationRequest request, ClientType type) {
assert request.getResponse() != null;
request.getResponse().send("Authentication is not available with the default authentication method.");
}
@Override public void handleTokenProcess(AuthenticationRequest request) {
assert request.getResponse() != null;
request.getResponse().send("Authentication is not available with the default authentication method.");
}
}
}
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