├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── main │ ├── java │ │ └── com │ │ │ └── catkatpowered │ │ │ └── katserver │ │ │ ├── event │ │ │ ├── Event.java │ │ │ ├── interfaces │ │ │ │ ├── Listener.java │ │ │ │ ├── EventHandler.java │ │ │ │ ├── Cancellable.java │ │ │ │ └── Blockable.java │ │ │ ├── events │ │ │ │ ├── CustomPacketReceiveEvent.java │ │ │ │ ├── MessageReceiveEvent.java │ │ │ │ └── MessageSendEvent.java │ │ │ ├── EventPriority.java │ │ │ ├── RegisteredHandler.java │ │ │ ├── RegisteredListener.java │ │ │ ├── KatEventManager.java │ │ │ └── EventBus.java │ │ │ ├── common │ │ │ ├── utils │ │ │ │ ├── KatClassScanner.java │ │ │ │ ├── KatFile.java │ │ │ │ ├── KatWorkSpace.java │ │ │ │ ├── KatDownload.java │ │ │ │ ├── KatShaUtils.java │ │ │ │ └── ReflectionSweet.java │ │ │ └── constants │ │ │ │ ├── KatStorageTypeConstants.java │ │ │ │ ├── KatPacketTypeConstants.java │ │ │ │ ├── KatMessageTypeConstants.java │ │ │ │ ├── KatMiscConstants.java │ │ │ │ └── KatConfigNodeConstants.java │ │ │ ├── database │ │ │ ├── interfaces │ │ │ │ ├── DatabaseConnector.java │ │ │ │ └── DatabaseConnection.java │ │ │ ├── KatDatabase.java │ │ │ ├── mongodb │ │ │ │ ├── MongodbConnector.java │ │ │ │ └── MongodbConnection.java │ │ │ └── KatDatabaseManager.java │ │ │ ├── network │ │ │ ├── websocket │ │ │ │ ├── packet │ │ │ │ │ ├── BasePacket.java │ │ │ │ │ ├── ErrorPacket.java │ │ │ │ │ ├── CustomPacket.java │ │ │ │ │ ├── WebSocketMessagePacket.java │ │ │ │ │ ├── ServerDescriptionPacket.java │ │ │ │ │ └── WebsocketMessageQueryPacket.java │ │ │ │ ├── KatWebSocketBroadcast.java │ │ │ │ └── KatWebSocketIncome.java │ │ │ ├── KatNetworkManager.java │ │ │ ├── http │ │ │ │ ├── HttpGetHandler.java │ │ │ │ └── HttpPostHandler.java │ │ │ ├── KatNetwork.java │ │ │ └── utils │ │ │ │ └── KatCertUtil.java │ │ │ ├── extension │ │ │ ├── event │ │ │ │ ├── LoadExtensionEvent.java │ │ │ │ ├── EnableExtensionEvent.java │ │ │ │ ├── DisableExtensionEvent.java │ │ │ │ └── ExtensionEvent.java │ │ │ ├── KatExtensionInfo.java │ │ │ ├── KatExtension.java │ │ │ ├── KatExtensionManager.java │ │ │ └── KatExtensionLoader.java │ │ │ ├── message │ │ │ ├── KatUniMessageTypeManager.java │ │ │ ├── KatUniMessageType.java │ │ │ └── KatUniMessage.java │ │ │ ├── tokenpool │ │ │ ├── KatTokenPoolManager.java │ │ │ └── KatTokenPool.java │ │ │ ├── storage │ │ │ ├── README.md │ │ │ ├── providers │ │ │ │ ├── KatStorageProvider.java │ │ │ │ └── local │ │ │ │ │ └── LocalProvider.java │ │ │ ├── KatStorage.java │ │ │ ├── KatStorageManager.java │ │ │ └── KatMessageStorage.java │ │ │ ├── task │ │ │ ├── KatTaskManager.java │ │ │ └── KatTask.java │ │ │ ├── KatServerMain.java │ │ │ ├── config │ │ │ ├── KatConfigManager.java │ │ │ └── KatConfig.java │ │ │ └── KatServer.java │ └── resources │ │ ├── config.toml │ │ └── log4j2.xml └── test │ └── java │ └── com │ └── catkatpowered │ └── katserver │ ├── common │ └── utils │ │ └── TestShaUtils.java │ ├── event │ └── TestEventBus.java │ ├── tokenpool │ └── TestKatTokenPool.java │ ├── database │ └── TestMongoDBDatabase.java │ ├── config │ └── TestKatConfig.java │ └── network │ └── TestKatNetwork.java ├── .gitignore ├── .github └── workflows │ ├── verify.yml │ ├── test-event.yml │ ├── test-config.yml │ ├── test-utils.yml │ ├── test-tokenpool.yml │ ├── repository.yml │ ├── test-network.yml │ └── test-database.yml ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'kat-server' 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CatkatPowered/kat-server/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/Event.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event; 2 | 3 | @SuppressWarnings("unused") 4 | public class Event {} 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # IDE 2 | .idea/ 3 | .vscode/ 4 | 5 | # Gradle 6 | .gradle/ 7 | build/ 8 | 9 | # Other 10 | bin/ 11 | 12 | # Project 13 | logs/ 14 | data/ 15 | config.toml -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/interfaces/Listener.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event.interfaces; 2 | 3 | @SuppressWarnings("unused") 4 | public interface Listener {} 5 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/utils/KatClassScanner.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.utils; 2 | 3 | /** 4 | * 扫包工具 用于扫描某个包下特定类型的类 5 | */ 6 | public class KatClassScanner {} 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/test/java/com/catkatpowered/katserver/common/utils/TestShaUtils.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.utils; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | public class TestShaUtils { 6 | 7 | @Test 8 | public void sha256() {} 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/constants/KatStorageTypeConstants.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.constants; 2 | 3 | public class KatStorageTypeConstants { 4 | 5 | public static final String KAT_STORAGE_PROVIDER_LOCAL = "local"; 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/database/interfaces/DatabaseConnector.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.database.interfaces; 2 | 3 | public interface DatabaseConnector { 4 | void open(); 5 | 6 | void close(); 7 | 8 | DatabaseConnection connection(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/websocket/packet/BasePacket.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.websocket.packet; 2 | 3 | import lombok.Data; 4 | 5 | // BasePacket只被用来继承 6 | @Data 7 | public class BasePacket { 8 | 9 | String type; 10 | 11 | public BasePacket(String type) { 12 | this.type = type; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/extension/event/LoadExtensionEvent.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.extension.event; 2 | 3 | import com.catkatpowered.katserver.extension.KatExtensionInfo; 4 | 5 | public class LoadExtensionEvent extends ExtensionEvent { 6 | 7 | public LoadExtensionEvent(KatExtensionInfo extensionInfo) { 8 | super(extensionInfo); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/extension/event/EnableExtensionEvent.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.extension.event; 2 | 3 | import com.catkatpowered.katserver.extension.KatExtensionInfo; 4 | 5 | public class EnableExtensionEvent extends ExtensionEvent { 6 | 7 | public EnableExtensionEvent(KatExtensionInfo extensionInfo) { 8 | super(extensionInfo); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/extension/event/DisableExtensionEvent.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.extension.event; 2 | 3 | import com.catkatpowered.katserver.extension.KatExtensionInfo; 4 | 5 | public class DisableExtensionEvent extends ExtensionEvent { 6 | 7 | public DisableExtensionEvent(KatExtensionInfo extensionInfo) { 8 | super(extensionInfo); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/message/KatUniMessageTypeManager.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.message; 2 | 3 | public class KatUniMessageTypeManager { 4 | 5 | public static boolean addMessageType(String msgType) { 6 | return KatUniMessageType.getInstance().addNewMessageType(msgType); 7 | } 8 | 9 | @Deprecated 10 | public static KatUniMessageType getInstance() { 11 | return KatUniMessageType.getInstance(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/events/CustomPacketReceiveEvent.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event.events; 2 | 3 | import com.catkatpowered.katserver.event.Event; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.EqualsAndHashCode; 7 | 8 | @Data 9 | @Builder 10 | @EqualsAndHashCode(callSuper = false) 11 | public class CustomPacketReceiveEvent extends Event { 12 | 13 | String extensionId; 14 | Object content; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/events/MessageReceiveEvent.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event.events; 2 | 3 | import com.catkatpowered.katserver.event.Event; 4 | import com.catkatpowered.katserver.message.KatUniMessage; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.EqualsAndHashCode; 8 | 9 | @Data 10 | @Builder 11 | @EqualsAndHashCode(callSuper = false) 12 | public class MessageReceiveEvent extends Event { 13 | 14 | KatUniMessage message; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/interfaces/EventHandler.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event.interfaces; 2 | 3 | import com.catkatpowered.katserver.event.EventPriority; 4 | import java.lang.annotation.*; 5 | 6 | @Documented 7 | @Retention(RetentionPolicy.RUNTIME) 8 | @Target(ElementType.METHOD) 9 | @SuppressWarnings("unused") 10 | public @interface EventHandler { 11 | EventPriority priority() default EventPriority.NORMAL; 12 | 13 | boolean ignoreCancelled() default false; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/extension/event/ExtensionEvent.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.extension.event; 2 | 3 | import com.catkatpowered.katserver.event.Event; 4 | import com.catkatpowered.katserver.extension.KatExtensionInfo; 5 | import lombok.Getter; 6 | 7 | public class ExtensionEvent extends Event { 8 | 9 | @Getter 10 | KatExtensionInfo extensionInfo; 11 | 12 | public ExtensionEvent(KatExtensionInfo extensionInfo) { 13 | this.extensionInfo = extensionInfo; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/events/MessageSendEvent.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event.events; 2 | 3 | import com.catkatpowered.katserver.event.Event; 4 | import com.catkatpowered.katserver.message.KatUniMessage; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.EqualsAndHashCode; 8 | 9 | @Data 10 | @Builder 11 | @EqualsAndHashCode(callSuper = false) 12 | public class MessageSendEvent extends Event { 13 | 14 | String extensionId; 15 | KatUniMessage message; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/extension/KatExtensionInfo.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.extension; 2 | 3 | import java.util.List; 4 | import lombok.Data; 5 | 6 | /** 7 | * 实体类 存放扩展描述文件 8 | */ 9 | @Data 10 | public class KatExtensionInfo { 11 | 12 | // 扩展主函数 13 | public String main; 14 | // 扩展名 15 | public String extension; 16 | // 扩展版本 17 | public String version; 18 | // 扩展网站 19 | public String website; 20 | // 扩展作者 21 | public List author; 22 | // 扩展依赖 23 | public List depend; 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/interfaces/Cancellable.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event.interfaces; 2 | 3 | /** 4 | * 一个 Event 接口, 实现该接口标识事件可以取消
5 | * 请注意这一个设计, 取消并不意味这事件会在 setCancelled(true) 后停止向下一个事件处理器传播
6 | * 如果事件处理器的注解中 ignoreCancelled 值为 true, 事件处理器将会被正常触发
7 | * 反之则不会被触发, 完全阻断事件请使用 com.catkatpowered.katserver.event.interfaces.Blockable 接口 8 | */ 9 | @SuppressWarnings("unused SpellCheckingInspection") 10 | public interface Cancellable { 11 | boolean isCancelled(); 12 | 13 | void setCancelled(boolean cancel); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/interfaces/Blockable.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event.interfaces; 2 | 3 | /** 4 | * 一个 Event 接口, 实现该接口标识事件可以阻断
5 | * 使用 setBlocked(true) 来完全阻断事件, 即使事件处理器的注解中 ignoreCancelled 值为 false
6 | * 事实上, 在 setBlocked(true) 后其他优先级比当前事件处理器低的处理器将被忽略, 直接结束当前一次 callEvent
7 | * 如果不是必要的, 仍推荐使用 com.catkatpowered.katserver.event.interfaces.Cancellable 接口 8 | */ 9 | @SuppressWarnings("unused SpellCheckingInspection") 10 | public interface Blockable { 11 | boolean isBlocked(); 12 | 13 | void setBlocked(boolean block); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/database/KatDatabase.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.database; 2 | 3 | import com.catkatpowered.katserver.database.interfaces.DatabaseConnector; 4 | 5 | public class KatDatabase { 6 | 7 | @SuppressWarnings("all") 8 | private static final KatDatabase Instance = new KatDatabase(); 9 | 10 | DatabaseConnector connector; 11 | 12 | public static KatDatabase getInstance() { 13 | return Instance; 14 | } 15 | 16 | public void register(DatabaseConnector connector) { 17 | this.connector = connector; 18 | this.connector.open(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/constants/KatPacketTypeConstants.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.constants; 2 | 3 | public class KatPacketTypeConstants { 4 | 5 | public static final String RESOURCE_TOKEN_PACKET = "resource_token"; 6 | public static final String MESSAGE_PACKET = "websocket_message"; 7 | public static final String MESSAGE_QUERY_PACKET = "websocket_message_query"; 8 | public static final String SERVER_DESCRIPTION_PACKET = "server_description"; 9 | public static final String ERROR_PACKET = "error"; 10 | public static final String CUSTOM_PACKET = "custom"; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/websocket/packet/ErrorPacket.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.websocket.packet; 2 | 3 | import com.catkatpowered.katserver.common.constants.KatPacketTypeConstants; 4 | import com.google.gson.annotations.SerializedName; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | 8 | @Data 9 | @Builder 10 | public class ErrorPacket { 11 | 12 | // 错误信息 13 | @SerializedName("error") 14 | String error; 15 | 16 | // 包类型 17 | final String type = KatPacketTypeConstants.ERROR_PACKET; 18 | 19 | public ErrorPacket(String error) { 20 | this.error = error; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/EventPriority.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event; 2 | 3 | /** 4 | * 很高兴的告诉您, 我在抄bukkit的同时
5 | * 把这个反人类设计一起抄过来了
6 | * 这个枚举使用在 @EventHandler 注解的 priority 参数中
7 | * 序号越大的优先级越低, 请不要被字面意思迷惑
8 | * 简单来说, LOWEST 优先级最高, 是第一个被触发的等级, MONITOR 优先级最低, 是最后一个被触发的等级

9 | * 1. LOWEST
10 | * 2. LOW
11 | * 3. NORMAL (default)
12 | * 4. HIGH
13 | * 5. HIGHEST
14 | * 6. MONITOR
15 | */ 16 | @SuppressWarnings("unused") 17 | public enum EventPriority { 18 | LOWEST, 19 | LOW, 20 | NORMAL, 21 | HIGH, 22 | HIGHEST, 23 | MONITOR, 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/KatNetworkManager.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network; 2 | 3 | import com.catkatpowered.katserver.event.KatEventManager; 4 | import com.catkatpowered.katserver.network.websocket.KatWebSocketBroadcast; 5 | import io.javalin.Javalin; 6 | 7 | public class KatNetworkManager { 8 | 9 | @SuppressWarnings("ResultOfMethodCallIgnored") 10 | public static void init() { 11 | KatNetwork.getInstance(); 12 | KatEventManager.registerListener(new KatWebSocketBroadcast()); 13 | } 14 | 15 | public static Javalin getNetworkServer() { 16 | return KatNetwork.getNetwork(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/websocket/packet/CustomPacket.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.websocket.packet; 2 | 3 | import com.catkatpowered.katserver.common.constants.KatPacketTypeConstants; 4 | import com.google.gson.annotations.SerializedName; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | 8 | @Data 9 | @Builder 10 | public class CustomPacket { 11 | 12 | @SerializedName("type") 13 | private final String type = KatPacketTypeConstants.CUSTOM_PACKET; 14 | 15 | // 扩展名,用于将包传递给相应的扩展处理 16 | @SerializedName("extension_id") 17 | String extensionId; 18 | 19 | @SerializedName("content") 20 | Object content; 21 | } 22 | -------------------------------------------------------------------------------- /.github/workflows/verify.yml: -------------------------------------------------------------------------------- 1 | name: Verify Build 2 | 3 | on: 4 | push: 5 | branches: [main, ci] 6 | pull_request: 7 | branches: [main, ci] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | if: "! contains(github.event.head_commit.message, '#Skip')" 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up JDK 17 17 | uses: actions/setup-java@v3 18 | with: 19 | java-version: 17 20 | distribution: adopt 21 | 22 | - name: Grant execute permission for gradlew 23 | run: chmod +x gradlew 24 | 25 | - name: Build with Gradle (build) 26 | run: ./gradlew build -x test 27 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/tokenpool/KatTokenPoolManager.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.tokenpool; 2 | 3 | public class KatTokenPoolManager { 4 | 5 | public static void init() {} 6 | 7 | public static String newToken() { 8 | return KatTokenPool.getINSTANCE().newToken(); 9 | } 10 | 11 | public static boolean revokeToken(String tokeString) { 12 | return KatTokenPool.getINSTANCE().destroyToken(tokeString); 13 | } 14 | 15 | public static boolean checkToken(String token) { 16 | return KatTokenPool.getINSTANCE().checkToken(token); 17 | } 18 | 19 | public static KatTokenPool getInstance() { 20 | return KatTokenPool.getINSTANCE(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/extension/KatExtension.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.extension; 2 | 3 | /** 4 | * 定义一个 Kat Server 扩展
5 | * 加载顺序 onLoad -> onEnable -> onDisable
6 | * 在 onLoad 过程核心会读取扩展的依赖 检查扩展是否符合标准 检查扩展权限
7 | * 抽象类应向扩展提供已经实现的 API 方法 由扩展实现抽象方法提供给核心调用 8 | *
9 | *

10 | * 日志推荐使用@Slf4j注解 11 | * 12 | * @author hanbings 13 | * @author suibing112233 14 | */ 15 | @SuppressWarnings("unused") 16 | public interface KatExtension { 17 | /** 18 | * 在插件被时执行此方法 抽象方法 由扩展实现 19 | */ 20 | void onLoad(); 21 | 22 | /** 23 | * 在插件被开启时执行此方法 抽象方法 由扩展实现 24 | */ 25 | void onEnable(); 26 | 27 | /** 28 | * 在插件被卸载时执行此方法 抽象方法 由扩展实现 29 | */ 30 | void onDisable(); 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/constants/KatMessageTypeConstants.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.constants; 2 | 3 | public class KatMessageTypeConstants { 4 | 5 | public static final String KAT_MESSAGE_TYPE_PLAIN_MESSAGE = "PlainMessage"; 6 | public static final String KAT_MESSAGE_TYPE_COLLECTION_MESSAGE = 7 | "CollectionMessage"; 8 | public static final String KAT_MESSAGE_TYPE_IMAGE_MESSAGE = "ImageMessage"; 9 | public static final String KAT_MESSAGE_TYPE_FILE_MESSAGE = "FileMessage"; 10 | public static final String KAT_MESSAGE_TYPE_AUDIO_MESSAGE = "AudioMessage"; 11 | public static final String KAT_MESSAGE_TYPE_VIDEO_MESSAGE = "VideoMessage"; 12 | public static final String KAT_MESSAGE_TYPE_MIXED_MESSAGE = "MixedMessage"; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/websocket/packet/WebSocketMessagePacket.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.websocket.packet; 2 | 3 | import com.catkatpowered.katserver.common.constants.KatPacketTypeConstants; 4 | import com.catkatpowered.katserver.message.KatUniMessage; 5 | import com.google.gson.annotations.SerializedName; 6 | import lombok.Builder; 7 | import lombok.Data; 8 | 9 | @Data 10 | @Builder 11 | public class WebSocketMessagePacket { 12 | 13 | /* 14 | { 15 | "type": "websocket_message", 16 | "message": {} 17 | } 18 | */ 19 | // 消息本体 20 | @SerializedName("message") 21 | KatUniMessage message; 22 | 23 | // 数据包类型 24 | @SerializedName("type") 25 | final String type = KatPacketTypeConstants.MESSAGE_PACKET; 26 | 27 | public WebSocketMessagePacket(KatUniMessage message) { 28 | this.message = message; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /.github/workflows/test-event.yml: -------------------------------------------------------------------------------- 1 | name: Tests for EventBus 2 | 3 | on: 4 | push: 5 | branches: [main, ci] 6 | pull_request: 7 | branches: [main, ci] 8 | 9 | jobs: 10 | config: 11 | runs-on: ubuntu-latest 12 | if: "! contains(github.event.head_commit.message, '#Skip')" 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up JDK 17 17 | uses: actions/setup-java@v3 18 | with: 19 | java-version: 17 20 | distribution: adopt 21 | 22 | - name: Grant execute permission for gradlew 23 | run: chmod +x gradlew 24 | 25 | - name: Run Gradle test 26 | run: ./gradlew test -i --tests --stacktrace "com.catkatpowered.katserver.event.TestEventBus" 27 | 28 | - name: Upload fail reports 29 | uses: actions/upload-artifact@v3 30 | if: failure() 31 | with: 32 | name: event-test-failure 33 | path: build/reports 34 | -------------------------------------------------------------------------------- /.github/workflows/test-config.yml: -------------------------------------------------------------------------------- 1 | name: Tests for Config 2 | 3 | on: 4 | push: 5 | branches: [main, ci] 6 | pull_request: 7 | branches: [main, ci] 8 | 9 | jobs: 10 | config: 11 | runs-on: ubuntu-latest 12 | if: "! contains(github.event.head_commit.message, '#Skip')" 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up JDK 17 17 | uses: actions/setup-java@v3 18 | with: 19 | java-version: 17 20 | distribution: adopt 21 | 22 | - name: Grant execute permission for gradlew 23 | run: chmod +x gradlew 24 | 25 | - name: Run Gradle test 26 | run: ./gradlew test -i --tests --stacktrace "com.catkatpowered.katserver.config.TestKatConfig" 27 | 28 | - name: Upload fail reports 29 | uses: actions/upload-artifact@v3 30 | if: failure() 31 | with: 32 | name: config-test-failure 33 | path: build/reports 34 | -------------------------------------------------------------------------------- /.github/workflows/test-utils.yml: -------------------------------------------------------------------------------- 1 | name: Tests for Utils 2 | 3 | on: 4 | push: 5 | branches: [main, ci] 6 | pull_request: 7 | branches: [main, ci] 8 | 9 | jobs: 10 | sha-utils: 11 | runs-on: ubuntu-latest 12 | if: "! contains(github.event.head_commit.message, '#Skip')" 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up JDK 17 17 | uses: actions/setup-java@v3 18 | with: 19 | java-version: 17 20 | distribution: adopt 21 | 22 | - name: Grant execute permission for gradlew 23 | run: chmod +x gradlew 24 | 25 | - name: Run Gradle test 26 | run: ./gradlew test -i --tests --stacktrace "com.catkatpowered.katserver.common.utils.TestShaUtils" 27 | 28 | - name: Upload fail reports 29 | uses: actions/upload-artifact@v3 30 | if: failure() 31 | with: 32 | name: sha-utils-test-failure 33 | path: build/reports 34 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/utils/KatFile.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.utils; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.net.URI; 6 | 7 | public class KatFile extends File { 8 | 9 | public KatFile(File parent, String child) { 10 | super(parent, child); 11 | } 12 | 13 | public KatFile(String pathname) { 14 | super(pathname); 15 | } 16 | 17 | public KatFile(String parent, String child) { 18 | super(parent, child); 19 | } 20 | 21 | public KatFile(URI uri) { 22 | super(uri); 23 | } 24 | 25 | public boolean lock() { 26 | try { 27 | (new File(super.getAbsolutePath() + ".lock")).createNewFile(); 28 | } catch (IOException e) { 29 | e.printStackTrace(); 30 | return false; 31 | } 32 | return true; 33 | } 34 | 35 | public boolean unlock() { 36 | return (new File(super.getAbsolutePath() + ".lock")).delete(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /.github/workflows/test-tokenpool.yml: -------------------------------------------------------------------------------- 1 | name: Tests for TokenPool 2 | 3 | on: 4 | push: 5 | branches: [main, ci] 6 | pull_request: 7 | branches: [main, ci] 8 | 9 | jobs: 10 | tokenpool: 11 | runs-on: ubuntu-latest 12 | if: "! contains(github.event.head_commit.message, '#Skip')" 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up JDK 17 17 | uses: actions/setup-java@v3 18 | with: 19 | java-version: 17 20 | distribution: adopt 21 | 22 | - name: Grant execute permission for gradlew 23 | run: chmod +x gradlew 24 | 25 | - name: Run Gradle test 26 | run: ./gradlew test -i --tests --stacktrace "com.catkatpowered.katserver.tokenpool.TestKatTokenPool" 27 | 28 | - name: Upload fail reports 29 | uses: actions/upload-artifact@v3 30 | if: failure() 31 | with: 32 | name: tokenpool-test-failure 33 | path: build/reports 34 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/storage/README.md: -------------------------------------------------------------------------------- 1 | # KatStorage 2 | 3 | KatServer 的储存模块,负责储存各种资源文件,例如从 IM 服务器缓存下来的语音、文件、图片等 4 | 5 | ## 替换能力 6 | 7 | **注意:储存模块不可以混合使用。若使用本地储存模块应当一直使用本地储存模块。** 8 | 9 | 本模块允许被替换,可以通过实现 `KatStorageProvider` 接口最终通过 `KatServer.KatStorageAPI.registerStorageProvider()` 方法完成注册 10 | 11 | 本模块通过配置配置文件中 `resource.storage_provider` 配置节点写入 `KatStorage` 实现者名称切换储存提供者 12 | 13 | ## 内置与默认 14 | 15 | 目前内置以下储存提供者,带`*`则为默认 16 | 17 | - \*local 18 | 19 | ## 实现细节 20 | 21 | ### `StorageProvider` 管理与切换 22 | 23 | 使用 Map 数据结构管理 `StorageProvider` ,Key 为实现的 `StorageProvider` 的名称,`KatStorage` 会根据在配置文件中填写的储存提供者名称在 Map 数据结构中查找对应实现 `KatStorageProvider` 的储存提供者 24 | 25 | ### 默认约定 26 | 27 | - 模块对文件名不敏感,不会用到任何文件名相关的内容 28 | - 模块使用 Hash 实现对文件的储存等,例如文件 Hash 为 `6f8483c9942d8368a301879b49935111a9b7278f79890d49f91391ec765cb129` 则其储存路径为`{DATA_DIRECTORY}/6f/84/6f8483c9942d8368a301879b49935111a9b7278f79890d49f91391ec765cb129` 29 | - `fetch()` 方法返回值若 `Optional` 为空则无法获取文件 30 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/task/KatTaskManager.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.task; 2 | 3 | import java.util.concurrent.Callable; 4 | import java.util.concurrent.Future; 5 | 6 | /** 7 | * @author Krysztal 8 | * @author hanbings 9 | */ 10 | public class KatTaskManager { 11 | 12 | public static void init() { 13 | KatTask.getInstance(); 14 | } 15 | 16 | public static Future addTask(Runnable task) { 17 | return KatTask.getInstance().addTask(task); 18 | } 19 | 20 | public static Future addTask(Callable task) { 21 | return KatTask.getInstance().addTask(task); 22 | } 23 | 24 | public static Future addTask(Runnable task, T result) { 25 | return KatTask.getInstance().addTask(task, result); 26 | } 27 | 28 | public static void exec(Runnable task) { 29 | KatTask.getInstance().exec(task); 30 | } 31 | 32 | @Deprecated 33 | public static KatTask getInstance() { 34 | return KatTask.getInstance(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/utils/KatWorkSpace.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.utils; 2 | 3 | import com.catkatpowered.katserver.common.constants.KatMiscConstants; 4 | import java.nio.file.Path; 5 | 6 | /** 7 | * KatServer 的工作目录有两种情况 8 | * 9 | *

  • 如果定义了 KAT_ENV_WORKING_DIR 环境变量,则 KatServer 的工作目录由环境变量确定。
  • 10 | *
  • 如果未定义 KAT_ENV_WORKING_DIR 环境变量,则 KatServer 的工作目录是程序运行目录。
  • 11 | * 12 | * @author Krysztal 13 | * @author CatMoe 14 | * @author hanbings 15 | */ 16 | public class KatWorkSpace { 17 | 18 | public static String getWorkingDir() { 19 | var workingDir = System.getenv().get(KatMiscConstants.KAT_ENV_WORKING_DIR); 20 | return workingDir == null || workingDir.isEmpty() 21 | ? System.getProperty("user.dir") 22 | : workingDir; 23 | } 24 | 25 | public static String fixPath(String path) { 26 | return Path.of(path).isAbsolute() 27 | ? path 28 | : KatWorkSpace.getWorkingDir() + path; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /.github/workflows/repository.yml: -------------------------------------------------------------------------------- 1 | name: Maven Publish 2 | 3 | on: 4 | push: 5 | branches: [main, ci] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | if: "! contains(github.event.head_commit.message, '#Skip')" 11 | steps: 12 | - uses: actions/checkout@v3 13 | 14 | publish: 15 | runs-on: ubuntu-latest 16 | if: "contains(github.event.head_commit.message, '#Publish')" 17 | steps: 18 | - uses: actions/checkout@v3 19 | 20 | - name: Set up JDK 17 21 | uses: actions/setup-java@v3 22 | with: 23 | java-version: 17 24 | distribution: adopt 25 | 26 | - name: Grant execute permission for gradlew 27 | run: chmod +x gradlew 28 | 29 | - name: Build with Gradle (build) 30 | run: ./gradlew build 31 | 32 | - name: Build with Gradle (publish) 33 | run: ./gradlew publish 34 | env: 35 | REPOSITORY_ROOT_URL: ${{ secrets.REPOSITORY_ROOT_URL }} 36 | REPOSITORY_USER: ${{ secrets.REPOSITORY_USER }} 37 | REPOSITORY_TOKEN: ${{ secrets.REPOSITORY_TOKEN }} 38 | -------------------------------------------------------------------------------- /.github/workflows/test-network.yml: -------------------------------------------------------------------------------- 1 | name: Tests for Network 2 | 3 | on: 4 | push: 5 | branches: [main, ci] 6 | pull_request: 7 | branches: [main, ci] 8 | 9 | jobs: 10 | config: 11 | runs-on: ubuntu-latest 12 | if: "! contains(github.event.head_commit.message, '#Skip')" 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up JDK 17 17 | uses: actions/setup-java@v3 18 | with: 19 | java-version: 17 20 | distribution: adopt 21 | 22 | - name: Set up MongoDB 4.4 23 | uses: supercharge/mongodb-github-action@1.7.0 24 | with: 25 | mongodb-version: 4.4 26 | 27 | - name: Grant execute permission for gradlew 28 | run: chmod +x gradlew 29 | 30 | - name: Run Gradle test 31 | run: ./gradlew test -i --tests --stacktrace "com.catkatpowered.katserver.network.TestKatNetwork" 32 | 33 | - name: Upload fail reports 34 | uses: actions/upload-artifact@v3 35 | if: failure() 36 | with: 37 | name: network-test-failure 38 | path: build/reports 39 | -------------------------------------------------------------------------------- /.github/workflows/test-database.yml: -------------------------------------------------------------------------------- 1 | name: Tests for Database 2 | 3 | on: 4 | push: 5 | branches: [main, ci] 6 | pull_request: 7 | branches: [main, ci] 8 | 9 | jobs: 10 | mongodb: 11 | runs-on: ubuntu-latest 12 | if: "! contains(github.event.head_commit.message, '#Skip')" 13 | steps: 14 | - uses: actions/checkout@v3 15 | 16 | - name: Set up JDK 17 17 | uses: actions/setup-java@v3 18 | with: 19 | java-version: 17 20 | distribution: adopt 21 | 22 | - name: Set up MongoDB 4.4 23 | uses: supercharge/mongodb-github-action@1.7.0 24 | with: 25 | mongodb-version: 4.4 26 | 27 | - name: Grant execute permission for gradlew 28 | run: chmod +x gradlew 29 | 30 | - name: Run Gradle test 31 | run: ./gradlew test -i --tests --stacktrace "com.catkatpowered.katserver.database.TestMongoDBDatabase" 32 | 33 | - name: Upload fail reports 34 | uses: actions/upload-artifact@v3 35 | if: failure() 36 | with: 37 | name: mongodb-test-failure 38 | path: build/reports 39 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/RegisteredHandler.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event; 2 | 3 | import com.catkatpowered.katserver.event.interfaces.Listener; 4 | import java.lang.reflect.Method; 5 | 6 | @SuppressWarnings("unused") 7 | public class RegisteredHandler { 8 | 9 | private EventPriority priority; 10 | private boolean ignoreCancelled; 11 | private Listener listener; 12 | private Method method; 13 | 14 | private RegisteredHandler() {} 15 | 16 | public RegisteredHandler( 17 | EventPriority priority, 18 | boolean ignoreCancelled, 19 | Listener listener, 20 | Method method 21 | ) { 22 | this.priority = priority; 23 | this.ignoreCancelled = ignoreCancelled; 24 | this.listener = listener; 25 | this.method = method; 26 | } 27 | 28 | public EventPriority getPriority() { 29 | return priority; 30 | } 31 | 32 | public boolean isIgnoreCancelled() { 33 | return ignoreCancelled; 34 | } 35 | 36 | public Listener getListener() { 37 | return listener; 38 | } 39 | 40 | public Method getMethod() { 41 | return method; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/http/HttpGetHandler.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.http; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.google.gson.Gson; 5 | import com.google.gson.annotations.SerializedName; 6 | import io.javalin.http.Context; 7 | import io.javalin.http.Handler; 8 | import lombok.Data; 9 | import org.jetbrains.annotations.NotNull; 10 | 11 | public class HttpGetHandler implements Handler { 12 | 13 | Gson gson = new Gson(); 14 | 15 | @Override 16 | public void handle(@NotNull Context ctx) throws Exception { 17 | HttpRequestBody body = gson.fromJson( 18 | new String(ctx.body().getBytes()), 19 | HttpRequestBody.class 20 | ); 21 | if (KatServer.KatTokenPoolAPI.checkToken(body.getResourceToken())) { 22 | // 直接用stream传递,用流发送给mosseger端 23 | ctx.result(KatServer.KatStorageAPI.fetch(body.getResourceHash())); 24 | } 25 | } 26 | } 27 | 28 | @Data 29 | class HttpRequestBody { 30 | 31 | @SerializedName("resource_token") 32 | private String resourceToken; 33 | 34 | @SerializedName("resource_hash") 35 | private String resourceHash; 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/storage/providers/KatStorageProvider.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.storage.providers; 2 | 3 | import com.catkatpowered.katserver.common.utils.KatShaUtils; 4 | import java.io.InputStream; 5 | import org.jetbrains.annotations.Nullable; 6 | 7 | /** 8 | * @author Krysztal 9 | */ 10 | public interface KatStorageProvider { 11 | /** 12 | * 获取资源 13 | * 14 | * @param hashString 为想要获取文件的 Hash 值,约定使用 {@link KatShaUtils} 15 | * 计算 Hash 16 | * @return 由 Optional 容器包装的包含资源文件的具体信息 17 | * @see KatShaUtils 18 | */ 19 | @Nullable 20 | public InputStream fetch(String hashString); 21 | 22 | /** 23 | * 使用 Hash 校验资源,校验工具为 {@link KatShaUtils} 24 | * 25 | * @param resource 包含资源信息的数据结构 26 | * @return 由 Optional 容器包装的包含资源文件的具体信息 27 | * @see KatShaUtils 28 | */ 29 | public boolean validate(String hashString); 30 | 31 | /** 32 | * 上传资源文件到指定位置。 33 | * 34 | * @param resource 包含资源信息的数据结构 35 | * @return 由 Optional 容器包装的包含资源文件的具体信息 36 | */ 37 | public void upload(String fileHash, InputStream inputStream); 38 | 39 | /** 40 | * 删除资源 41 | * 42 | * @param resource 包含资源信息的数据结构 43 | * @return 是否成功删除 44 | */ 45 | public boolean delete(String hashString); 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/websocket/packet/ServerDescriptionPacket.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.websocket.packet; 2 | 3 | import com.catkatpowered.katserver.common.constants.KatPacketTypeConstants; 4 | import com.google.gson.annotations.SerializedName; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | 8 | /** 9 | * 用于描述服务器的信息 10 | * 11 | * @author hanbings 12 | */ 13 | @Data 14 | @Builder 15 | public class ServerDescriptionPacket { 16 | 17 | // 数据包类型 18 | @SerializedName("type") 19 | private final String type = KatPacketTypeConstants.SERVER_DESCRIPTION_PACKET; 20 | 21 | // 服务器名称 22 | @SerializedName("server") 23 | String server; 24 | 25 | // 服务器版本 26 | @SerializedName("version") 27 | String version; 28 | 29 | // 服务器描述 30 | @SerializedName("description") 31 | String description; 32 | 33 | // 所有接入的IM桥及其描述 34 | // TODO: 改为自动获取,等待imbridge接入系统完工并提供API 35 | @SerializedName("im_bridge_description") 36 | String imBridgeDescription; 37 | 38 | public ServerDescriptionPacket( 39 | String server, 40 | String version, 41 | String imBridgeDescription, 42 | String description 43 | ) { 44 | this.server = server; 45 | this.version = version; 46 | this.imBridgeDescription = imBridgeDescription; 47 | this.description = description; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/message/KatUniMessageType.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.message; 2 | 3 | import com.catkatpowered.katserver.common.constants.KatMessageTypeConstants; 4 | import java.util.HashSet; 5 | import lombok.Getter; 6 | import lombok.Setter; 7 | 8 | /** 9 | * Kat 消息类型管理器 10 | * 11 | * @author suibing112233 12 | */ 13 | public class KatUniMessageType { 14 | 15 | private static final KatUniMessageType Instance = new KatUniMessageType(); 16 | 17 | @Getter 18 | @Setter 19 | private HashSet messageTypes = new HashSet<>() { 20 | { 21 | add(KatMessageTypeConstants.KAT_MESSAGE_TYPE_FILE_MESSAGE); 22 | add(KatMessageTypeConstants.KAT_MESSAGE_TYPE_COLLECTION_MESSAGE); 23 | add(KatMessageTypeConstants.KAT_MESSAGE_TYPE_PLAIN_MESSAGE); 24 | add(KatMessageTypeConstants.KAT_MESSAGE_TYPE_AUDIO_MESSAGE); 25 | add(KatMessageTypeConstants.KAT_MESSAGE_TYPE_IMAGE_MESSAGE); 26 | add(KatMessageTypeConstants.KAT_MESSAGE_TYPE_VIDEO_MESSAGE); 27 | add(KatMessageTypeConstants.KAT_MESSAGE_TYPE_MIXED_MESSAGE); 28 | } 29 | }; 30 | 31 | private KatUniMessageType() {} 32 | 33 | public static KatUniMessageType getInstance() { 34 | return Instance; 35 | } 36 | 37 | public boolean addNewMessageType(String msgType) { 38 | return this.messageTypes.add(msgType); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/task/KatTask.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.task; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 5 | import java.util.concurrent.Callable; 6 | import java.util.concurrent.ExecutorService; 7 | import java.util.concurrent.Executors; 8 | import java.util.concurrent.Future; 9 | 10 | @SuppressWarnings("unused") 11 | public class KatTask { 12 | 13 | private static final KatTask Instance = new KatTask(); 14 | 15 | private final ExecutorService executorService = Executors.newFixedThreadPool( 16 | KatServer.KatConfigAPI 17 | .getConfig(KatConfigNodeConstants.KAT_CONFIG_EXEC_THREADS) 18 | .get() 19 | .intValue() 20 | ); 21 | 22 | private KatTask() {} 23 | 24 | public static KatTask getInstance() { 25 | return Instance; 26 | } 27 | 28 | public Future addTask(Runnable task) { 29 | return this.executorService.submit(task); 30 | } 31 | 32 | public Future addTask(Callable task) { 33 | return this.executorService.submit(task); 34 | } 35 | 36 | public Future addTask(Runnable task, T result) { 37 | return this.executorService.submit(task, result); 38 | } 39 | 40 | public void exec(Runnable task) { 41 | this.executorService.execute(task); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/KatServerMain.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver; 2 | 3 | import com.catkatpowered.katserver.common.constants.KatMiscConstants; 4 | import com.catkatpowered.katserver.config.KatConfig; 5 | import com.catkatpowered.katserver.config.KatConfigManager; 6 | import com.catkatpowered.katserver.database.KatDatabaseManager; 7 | import com.catkatpowered.katserver.event.KatEventManager; 8 | import com.catkatpowered.katserver.extension.KatExtensionManager; 9 | import com.catkatpowered.katserver.network.KatNetworkManager; 10 | import com.catkatpowered.katserver.storage.KatStorageManager; 11 | import com.catkatpowered.katserver.task.KatTaskManager; 12 | import lombok.extern.slf4j.Slf4j; 13 | 14 | /** 15 | * 本项目采用 AGPL v3 进行开源 请遵循开源协议 16 | */ 17 | @Slf4j 18 | public class KatServerMain { 19 | 20 | public static void main(String[] args) { 21 | // 画大饼 22 | log.info(KatMiscConstants.KAT_SERVER_LOGO); 23 | 24 | // 启动配置文件模块 25 | KatConfigManager.init(); 26 | // 启动事件总线模块 27 | KatEventManager.init(); 28 | // 启动网络模块 29 | KatNetworkManager.init(); 30 | // 启动数据库 31 | KatDatabaseManager.init(); 32 | // 启动储存模块 33 | KatStorageManager.init(); 34 | // 启动任务模块 35 | KatTaskManager.init(); 36 | // 启动扩展模块 37 | KatExtensionManager.init(); 38 | 39 | // 启动完成 40 | log.info("Started!"); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/resources/config.toml: -------------------------------------------------------------------------------- 1 | ######################### Network ############################# 2 | [network] 3 | network_port = 25565 4 | 5 | [network.selfgen_cert] 6 | cert_password = "catmoe" 7 | cert_alias = "catmoe" 8 | 9 | [network.custom_cert] 10 | enabled = false 11 | cert_path = "./cert.jks" 12 | cert_password = "catmoe" 13 | 14 | ######################### Database ############################ 15 | [database] 16 | # default support mongodb 17 | # demo database_url: 18 | # mongodb: mongodb://localhost:27017/database_name 19 | # 20 | # Note: No need to carry username and password in url 21 | database_url = "mongodb://localhost:27017/kat-server" 22 | database_username = "" 23 | database_password = "" 24 | 25 | ####################### Storage ############################### 26 | # The resource file storage 27 | [resource] 28 | # You can choose those type of storage_provider 29 | # 1.local 30 | storage_provider = "local" 31 | 32 | # If you choose `local`, 33 | # you can set the resource file where to store. 34 | data_folder_path = "./data" 35 | 36 | ####################### ExecThreads ############################ 37 | [exec] 38 | exec_threads = 16 39 | 40 | ####################### TokenPool ############################## 41 | # This section are the settings of token pool 42 | 43 | [tokenpool] 44 | # You can set the token how long to live 45 | # 46 | # Unit: Millisecond 47 | outdated = 10000 48 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/http/HttpPostHandler.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.http; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.google.gson.Gson; 5 | import com.google.gson.annotations.SerializedName; 6 | import io.javalin.http.BadRequestResponse; 7 | import io.javalin.http.Context; 8 | import io.javalin.http.Handler; 9 | import io.javalin.http.UploadedFile; 10 | import java.io.InputStream; 11 | import lombok.Builder; 12 | import lombok.extern.slf4j.Slf4j; 13 | import org.jetbrains.annotations.NotNull; 14 | 15 | @Slf4j 16 | public class HttpPostHandler implements Handler { 17 | 18 | Gson gson = new Gson(); 19 | 20 | @Override 21 | public void handle(@NotNull Context ctx) throws Exception { 22 | String resourceHash = ctx.pathParam("resourceHash"); 23 | String resourceName = ctx.pathParam("resourceName"); 24 | UploadedFile uploadedFile = ctx.uploadedFile(resourceName); 25 | InputStream inputStream = uploadedFile.content(); 26 | KatServer.KatStorageAPI.upload(resourceHash, inputStream); 27 | // 返回对应的token 28 | ctx.json( 29 | gson.toJson( 30 | HttpPostResponse 31 | .builder() 32 | .resourceToken(KatServer.KatTokenPoolAPI.newToken()) 33 | .build() 34 | ) 35 | ); 36 | throw new BadRequestResponse(); 37 | } 38 | } 39 | 40 | @Builder 41 | class HttpPostResponse { 42 | 43 | @SerializedName("resource_token") 44 | String resourceToken; 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/storage/KatStorage.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.storage; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 5 | import com.catkatpowered.katserver.common.constants.KatStorageTypeConstants; 6 | import com.catkatpowered.katserver.storage.providers.KatStorageProvider; 7 | import com.catkatpowered.katserver.storage.providers.local.LocalProvider; 8 | import java.util.HashMap; 9 | import jdk.jfr.Experimental; 10 | import lombok.Getter; 11 | 12 | @Experimental 13 | public class KatStorage { 14 | 15 | private static final KatStorage Instance = new KatStorage(); 16 | 17 | private final HashMap storageProviders = new HashMap() { 18 | { 19 | put( 20 | KatStorageTypeConstants.KAT_STORAGE_PROVIDER_LOCAL, 21 | new LocalProvider() 22 | ); 23 | } 24 | }; 25 | 26 | @Getter 27 | private KatStorageProvider provider; 28 | 29 | private KatStorage() { 30 | this.provider = 31 | this.storageProviders.get( 32 | KatServer.KatConfigAPI 33 | .getConfig( 34 | KatConfigNodeConstants.KAT_CONFIG_RESOURCE_STORAGE_PROVIDER 35 | ) 36 | .get() 37 | ); 38 | } 39 | 40 | public static KatStorage getInstance() { 41 | return Instance; 42 | } 43 | 44 | public void addStorage(String name, KatStorageProvider storage) { 45 | this.storageProviders.put(name, storage); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/websocket/packet/WebsocketMessageQueryPacket.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.websocket.packet; 2 | 3 | import com.catkatpowered.katserver.common.constants.KatPacketTypeConstants; 4 | import com.catkatpowered.katserver.message.KatUniMessage; 5 | import com.google.gson.annotations.SerializedName; 6 | import java.util.List; 7 | import lombok.Builder; 8 | import lombok.Data; 9 | 10 | // 此数据包双向发送 11 | // moseeger -> kat-server 时提供 extensionId,startTimeStamp,endTimeStamp,messageGroup 12 | // kat-server -> moseeger 时返回原信息并填充 messages 13 | @Data 14 | @Builder 15 | public class WebsocketMessageQueryPacket { 16 | 17 | // 平台标识符 18 | @SerializedName("extension_id") 19 | String extensionId; 20 | 21 | // 数组形式的消息组(返回时使用) 22 | @SerializedName("messages") 23 | List messages; 24 | 25 | // 数据包类型 26 | @SerializedName("type") 27 | final String type = KatPacketTypeConstants.MESSAGE_QUERY_PACKET; 28 | 29 | // 查询起始时间戳 30 | @SerializedName("start_timestamp") 31 | Integer startTimeStamp; 32 | 33 | // 查询结束时间戳 34 | @SerializedName("end_timestamp") 35 | Integer endTimeStamp; 36 | 37 | // 查询平台下messagegroup标识 38 | @SerializedName("message_group") 39 | String messageGroup; 40 | 41 | public WebsocketMessageQueryPacket( 42 | String extensionId, 43 | List messages, 44 | Integer startTimeStamp, 45 | Integer endTimeStamp, 46 | String messageGroup 47 | ) { 48 | this.extensionId = extensionId; 49 | this.messages = messages; 50 | this.startTimeStamp = startTimeStamp; 51 | this.endTimeStamp = endTimeStamp; 52 | this.messageGroup = messageGroup; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/com/catkatpowered/katserver/event/TestEventBus.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import com.catkatpowered.katserver.event.interfaces.EventHandler; 6 | import com.catkatpowered.katserver.event.interfaces.Listener; 7 | import lombok.Getter; 8 | import lombok.Setter; 9 | import org.junit.jupiter.api.Test; 10 | 11 | public class TestEventBus { 12 | 13 | @Test 14 | public void event() { 15 | // 初始化事件总线 16 | KatEventManager.init(); 17 | // 获取事件总线 18 | EventBus eventBus = KatEventManager.getEventBus(); 19 | // 注册事件 20 | TestEvent event = new TestEvent("Hello World!"); 21 | TestVoidEvent voidEvent = new TestVoidEvent(); 22 | eventBus.registerEvent(event); 23 | eventBus.registerEvent(voidEvent); 24 | // 注册监听器 25 | eventBus.registerListener(new TestListener()); 26 | // 发布事件 27 | eventBus.callEvent(event); 28 | } 29 | 30 | static class TestEvent extends Event { 31 | 32 | @Setter 33 | @Getter 34 | String message; 35 | 36 | public TestEvent(String message) { 37 | this.message = message; 38 | } 39 | } 40 | 41 | static class TestVoidEvent extends Event { 42 | 43 | public TestVoidEvent() {} 44 | } 45 | 46 | public static class TestListener implements Listener { 47 | 48 | // 测试基本监听 49 | @EventHandler 50 | public void onTestEvent(TestEvent event) { 51 | assertEquals("Hello World!", event.getMessage()); 52 | } 53 | 54 | // 测试事件是否泄漏 55 | @EventHandler 56 | public void onTestVoidEvent(TestVoidEvent event) throws Exception { 57 | throw new Exception(); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/RegisteredListener.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event; 2 | 3 | import com.catkatpowered.katserver.event.interfaces.Listener; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | @SuppressWarnings("unused") 8 | public class RegisteredListener { 9 | 10 | private final List handlerList = new ArrayList<>(); 11 | private final List priorityIndex = new ArrayList<>(); 12 | 13 | public RegisteredListener() { 14 | for (int count = 0; count < 6; count++) { 15 | priorityIndex.add(0); 16 | } 17 | } 18 | 19 | public List getHandlerList() { 20 | return handlerList; 21 | } 22 | 23 | public void addHandler(RegisteredHandler handler) { 24 | // 这一处非常糟糕的说 25 | int priority = getPriorityShadow(handler.getPriority()); 26 | handlerList.add(priorityIndex.get(priority), handler); 27 | for (int count = priority; count < 6; count++) { 28 | priorityIndex.set(count, priorityIndex.get(count) + 1); 29 | } 30 | } 31 | 32 | public void removeHandler(RegisteredHandler handler) { 33 | handlerList.removeIf(registeredHandler -> 34 | registeredHandler.getListener().equals(handler.getListener()) 35 | ); 36 | } 37 | 38 | public void removeHandler(Listener listener) { 39 | handlerList.removeIf(registeredHandler -> 40 | registeredHandler.getListener().equals(listener) 41 | ); 42 | } 43 | 44 | private int getPriorityShadow(EventPriority priority) { 45 | return switch (priority) { 46 | case LOWEST -> 0; 47 | case LOW -> 1; 48 | case HIGH -> 3; 49 | case HIGHEST -> 4; 50 | case MONITOR -> 5; 51 | default -> 2; 52 | }; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/utils/KatDownload.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.utils; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.net.URL; 8 | import java.util.Map; 9 | import okhttp3.OkHttpClient; 10 | import okhttp3.Request; 11 | 12 | /** 13 | * KatServer 提供的标准下载工具 14 | * 15 | * @author Krysztal 16 | * @see OkHttpClient 17 | */ 18 | public class KatDownload { 19 | 20 | public static InputStream getDownloadFileStream( 21 | File file, 22 | URL url, 23 | Map headers 24 | ) throws IOException { 25 | var client = new OkHttpClient(); 26 | var downloadRequestBuilder = new Request.Builder().url(url); 27 | 28 | if (headers != null) for (var i : headers.keySet()) { 29 | downloadRequestBuilder.addHeader(i, headers.get(i)); 30 | } 31 | 32 | var downloadRequest = downloadRequestBuilder.build(); 33 | var call = client.newCall(downloadRequest); 34 | 35 | return call.execute().body().byteStream(); 36 | } 37 | 38 | public static void writeFile(File path, InputStream inputStream) { 39 | var file = new KatFile(path.getAbsolutePath()); 40 | 41 | file.lock(); 42 | 43 | // Buffer 44 | var len = 0; 45 | var buffer = new byte[2048]; 46 | 47 | try { 48 | var fileOutputStream = new FileOutputStream(path); 49 | 50 | while ((len = inputStream.read(buffer)) != -1) { 51 | fileOutputStream.write(buffer, 0, len); 52 | } 53 | 54 | fileOutputStream.close(); 55 | } catch (IOException e) { 56 | e.printStackTrace(); 57 | file.delete(); 58 | } finally { 59 | file.unlock(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/websocket/KatWebSocketBroadcast.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.websocket; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.event.events.MessageReceiveEvent; 5 | import com.catkatpowered.katserver.event.interfaces.EventHandler; 6 | import com.catkatpowered.katserver.event.interfaces.Listener; 7 | import com.catkatpowered.katserver.message.KatUniMessage; 8 | import com.catkatpowered.katserver.network.KatNetwork; 9 | import com.catkatpowered.katserver.network.websocket.packet.WebSocketMessagePacket; 10 | import com.catkatpowered.katserver.storage.KatMessageStorage; 11 | import com.google.gson.Gson; 12 | import lombok.extern.slf4j.Slf4j; 13 | import org.eclipse.jetty.websocket.api.Session; 14 | 15 | // extension -API-> katserver -websocket-> moseeger 16 | // 此处监听event并转换成网络包发送给moseeger 17 | @Slf4j 18 | public class KatWebSocketBroadcast implements Listener { 19 | 20 | @EventHandler 21 | public void onMessageReceive(MessageReceiveEvent event) { 22 | KatMessageStorage.createMessage(event.getMessage()); 23 | Gson gson = new Gson(); 24 | /* 25 | 判断是否为文件类型的消息包 26 | 若是,则填充resource_token给mosseger进行下一步请求使用 27 | 若不是,则直接发送 28 | */ 29 | WebSocketMessagePacket packet; 30 | if (event.getMessage().isResource()) { 31 | KatUniMessage message = event.getMessage(); 32 | message.setResourceToken(KatServer.KatTokenPoolAPI.newToken()); 33 | packet = WebSocketMessagePacket.builder().message(message).build(); 34 | } else { 35 | packet = 36 | WebSocketMessagePacket.builder().message(event.getMessage()).build(); 37 | } 38 | try { 39 | for (Session session : KatNetwork.getSessions()) { 40 | session.getRemote().sendString(gson.toJson(packet)); 41 | } 42 | } catch (Exception e) { 43 | log.error(e.getMessage()); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/tokenpool/KatTokenPool.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.tokenpool; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 5 | import java.util.Optional; 6 | import java.util.UUID; 7 | import java.util.concurrent.ConcurrentHashMap; 8 | import lombok.Getter; 9 | import lombok.Setter; 10 | 11 | public class KatTokenPool { 12 | 13 | private static final KatTokenPool INSTANCE = new KatTokenPool(); 14 | 15 | @Getter 16 | @Setter 17 | private ConcurrentHashMap tokenPool = new ConcurrentHashMap<>(); 18 | 19 | private KatTokenPool() {} 20 | 21 | public static KatTokenPool getINSTANCE() { 22 | return INSTANCE; 23 | } 24 | 25 | public String newToken() { 26 | var uuid = UUID.randomUUID(); 27 | this.tokenPool.put(uuid.toString(), System.currentTimeMillis()); 28 | return uuid.toString(); 29 | } 30 | 31 | public boolean checkToken(String token) { 32 | return this.tokenPool.containsKey(token); 33 | } 34 | 35 | public boolean destroyToken(String token) { 36 | return !Optional.of(this.tokenPool.remove(token)).isEmpty(); 37 | } 38 | 39 | /** 40 | * 通过传入的action判断对TokenPool的操作 41 | * 42 | * @param action 操作类型 43 | */ 44 | public void cleanTokens(ClearAction action) { 45 | switch (action) { 46 | case All -> this.tokenPool.clear(); 47 | case Outdated -> { 48 | Long outdatedTime = KatServer.KatConfigAPI 49 | .getConfig(KatConfigNodeConstants.KAT_CONFIG_TOKENPOOL_OUTDATED) 50 | .get(); 51 | for (var item : this.tokenPool.entrySet()) if ( 52 | (System.currentTimeMillis() - item.getValue()) >= outdatedTime 53 | ) this.tokenPool.remove(item.getKey()); 54 | } 55 | } 56 | } 57 | 58 | public enum ClearAction { 59 | All, 60 | Outdated, 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/KatEventManager.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event; 2 | 3 | import com.catkatpowered.katserver.event.events.MessageReceiveEvent; 4 | import com.catkatpowered.katserver.event.events.MessageSendEvent; 5 | import com.catkatpowered.katserver.event.interfaces.Listener; 6 | import java.util.Map; 7 | 8 | /** 9 | * 事件总线 10 | * 11 | * @author hanbings 12 | * @author Krysztal 13 | */ 14 | public class KatEventManager { 15 | 16 | public static void init() { 17 | // TODO: 注册所有events包下的event 18 | // 扫包大师 19 | registerEvent(MessageReceiveEvent.builder().build()); 20 | registerEvent(MessageSendEvent.builder().build()); 21 | } 22 | 23 | public static void callEvent(Event event) { 24 | EventBus.getInstance().callEvent(event); 25 | } 26 | 27 | public static void registerEvent(Event event) { 28 | EventBus.getInstance().registerEvent(event); 29 | } 30 | 31 | public static void unregisterEvent(Event event) { 32 | EventBus.getInstance().unregisterEvent(event); 33 | } 34 | 35 | public static void registerListener(Listener listener) { 36 | EventBus.getInstance().registerListener(listener); 37 | } 38 | 39 | public static void unregisterListener(Listener listener) { 40 | EventBus.getInstance().unregisterListener(listener); 41 | } 42 | 43 | /** 44 | * 非常不建议直接获取 EventBus 的实例。 45 | *

    46 | * 若您想尽可能的使用底层,您应当使用其他已经抽象出来的 {@link KatEventManager} 方法。 47 | * 48 | * @return EventBus 的实例 49 | */ 50 | @Deprecated 51 | public static EventBus getEventBus() { 52 | return EventBus.getInstance(); 53 | } 54 | 55 | public static RegisteredListener getEventHandler(Event event) { 56 | return EventBus.getInstance().getEventHandler(event); 57 | } 58 | 59 | public static Map, RegisteredListener> getEventHandlers() { 60 | return EventBus.getInstance().getEventHandlers(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/constants/KatMiscConstants.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.constants; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.utils.KatWorkSpace; 5 | 6 | /** 7 | * 提供常量 8 | * 9 | * @author hanbings 10 | * @author Krysztal 11 | * @author CatMoe 12 | */ 13 | public class KatMiscConstants { 14 | 15 | // Kat Server 项目名 16 | public static final String KAT_PROJECT_NAME = "KatServer"; 17 | 18 | // Kat Server 版本号 19 | public static final String KAT_SERVER_VERSION = "1.0.0"; 20 | 21 | // Kat Server 字符画 22 | public static final String KAT_SERVER_LOGO = 23 | """ 24 | 25 | _ __ _ _____ \\s 26 | | |/ / | | / ____| \\s 27 | | ' / __ _| |_| (___ ___ _ ____ _____ _ __\\s 28 | | < / _` | __|\\\\___ \\\\ / _ \\\\ '__\\\\ \\\\ / / _ \\\\ '__| 29 | | . \\\\ (_| | |_ ____) | __/ | \\\\ V / __/ | \\s 30 | |_|\\\\_\\\\__,_|\\\\__|_____/ \\\\___|_| \\\\_/ \\\\___|_| \\s 31 | \\s 32 | """; 33 | 34 | // Kat Server 环境变量:KAT_ENV_WORKING_DIR 35 | public static final String KAT_ENV_WORKING_DIR = "KAT_ENV_WORKING_DIR"; 36 | 37 | // 日志文件储存路径 38 | public static final String KAT_LOGGER_PATH = KatWorkSpace.fixPath("/log"); 39 | 40 | // 扩展存储路径 41 | public static final String KAT_EXTENSIONS_ROOT = KatWorkSpace.fixPath( 42 | "/extension" 43 | ); 44 | // 扩展配置文件存储路径 45 | public static final String KAT_EXTENSIONS_CONFIG_ROOT = KatWorkSpace.fixPath( 46 | "/extension/config" 47 | ); 48 | 49 | // SQLite 数据库存储路径 50 | public static final String KAT_DATABASE_PATH = KatWorkSpace.fixPath( 51 | KatServer.KatConfigAPI.getConfig( 52 | KatConfigNodeConstants.KAT_CONFIG_RESOURCE_DATA_FOLDER_PATH 53 | ) + 54 | "/database.db" 55 | ); 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/config/KatConfigManager.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.config; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 5 | import com.catkatpowered.katserver.common.utils.KatWorkSpace; 6 | import java.io.IOException; 7 | import java.nio.file.Files; 8 | import java.nio.file.Path; 9 | import java.util.Map; 10 | import java.util.Optional; 11 | import lombok.extern.slf4j.Slf4j; 12 | 13 | /** 14 | * @author Krysztal 15 | */ 16 | @Slf4j 17 | public class KatConfigManager { 18 | 19 | public static void init() { 20 | if ( 21 | !Files.exists( 22 | Path.of( 23 | KatWorkSpace.fixPath( 24 | KatServer.KatConfigAPI 25 | .getConfig( 26 | KatConfigNodeConstants.KAT_CONFIG_RESOURCE_DATA_FOLDER_PATH 27 | ) 28 | .get() 29 | ) 30 | ) 31 | ) 32 | ) { 33 | try { 34 | Files.createDirectory( 35 | Path.of( 36 | KatWorkSpace.fixPath( 37 | KatServer.KatConfigAPI 38 | .getConfig( 39 | KatConfigNodeConstants.KAT_CONFIG_RESOURCE_DATA_FOLDER_PATH 40 | ) 41 | .get() 42 | ) 43 | ) 44 | ); 45 | } catch (IOException e) { 46 | log.error(String.valueOf(e)); 47 | } 48 | } 49 | } 50 | 51 | @SuppressWarnings("unchecked") 52 | public static Optional getConfig(String configNode) { 53 | var optionalConfigNode = Optional.ofNullable(configNode); 54 | 55 | if (optionalConfigNode.isEmpty()) { 56 | return Optional.empty(); 57 | } 58 | 59 | Object res = KatConfig.getInstance().getConfigContent().get(configNode); 60 | 61 | return Optional.ofNullable((T) res); 62 | } 63 | 64 | public static Map getAllConfig() { 65 | return KatConfig.getInstance().getConfigContent(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/extension/KatExtensionManager.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.extension; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.extension.event.DisableExtensionEvent; 5 | import com.catkatpowered.katserver.extension.event.EnableExtensionEvent; 6 | import com.catkatpowered.katserver.extension.event.ExtensionEvent; 7 | import com.catkatpowered.katserver.extension.event.LoadExtensionEvent; 8 | import java.io.File; 9 | 10 | /** 11 | * 扩展管理器 12 | * 13 | * @author hanbings 14 | */ 15 | public class KatExtensionManager { 16 | 17 | public static void init() { 18 | // 注册 Event 19 | KatServer.KatEventBusAPI.registerEvent( 20 | new ExtensionEvent(new KatExtensionInfo()) 21 | ); 22 | KatServer.KatEventBusAPI.registerEvent( 23 | new LoadExtensionEvent(new KatExtensionInfo()) 24 | ); 25 | KatServer.KatEventBusAPI.registerEvent( 26 | new EnableExtensionEvent(new KatExtensionInfo()) 27 | ); 28 | KatServer.KatEventBusAPI.registerEvent( 29 | new DisableExtensionEvent(new KatExtensionInfo()) 30 | ); 31 | 32 | // 加载所有扩展 33 | KatExtensionManager.loadExtensions(); 34 | } 35 | 36 | /** 37 | * 加载所有符合要求的扩展 38 | */ 39 | public static void loadExtensions() { 40 | KatExtensionLoader.getInstance().loadExtensions(); 41 | } 42 | 43 | /** 44 | * 加载一个扩展 45 | * 46 | * @param jar 扩展文件 47 | */ 48 | public static void loadExtension(File jar) { 49 | KatExtensionLoader.getInstance().loadExtension(jar); 50 | } 51 | 52 | /** 53 | * 卸载全部扩展 54 | */ 55 | public static void unloadExtensions() { 56 | KatExtensionLoader.getInstance().unloadExtensions(); 57 | } 58 | 59 | /** 60 | * 卸载一个扩展 61 | * 62 | * @param extension 扩展名 63 | */ 64 | public static void unloadExtension(String extension) { 65 | KatExtensionLoader.getInstance().unloadExtension(extension); 66 | } 67 | 68 | /** 69 | * 卸载一个扩展 70 | * 71 | * @param extension 扩展实例 72 | */ 73 | public static void unloadExtension(KatExtension extension) { 74 | KatExtensionLoader.getInstance().unloadExtension(extension); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/constants/KatConfigNodeConstants.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.constants; 2 | 3 | public class KatConfigNodeConstants { 4 | 5 | public static final String KAT_CONFIG_RESOURCE = "resource"; 6 | public static final String KAT_CONFIG_RESOURCE_STORAGE_PROVIDER = 7 | KAT_CONFIG_RESOURCE + "." + "storage_provider"; 8 | public static final String KAT_CONFIG_RESOURCE_DATA_FOLDER_PATH = 9 | KAT_CONFIG_RESOURCE + "." + "data_folder_path"; 10 | 11 | public static final String KAT_CONFIG_NETWORK = "network"; 12 | public static final String KAT_CONFIG_NETWORK_PORT = 13 | KAT_CONFIG_NETWORK + "." + "network_port"; 14 | public static final String KAT_CONFIG_NETWORK_CUSTOM_CERT_ENABLED = 15 | KAT_CONFIG_NETWORK + "." + "custom_cert" + "." + "enabled"; 16 | public static final String KAT_CONFIG_NETWORK_CUSTOM_CERT_PATH = 17 | KAT_CONFIG_NETWORK + "." + "custom_cert" + "." + "cert_path"; 18 | public static final String KAT_CONFIG_NETWORK_CUSTOM_CERT_PASSWORD = 19 | KAT_CONFIG_NETWORK + "." + "custom_cert" + "." + "cert_password"; 20 | public static final String KAT_CONFIG_NETWORK_SELFGEN_CERT_PASSWORD = 21 | KAT_CONFIG_NETWORK + "." + "selfgen_cert" + "." + "cert_password"; 22 | public static final String KAT_CONFIG_NETWORK_SELFGEN_CERT_ALIAS = 23 | KAT_CONFIG_NETWORK + "." + "selfgen_cert" + "." + "cert_alias"; 24 | 25 | public static final String KAT_CONFIG_EXEC = "exec"; 26 | public static final String KAT_CONFIG_EXEC_THREADS = 27 | KAT_CONFIG_EXEC + "." + "exec_threads"; 28 | 29 | public static final String KAT_CONFIG_TOKENPOOL = "tokenpool"; 30 | public static final String KAT_CONFIG_TOKENPOOL_OUTDATED = 31 | KAT_CONFIG_TOKENPOOL + "." + "outdated"; 32 | 33 | public static final String KAT_CONFIG_DATABASE = "database"; 34 | public static final String KAT_CONFIG_DATABASE_TYPE = 35 | KAT_CONFIG_DATABASE + "." + "database_type"; 36 | public static final String KAT_CONFIG_DATABASE_URL = 37 | KAT_CONFIG_DATABASE + "." + "database_url"; 38 | public static final String KAT_CONFIG_DATABASE_USER_NAME = 39 | KAT_CONFIG_DATABASE + "." + "database_username"; 40 | public static final String KAT_CONFIG_DATABASE_PASSWORD = 41 | KAT_CONFIG_DATABASE + "." + "database_password"; 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/database/interfaces/DatabaseConnection.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.database.interfaces; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | public interface DatabaseConnection { 7 | /** 8 | * 创建一个数据文档 9 | * 10 | * @param collection 目标集合 11 | * @param data 数据实体 12 | */ 13 | void create(String collection, Object data); 14 | 15 | /** 16 | * 创建一打数据集合 17 | * 18 | * @param collection 目标集合 19 | * @param data 数据实体 20 | */ 21 | void create(String collection, List data); 22 | 23 | /** 24 | * 更新一些数据文档 25 | * 26 | * @param collection 目标集合 27 | * @param index 数据索引 需要 new 一个目标对应的 Map kv 值 仅写入索引数据 将自动处理为 Bson 28 | * @param data 数据实体 需要更新进入数据库的数据实体 29 | */ 30 | void update(String collection, Map index, Object data); 31 | 32 | /** 33 | * 删除一些数据文档 34 | * 35 | * @param collection 目标集合 36 | * @param index 数据索引 需要 new 一个目标对应的 Map kv 值 仅写入索引数据 将自动处理为 Bson 37 | */ 38 | void delete(String collection, Map index); 39 | 40 | /** 41 | * 查询数据集合 符合的结果将进入 List 列表返回 需要提供泛型数据实体类类型 42 | * 43 | * @param collection 目标集合 44 | * @param index 数据索引 需要 new 一个目标对应的 Map kv 值 仅写入索引数据 将自动处理为 Bson 45 | * @param type 泛型数据实体类类型 46 | * @param 返回的数据实体类型 47 | * @return 数据实体列表 48 | */ 49 | List read(String collection, Map index, Class type); 50 | 51 | /** 52 | * 搜索数据集合 符合的结果将进入 List 列表返回 需要提供泛型数据实体类类型
    53 | * 本方法提供根据某一个字段名称的边界以及限制数量进行搜索的操作
    54 | * 其中 top 与 bottom 值为泛型值类型 指定的字段需与存储数据的类型对应
    55 | * 举例:
    56 | * number 存储数据类型为 int
    57 | * 那么 top 和 bottom 值为 int 类型 即无需双引号的拆箱类型
    58 | * 伪代码:
    59 | * search(String collection, String data, int top, int bottom, int limit, Class type) 60 | * 61 | * @param collection 目标集合 62 | * @param data 字段名称 63 | * @param top 边界 64 | * @param bottom 边界 65 | * @param limit 限制值 66 | * @param type 泛型数据实体类类型 67 | * @param 返回的数据实体类型 68 | * @return 数据实体列表 69 | */ 70 | List search( 71 | String collection, 72 | String data, 73 | V top, 74 | V bottom, 75 | int limit, 76 | Class type 77 | ); 78 | } 79 | -------------------------------------------------------------------------------- /src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 18 | 19 | 20 | 21 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/config/KatConfig.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.config; 2 | 3 | import com.catkatpowered.katserver.common.utils.KatWorkSpace; 4 | import java.io.*; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import java.util.Objects; 8 | import lombok.Getter; 9 | import lombok.Setter; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.tomlj.Toml; 12 | import org.tomlj.TomlParseResult; 13 | 14 | /** 15 | * KatServer 的配置文件项 16 | * 17 | * @author CatMoe 18 | * @author Krysztal 19 | */ 20 | @Slf4j 21 | public class KatConfig { 22 | 23 | private static final KatConfig Instance = new KatConfig(); 24 | 25 | @Getter 26 | @Setter 27 | private Map configContent = new HashMap<>(); 28 | 29 | private KatConfig() { 30 | File katConfigFile = new File(KatWorkSpace.fixPath("./config.toml")); 31 | try { 32 | // 检测配置文件状态并处理 33 | if (katConfigFile.exists()) { 34 | InputStream inputStream = new FileInputStream(katConfigFile); 35 | TomlParseResult toml = Toml.parse(inputStream); 36 | for (Map.Entry entry : toml.dottedEntrySet()) { 37 | configContent.put(entry.getKey(), entry.getValue()); 38 | } 39 | inputStream.close(); 40 | } else { 41 | if (katConfigFile.createNewFile()) { 42 | OutputStream outputStream = new FileOutputStream(katConfigFile); 43 | outputStream.write( 44 | Objects 45 | .requireNonNull( 46 | KatConfig.class.getClassLoader() 47 | .getResourceAsStream("config.toml") 48 | ) 49 | .readAllBytes() 50 | ); 51 | outputStream.flush(); 52 | outputStream.close(); 53 | InputStream inputStream = new FileInputStream(katConfigFile); 54 | TomlParseResult toml = Toml.parse(inputStream); 55 | for (Map.Entry entry : toml.dottedEntrySet()) { 56 | configContent.put(entry.getKey(), entry.getValue()); 57 | } 58 | inputStream.close(); 59 | } else { 60 | log.error("Unable to write config file!"); 61 | } 62 | } 63 | } catch (Exception e) { 64 | log.error(String.valueOf(e)); 65 | } 66 | } 67 | 68 | public static KatConfig getInstance() { 69 | return Instance; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/storage/KatStorageManager.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.storage; 2 | 3 | import com.catkatpowered.katserver.storage.providers.KatStorageProvider; 4 | import com.catkatpowered.katserver.storage.providers.local.*; 5 | import java.io.InputStream; 6 | import org.jetbrains.annotations.Nullable; 7 | 8 | public class KatStorageManager { 9 | 10 | public static void init() { 11 | KatStorage.getInstance(); 12 | } 13 | 14 | /** 15 | * 获取储存提供者 16 | * 17 | * @return 配置文件中所配置的 KatStorageProvider 18 | * @see KatStorageProvider 19 | */ 20 | public static KatStorageProvider getStorageProvider() { 21 | return KatStorage.getInstance().getProvider(); 22 | } 23 | 24 | /** 25 | * 注册新的储存提供者 26 | * 27 | * @param name 储存提供者名称 28 | * @param newKatStorageProvider 储存提供者实现 29 | * @see KatStorageProvider 30 | * @see LocalProvider 31 | */ 32 | public static void registerStorageProvider( 33 | String name, 34 | KatStorageProvider newKatStorageProvider 35 | ) { 36 | KatStorage.getInstance().addStorage(name, newKatStorageProvider); 37 | } 38 | 39 | /** 40 | * 拉取资源位置。 41 | *

    42 | * 注意,该函数返回值中为URI,需要做适当的处理 43 | * 44 | * @param hashString 45 | * @return 46 | */ 47 | @Nullable 48 | public static InputStream fetch(String hashString) { 49 | return KatStorage.getInstance().getProvider().fetch(hashString); 50 | } 51 | 52 | /** 53 | * 校验文件是否正确 54 | * 55 | * @param hashString 56 | * @return 57 | */ 58 | public static boolean validate(String hashString) { 59 | return KatStorage.getInstance().getProvider().validate(hashString); 60 | } 61 | 62 | /** 63 | * 上传文件 64 | * 65 | * @param resource 包含信息的容器 66 | * @return 67 | */ 68 | public static void upload(String fileHash, InputStream inputStream) { 69 | KatStorage.getInstance().getProvider().upload(fileHash, inputStream); 70 | } 71 | 72 | /** 73 | * 删除文件。 74 | * 75 | * @param hashString 文件hash值 76 | * @return 77 | */ 78 | public static boolean delete(String hashString) { 79 | return KatStorage.getInstance().getProvider().delete(hashString); 80 | } 81 | 82 | /** 83 | * 非常不推荐您使用这个方法 84 | * 85 | * @return 获取 KatStorage 的实例 86 | */ 87 | @Deprecated 88 | public static KatStorage getInstance() { 89 | return KatStorage.getInstance(); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/database/mongodb/MongodbConnector.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.database.mongodb; 2 | 3 | import com.catkatpowered.katserver.database.interfaces.DatabaseConnection; 4 | import com.catkatpowered.katserver.database.interfaces.DatabaseConnector; 5 | import com.google.gson.Gson; 6 | import com.mongodb.MongoClient; 7 | import com.mongodb.MongoClientURI; 8 | import com.mongodb.MongoCredential; 9 | import com.mongodb.ServerAddress; 10 | import java.net.URI; 11 | import java.net.URISyntaxException; 12 | import lombok.extern.slf4j.Slf4j; 13 | 14 | @Slf4j 15 | public record MongodbConnector(String url, String username, String password) 16 | implements DatabaseConnector { 17 | static MongoClient client; 18 | static DatabaseConnection connection; 19 | static Gson gson = new Gson(); 20 | 21 | @Override 22 | public void open() { 23 | MongoClientURI resource = new MongoClientURI(url); 24 | String host = "127.0.0.1"; 25 | int port = 27017; 26 | 27 | try { 28 | URI uri = new URI(url); 29 | host = uri.getHost(); 30 | port = uri.getPort(); 31 | } catch (URISyntaxException exception) { 32 | log.error(exception.getMessage()); 33 | } 34 | 35 | // 参数或 url 其中一个不为空则使用参数或 url 36 | if ( 37 | (username == null || password == null) && 38 | (resource.getUsername() == null || resource.getPassword() == null) 39 | ) { 40 | log.warn( 41 | "No username or password provided. " + 42 | "This is not secure, and it is very likely that the physical server " + 43 | "can be compromised without the firewall being turned on." 44 | ); 45 | client = 46 | new MongoClient(new ServerAddress(host, port), resource.getOptions()); 47 | } else { 48 | client = 49 | new MongoClient( 50 | new ServerAddress(host, port), 51 | // url 的用户名和密码 或 参数的用户名和密码 52 | // 按配置文件说明 url 的用户名和密码可不填写 故首选读取参数 53 | MongoCredential.createCredential( 54 | username != null ? username : resource.getUsername(), 55 | resource.getDatabase() != null ? resource.getDatabase() : "test", 56 | password != null ? password.toCharArray() : resource.getPassword() 57 | ), 58 | resource.getOptions() 59 | ); 60 | } 61 | 62 | connection = new MongodbConnection(gson, client, resource.getDatabase()); 63 | } 64 | 65 | @Override 66 | public void close() { 67 | client.close(); 68 | } 69 | 70 | @Override 71 | public DatabaseConnection connection() { 72 | return connection; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/database/KatDatabaseManager.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.database; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 5 | import com.catkatpowered.katserver.database.interfaces.DatabaseConnector; 6 | import com.catkatpowered.katserver.database.mongodb.MongodbConnector; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | /** 11 | * 数据库处理层 桥接数据库 12 | * 13 | * @author hanbings 14 | * @author suibing112233 15 | */ 16 | public class KatDatabaseManager { 17 | 18 | @SuppressWarnings("ResultOfMethodCallIgnored") 19 | public static void init() { 20 | KatDatabase.getInstance(); 21 | 22 | // 丑炸了 XD 23 | @SuppressWarnings("OptionalGetWithoutIsPresent") 24 | String url = KatServer.KatConfigAPI 25 | .getConfig(KatConfigNodeConstants.KAT_CONFIG_DATABASE_URL) 26 | .get(); 27 | String username = KatServer.KatConfigAPI 28 | .getConfig(KatConfigNodeConstants.KAT_CONFIG_DATABASE_USER_NAME) 29 | .orElse(null); 30 | String password = KatServer.KatConfigAPI 31 | .getConfig(KatConfigNodeConstants.KAT_CONFIG_DATABASE_PASSWORD) 32 | .orElse(null); 33 | 34 | // 初始化数据库连接器 35 | KatDatabaseManager.register(new MongodbConnector(url, username, password)); 36 | } 37 | 38 | public static void register(DatabaseConnector connector) { 39 | KatDatabase.getInstance().register(connector); 40 | } 41 | 42 | public static void create(String collection, Object data) { 43 | KatDatabase.getInstance().connector.connection().create(collection, data); 44 | } 45 | 46 | public static void update( 47 | String collection, 48 | Map index, 49 | Object data 50 | ) { 51 | KatDatabase 52 | .getInstance() 53 | .connector.connection() 54 | .update(collection, index, data); 55 | } 56 | 57 | public static void delete(String collection, Map index) { 58 | KatDatabase.getInstance().connector.connection().delete(collection, index); 59 | } 60 | 61 | public static List read( 62 | String collection, 63 | Map index, 64 | Class type 65 | ) { 66 | return KatDatabase 67 | .getInstance() 68 | .connector.connection() 69 | .read(collection, index, type); 70 | } 71 | 72 | public static List search( 73 | String collection, 74 | String data, 75 | V top, 76 | V bottom, 77 | int limit, 78 | Class type 79 | ) { 80 | return KatDatabase 81 | .getInstance() 82 | .connector.connection() 83 | .search(collection, data, top, bottom, limit, type); 84 | } 85 | 86 | public static void create(String collection, List data) { 87 | KatDatabase.getInstance().connector.connection().create(collection, data); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/test/java/com/catkatpowered/katserver/tokenpool/TestKatTokenPool.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.tokenpool; 2 | 3 | import static org.junit.jupiter.api.Assertions.*; 4 | 5 | import com.catkatpowered.katserver.config.KatConfig; 6 | import com.catkatpowered.katserver.tokenpool.KatTokenPool.ClearAction; 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | import org.junit.jupiter.api.BeforeAll; 10 | import org.junit.jupiter.api.Test; 11 | import org.tomlj.Toml; 12 | import org.tomlj.TomlParseResult; 13 | 14 | public class TestKatTokenPool { 15 | 16 | static String defaultConfig = 17 | """ 18 | [tokenpool] 19 | # You can set the token how long to live 20 | # 21 | # Unit: Millisecond 22 | outdated = 10000 23 | """; 24 | 25 | @BeforeAll 26 | public static void initTest() { 27 | Map config = new HashMap<>(); 28 | TomlParseResult toml = Toml.parse(defaultConfig); 29 | for (Map.Entry entry : toml.dottedEntrySet()) { 30 | config.put(entry.getKey(), entry.getValue()); 31 | } 32 | KatConfig.getInstance().setConfigContent(config); 33 | } 34 | 35 | @Test 36 | public void newToken() { 37 | var token = KatTokenPool.getINSTANCE().newToken(); 38 | assertTrue(KatTokenPool.getINSTANCE().checkToken(token)); 39 | } 40 | 41 | @Test 42 | public void cleanTokensForClearAll() { 43 | KatTokenPool.getINSTANCE().newToken(); 44 | KatTokenPool.getINSTANCE().newToken(); 45 | KatTokenPool.getINSTANCE().newToken(); 46 | KatTokenPool.getINSTANCE().newToken(); 47 | KatTokenPool.getINSTANCE().newToken(); 48 | 49 | KatTokenPool.getINSTANCE().cleanTokens(ClearAction.All); 50 | 51 | assertEquals(0, KatTokenPool.getINSTANCE().getTokenPool().size()); 52 | } 53 | 54 | @Test 55 | public void cleanTokensForClearOutdated() { 56 | var token1 = KatTokenPool.getINSTANCE().newToken(); // -10s | Outdated 57 | var token2 = KatTokenPool.getINSTANCE().newToken(); // -5s | 58 | var token3 = KatTokenPool.getINSTANCE().newToken(); // +0s | 59 | var token4 = KatTokenPool.getINSTANCE().newToken(); // +5s | 60 | var token5 = KatTokenPool.getINSTANCE().newToken(); // +10s | 61 | 62 | var pool = KatTokenPool.getINSTANCE().getTokenPool(); 63 | 64 | pool.put(token1, pool.get(token1) - 10 * 1000); 65 | pool.put(token2, pool.get(token2) - 5 * 1000); 66 | pool.put(token3, pool.get(token3) + 0 * 1000); 67 | pool.put(token4, pool.get(token4) + 5 * 1000); 68 | pool.put(token5, pool.get(token5) + 10 * 1000); 69 | 70 | KatTokenPool.getINSTANCE().setTokenPool(pool); 71 | 72 | KatTokenPool.getINSTANCE().cleanTokens(ClearAction.Outdated); 73 | 74 | assertEquals(4, KatTokenPool.getINSTANCE().getTokenPool().size()); 75 | } 76 | 77 | @Test 78 | public void destroyToken() { 79 | var token = KatTokenPool.getINSTANCE().newToken(); 80 | 81 | assertTrue(KatTokenPool.getINSTANCE().getTokenPool().containsKey(token)); 82 | KatTokenPool.getINSTANCE().destroyToken(token); 83 | assertFalse(KatTokenPool.getINSTANCE().getTokenPool().containsKey(token)); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/KatNetwork.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 5 | import com.catkatpowered.katserver.network.http.HttpGetHandler; 6 | import com.catkatpowered.katserver.network.http.HttpPostHandler; 7 | import com.catkatpowered.katserver.network.utils.KatCertUtil; 8 | import com.catkatpowered.katserver.network.websocket.KatWebSocketIncome; 9 | import io.javalin.Javalin; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | import lombok.Getter; 15 | import lombok.Setter; 16 | import org.eclipse.jetty.server.*; 17 | import org.eclipse.jetty.util.ssl.SslContextFactory; 18 | import org.eclipse.jetty.websocket.api.Session; 19 | 20 | public class KatNetwork { 21 | 22 | private static final KatNetwork Instance = new KatNetwork(); 23 | 24 | @Getter 25 | private static Javalin network; 26 | 27 | // 包含所有moseeger客户端,实现无限客户端 28 | @Getter 29 | @Setter 30 | private static List sessions = new ArrayList<>(); 31 | 32 | private KatNetwork() { 33 | Javalin server = Javalin.create(javalinConfig -> { 34 | javalinConfig.jetty.server(() -> { 35 | Server app = new Server(); 36 | SslContextFactory.Server sslContextFactory = KatCertUtil.getSslContextFactory(); 37 | sslContextFactory.setSniRequired(false); 38 | 39 | HttpConfiguration httpsConfig = new HttpConfiguration(); 40 | SecureRequestCustomizer secureRequestCustomizer = new SecureRequestCustomizer(); 41 | secureRequestCustomizer.setSniHostCheck(false); 42 | httpsConfig.addCustomizer(secureRequestCustomizer); 43 | HttpConnectionFactory https = new HttpConnectionFactory(httpsConfig); 44 | SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslContextFactory, https.getProtocol()); 45 | 46 | ServerConnector sslConnector = new ServerConnector( 47 | app, 48 | sslConnectionFactory, 49 | https 50 | ); 51 | sslConnector.setPort( 52 | KatServer.KatConfigAPI 53 | .getConfig(KatConfigNodeConstants.KAT_CONFIG_NETWORK_PORT) 54 | .get() 55 | .intValue() 56 | ); 57 | 58 | app.setConnectors(new Connector[]{sslConnector}); 59 | return app; 60 | }); 61 | }); 62 | // HTTP Handlers 63 | // mosseger向kat-server请求文件 64 | server.get("/resource/{resourceHash}", new HttpGetHandler()); 65 | // mosseger向kat-server上传文件 66 | server.post( 67 | "/resource/{resourceHash}/{resourceName}", 68 | new HttpPostHandler() 69 | ); 70 | 71 | // WebSocket Handlers 72 | server.ws("/websocket", KatWebSocketIncome::KatNetworkIncomeHandler); 73 | 74 | network = server.start(); 75 | } 76 | 77 | public static KatNetwork getInstance() { 78 | return Instance; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/test/java/com/catkatpowered/katserver/database/TestMongoDBDatabase.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.database; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import com.catkatpowered.katserver.database.mongodb.MongodbConnection; 7 | import com.catkatpowered.katserver.database.mongodb.MongodbConnector; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | import java.util.stream.IntStream; 11 | import lombok.AllArgsConstructor; 12 | import org.junit.jupiter.api.Test; 13 | 14 | @SuppressWarnings("SpellCheckingInspection") 15 | public class TestMongoDBDatabase { 16 | 17 | @AllArgsConstructor 18 | static class Data { 19 | 20 | String message; 21 | int number; 22 | boolean flag; 23 | HashMap map; 24 | String[] array; 25 | } 26 | 27 | @Test 28 | public void connect() { 29 | // 生成连接器 30 | MongodbConnector connector = new MongodbConnector( 31 | "mongodb://localhost:27017/kat-server", 32 | null, 33 | null 34 | ); 35 | // 连接 36 | connector.open(); 37 | // 获取连接 38 | MongodbConnection connection = (MongodbConnection) connector.connection(); 39 | 40 | // 写入数据 41 | connection.create( 42 | "test", 43 | new Data( 44 | "点一份炒饭", 45 | 1919810, 46 | true, 47 | new HashMap<>() { 48 | { 49 | put("锟斤拷", "烫烫烫"); 50 | } 51 | }, 52 | new String[] { "1", "1", "4", "5", "1", "4" } 53 | ) 54 | ); 55 | // 读取数据 56 | List data = connection.read( 57 | "test", 58 | new HashMap<>() { 59 | { 60 | put("message", "点一份炒饭"); 61 | } 62 | }, 63 | Data.class 64 | ); 65 | // 测试数据 66 | assertEquals("点一份炒饭", data.get(0).message); 67 | assertEquals(1919810, data.get(0).number); 68 | assertTrue(data.get(0).flag); 69 | assertEquals("烫烫烫", data.get(0).map.get("锟斤拷")); 70 | assertEquals("1", data.get(0).array[0]); 71 | 72 | // 删除数据 73 | connection.delete( 74 | "test", 75 | new HashMap<>() { 76 | { 77 | put("message", "点一份炒饭"); 78 | } 79 | } 80 | ); 81 | // 验证删除 82 | data = 83 | connection.read( 84 | "test", 85 | new HashMap<>() { 86 | { 87 | put("message", "点一份炒饭"); 88 | } 89 | }, 90 | Data.class 91 | ); 92 | assertEquals(0, data.size()); 93 | 94 | // search 方法查询数据 95 | IntStream 96 | .range(114514, 114517) 97 | .forEach(count -> { 98 | connection.create( 99 | "test", 100 | new Data( 101 | "点一份炒饭", 102 | count, 103 | true, 104 | new HashMap<>() { 105 | { 106 | put("锟斤拷", "烫烫烫"); 107 | } 108 | }, 109 | new String[] { "1", "1", "4", "5", "1", "4" } 110 | ) 111 | ); 112 | }); 113 | 114 | // 查询数据 115 | data = connection.search("test", "number", 114514, 114516, 10, Data.class); 116 | // 测试数据 117 | assertEquals(3, data.size()); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/storage/KatMessageStorage.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.storage; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.message.KatUniMessage; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Optional; 8 | import jdk.jfr.Experimental; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.jetbrains.annotations.NotNull; 11 | 12 | @SuppressWarnings("unused") 13 | @Experimental 14 | @Slf4j 15 | public class KatMessageStorage { 16 | 17 | public static Optional> searchMessage( 18 | String extensionID, 19 | String messageGroup, 20 | Integer startTimeStamp, 21 | Integer endTimeStamp 22 | ) { 23 | return Optional.ofNullable( 24 | KatServer.KatDatabaseAPI.search( 25 | extensionID + "_" + messageGroup, 26 | "message_timestamp", 27 | startTimeStamp, 28 | endTimeStamp, 29 | // TODO: 商议消息数限制 30 | 20, 31 | KatUniMessage.class 32 | ) 33 | ); 34 | } 35 | 36 | /** 37 | * 用于查询单条消息记录,索引值为KatUniMessage.messageID 38 | * 39 | * @param indexMsg 对应数据库当中的索引 40 | * @return 返回被Optional包装的List类型 41 | * @see Optional 42 | */ 43 | public static Optional> getMessage( 44 | @NotNull KatUniMessage indexMsg 45 | ) { 46 | return Optional.ofNullable( 47 | KatServer.KatDatabaseAPI.read( 48 | indexMsg.extensionID + "_" + indexMsg.getMessageGroup(), 49 | new HashMap() { 50 | { 51 | put("messageID", indexMsg.getMessageID()); 52 | } 53 | }, 54 | KatUniMessage.class 55 | ) 56 | ); 57 | } 58 | 59 | /** 60 | * 更新数据库当中的消息记录
    61 | * 62 | * @param oldContent 旧消息记录 63 | * @param newContent 新消息记录 64 | */ 65 | public static void updateMessage( 66 | @NotNull KatUniMessage oldContent, 67 | KatUniMessage newContent 68 | ) { 69 | KatServer.KatDatabaseAPI.update( 70 | oldContent.extensionID + "_" + oldContent.getMessageGroup(), 71 | new HashMap() { 72 | { 73 | put("message_id", oldContent.getMessageID()); 74 | } 75 | }, 76 | newContent 77 | ); 78 | } 79 | 80 | /** 81 | * 删除消息记录 82 | * 83 | * @param indexMsg 必须包含KatUniMessage.messageGroupKatUniMessage.messageID 84 | */ 85 | public static void deleteMessage(@NotNull KatUniMessage indexMsg) { 86 | if (indexMsg.isFullIndex()) { 87 | KatServer.KatDatabaseAPI.delete( 88 | indexMsg.extensionID + "_" + indexMsg.getMessageGroup(), 89 | new HashMap() { 90 | { 91 | put("message_id", indexMsg.getMessageID()); 92 | } 93 | } 94 | ); 95 | } 96 | } 97 | 98 | /** 99 | * 存放新的消息 100 | * 101 | * @param indexMsg 准备存放的信息 102 | */ 103 | public static void createMessage(@NotNull KatUniMessage indexMsg) { 104 | if (indexMsg.isFullIndex()) { 105 | KatServer.KatDatabaseAPI.create( 106 | indexMsg.extensionID + "_" + indexMsg.getMessageGroup(), 107 | indexMsg 108 | ); 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/utils/KatShaUtils.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.utils; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.security.MessageDigest; 8 | import java.security.NoSuchAlgorithmException; 9 | import org.jetbrains.annotations.NotNull; 10 | 11 | /** 12 | * Sha256 辅助工具类。 13 | *

    14 | * KatServer 内部默认并且推荐使用本工具计算 Hash,包括并且不限于以下内容使用本工具类 15 | * 16 | *

  • {@link com.catkatpowered.katserver.storage.providers.KatResource#hash}
  • 17 | * 18 | * @author hanbings 19 | * @author Krysztal 20 | */ 21 | @SuppressWarnings("unused") 22 | public class KatShaUtils { 23 | 24 | /** 25 | * 计算文件的 {@code Sha256} 26 | * 27 | * @param file 目标文件 28 | * @return {@code Sha256} 计算结果 29 | */ 30 | public static String sha256(File file) { 31 | if (file == null || file.length() == 0) { 32 | return null; 33 | } 34 | try { 35 | MessageDigest messageDigest = MessageDigest.getInstance("Sha256"); 36 | FileInputStream fileInputStream = new FileInputStream(file); 37 | return sumSha256(fileInputStream, messageDigest); 38 | } catch (IOException | NoSuchAlgorithmException exception) { 39 | exception.printStackTrace(); 40 | } 41 | return null; 42 | } 43 | 44 | /** 45 | * 计算输入流的 {@code Sha256} 46 | * 47 | * @param inputStream 目标输入流 48 | * @return {@code Sha256} 计算结果 49 | */ 50 | public static String sha256(InputStream inputStream) { 51 | if (inputStream == null) { 52 | return null; 53 | } 54 | try { 55 | MessageDigest messageDigest = MessageDigest.getInstance("Sha256"); 56 | return sumSha256(inputStream, messageDigest); 57 | } catch (IOException | NoSuchAlgorithmException exception) { 58 | exception.printStackTrace(); 59 | } 60 | return null; 61 | } 62 | 63 | /** 64 | * 计算字节数组的 {@code Sha256} 65 | * 66 | * @param bytes 目标字节 67 | * @return {@code Sha256} 计算结果 68 | */ 69 | public static String sha256(byte[] bytes) { 70 | try { 71 | MessageDigest messageDigest = MessageDigest.getInstance("Sha256"); 72 | messageDigest.update(bytes); 73 | byte[] byteArray = messageDigest.digest(); 74 | StringBuilder stringBuilder = new StringBuilder(); 75 | for (byte temp : byteArray) { 76 | stringBuilder.append(String.format("%02x", temp)); 77 | } 78 | return stringBuilder.toString(); 79 | } catch (NoSuchAlgorithmException exception) { 80 | exception.printStackTrace(); 81 | } 82 | return null; 83 | } 84 | 85 | @NotNull 86 | private static String sumSha256( 87 | InputStream inputStream, 88 | MessageDigest messageDigest 89 | ) throws IOException { 90 | byte[] buffer = new byte[1024]; 91 | int len; 92 | while ((len = inputStream.read(buffer)) != -1) { 93 | messageDigest.update(buffer, 0, len); 94 | } 95 | inputStream.close(); 96 | byte[] byteArray = messageDigest.digest(); 97 | StringBuilder stringBuilder = new StringBuilder(); 98 | for (byte temp : byteArray) { 99 | stringBuilder.append(String.format("%02x", temp)); 100 | } 101 | return stringBuilder.toString(); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/storage/providers/local/LocalProvider.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.storage.providers.local; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 5 | import com.catkatpowered.katserver.common.utils.KatDownload; 6 | import com.catkatpowered.katserver.common.utils.KatShaUtils; 7 | import com.catkatpowered.katserver.common.utils.KatWorkSpace; 8 | import com.catkatpowered.katserver.storage.providers.KatStorageProvider; 9 | import java.io.File; 10 | import java.io.FileInputStream; 11 | import java.io.IOException; 12 | import java.io.InputStream; 13 | import java.nio.file.Path; 14 | import java.util.Objects; 15 | import java.util.Optional; 16 | import org.jetbrains.annotations.Nullable; 17 | 18 | /** 19 | * @author Krysztal 20 | */ 21 | public class LocalProvider implements KatStorageProvider { 22 | 23 | private final String resourceStoragePath; 24 | 25 | public LocalProvider() { 26 | super(); 27 | resourceStoragePath = 28 | KatServer.KatConfigAPI 29 | .getConfig( 30 | KatConfigNodeConstants.KAT_CONFIG_RESOURCE_DATA_FOLDER_PATH 31 | ) 32 | .orElse(KatWorkSpace.fixPath("./data")); 33 | } 34 | 35 | /** 36 | * 通过文件 Hash 获取资源文件 37 | * 38 | * @return URI 字段为文件于磁盘中的位置 39 | * @see java.net.URI 40 | * @see Optional 41 | * @see com.catkatpowered.katserver.common.utils.KatShaUtils 42 | */ 43 | @Override 44 | @Nullable 45 | public InputStream fetch(String hashString) { 46 | var path = toPath(hashString); 47 | if (path == null) return null; 48 | 49 | var file = new File(path); 50 | if (!(new File(path)).exists()) return null; 51 | 52 | InputStream fileInputStream = null; 53 | 54 | try { 55 | fileInputStream = new FileInputStream(file); 56 | } catch (Exception e) { 57 | e.printStackTrace(); 58 | } 59 | 60 | return fileInputStream; 61 | } 62 | 63 | @Override 64 | public boolean validate(String hashString) { 65 | // 判断是否存在文件,若不存在则返回空 Optional 66 | var fetchedResource = this.fetch(hashString); 67 | if (fetchedResource == null) return false; 68 | 69 | // 由于是本地文件,因此直接计算文件Sha256 70 | var fileSha256 = KatShaUtils.sha256(fetchedResource); 71 | 72 | try { 73 | fetchedResource.close(); 74 | } catch (IOException e) { 75 | e.printStackTrace(); 76 | } 77 | 78 | return Objects.equals(hashString, fileSha256); 79 | } 80 | 81 | @Override 82 | public void upload(String fileHash, InputStream inputStream) { 83 | var filePath = this.toPath(fileHash); 84 | 85 | KatDownload.writeFile(new File(filePath), inputStream); 86 | } 87 | 88 | @Override 89 | public boolean delete(String hashString) { 90 | var fetchedFilePath = this.fetch(hashString); 91 | if (fetchedFilePath == null) return false; 92 | 93 | var file = new File(this.toPath(hashString)); 94 | return file.delete(); 95 | } 96 | 97 | private String toPath(String hashString) { 98 | return Path 99 | .of( 100 | this.resourceStoragePath, 101 | hashString.substring(0, 2), 102 | hashString.substring(2, 4) 103 | ) 104 | .toAbsolutePath() 105 | .toString(); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/database/mongodb/MongodbConnection.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.database.mongodb; 2 | 3 | import com.catkatpowered.katserver.database.interfaces.DatabaseConnection; 4 | import com.google.gson.Gson; 5 | import com.mongodb.BasicDBObject; 6 | import com.mongodb.MongoClient; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | import java.util.Map; 10 | import java.util.stream.Collectors; 11 | import org.bson.Document; 12 | 13 | public record MongodbConnection(Gson gson, MongoClient client, String database) 14 | implements DatabaseConnection { 15 | @Override 16 | public void create(String collection, Object data) { 17 | client 18 | .getDatabase(database) 19 | .getCollection(collection) 20 | .insertOne(Document.parse(gson.toJson(data))); 21 | } 22 | 23 | @Override 24 | public void create(String collection, List data) { 25 | client 26 | .getDatabase(database) 27 | .getCollection(collection) 28 | .insertMany( 29 | data 30 | .stream() 31 | .map(d -> Document.parse(gson.toJson(d))) 32 | .collect(Collectors.toList()) 33 | ); 34 | } 35 | 36 | @Override 37 | public void update( 38 | String collection, 39 | Map index, 40 | Object data 41 | ) { 42 | client 43 | .getDatabase(database) 44 | .getCollection(collection) 45 | .updateMany( 46 | Document.parse(gson.toJsonTree(index, Map.class).toString()), 47 | Document.parse(gson.toJson(data)) 48 | ); 49 | } 50 | 51 | @Override 52 | public void delete(String collection, Map index) { 53 | client 54 | .getDatabase(database) 55 | .getCollection(collection) 56 | .deleteMany(Document.parse(gson.toJsonTree(index, Map.class).toString())); 57 | } 58 | 59 | @Override 60 | public List read( 61 | String collection, 62 | Map index, 63 | Class type 64 | ) { 65 | List list = new ArrayList<>(); 66 | // 获取数据库连接 67 | client 68 | .getDatabase(database) 69 | .getCollection(collection) 70 | .find(Document.parse(gson.toJsonTree(index, Map.class).toString())) 71 | .iterator() 72 | .forEachRemaining(document -> { 73 | // 将 document 转换回对象 74 | list.add(gson.fromJson(document.toJson(), type)); 75 | }); 76 | return list; 77 | } 78 | 79 | @Override 80 | public List search( 81 | String collection, 82 | String data, 83 | V top, 84 | V bottom, 85 | int limit, 86 | Class type 87 | ) { 88 | List list = new ArrayList<>(); 89 | // 获取数据库连接 90 | client 91 | .getDatabase(database) 92 | .getCollection(collection) 93 | .find( 94 | new BasicDBObject() { 95 | { 96 | put( 97 | data, 98 | new BasicDBObject() { 99 | { 100 | put("$gte", top); 101 | put("$lte", bottom); 102 | } 103 | } 104 | ); 105 | } 106 | } 107 | ) 108 | .skip(0) 109 | .limit(limit) 110 | .iterator() 111 | .forEachRemaining(document -> { 112 | // 将 document 转换回对象 113 | list.add(gson.fromJson(document.toJson(), type)); 114 | }); 115 | return list; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/test/java/com/catkatpowered/katserver/config/TestKatConfig.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.config; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import com.catkatpowered.katserver.KatServer; 6 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | import java.util.Optional; 10 | import org.junit.jupiter.api.Test; 11 | import org.tomlj.Toml; 12 | import org.tomlj.TomlParseResult; 13 | 14 | public class TestKatConfig { 15 | 16 | String defaultConfig = 17 | """ 18 | ######################### Network ############################# 19 | [network] 20 | network_port = 25565 21 | 22 | [network.selfgen_cert] 23 | cert_password = "catmoe" 24 | cert_alias = "catmoe" 25 | 26 | [network.custom_cert] 27 | enabled = false 28 | cert_path = "./cert.jks" 29 | cert_password = "catmoe" 30 | 31 | ######################### Database ############################ 32 | [database] 33 | # default support mongodb 34 | # demo database_url: 35 | # mongodb: mongodb://localhost:27017/database_name 36 | # 37 | # Note: No need to carry username and password in url 38 | database_url = "mongodb://localhost:27017/kat-server" 39 | database_username = "" 40 | database_password = "" 41 | 42 | ####################### Storage ############################### 43 | # The resource file storage 44 | [resource] 45 | # You can choose those type of storage_provider 46 | # 1.local 47 | storage_provider = "local" 48 | 49 | # If you choose `local`, 50 | # you can set the resource file where to store. 51 | data_folder_path = "./data" 52 | 53 | ####################### ExecThreads ############################ 54 | [exec] 55 | exec_threads = 16 56 | 57 | ####################### TokenPool ############################## 58 | # This section are the settings of token pool 59 | 60 | [tokenpool] 61 | # You can set the token how long to live 62 | # 63 | # Unit: Millisecond 64 | outdated = 10000 65 | """; 66 | 67 | @Test 68 | public void testConfigNode() { 69 | Map config = new HashMap<>(); 70 | TomlParseResult toml = Toml.parse(defaultConfig); 71 | for (Map.Entry entry : toml.dottedEntrySet()) { 72 | //System.out.println(entry.getKey() + " / " + entry.getValue()); 73 | config.put(entry.getKey(), entry.getValue()); 74 | } 75 | KatConfig.getInstance().setConfigContent(config); 76 | 77 | // Get undefined or null config node 78 | var undefinedNode = KatServer.KatConfigAPI.getConfig("undefined"); 79 | assertEquals(Optional.empty(), undefinedNode); 80 | 81 | var nullNode = KatServer.KatConfigAPI.getConfig(""); 82 | assertEquals(Optional.empty(), nullNode); 83 | 84 | var nullConfigNode = KatServer.KatConfigAPI.getConfig(null); // 炒饭 85 | assertEquals(Optional.empty(), nullConfigNode); 86 | 87 | // Try worn type cast 88 | KatServer.KatConfigAPI.getConfig( 89 | KatConfigNodeConstants.KAT_CONFIG_DATABASE 90 | ); // 炒饭,酒吧没炸就行 91 | 92 | // Get already exist config node 93 | var networkPort = KatServer.KatConfigAPI 94 | .getConfig(KatConfigNodeConstants.KAT_CONFIG_NETWORK_PORT) 95 | .get() 96 | .intValue(); 97 | assertEquals(25565, networkPort); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/event/EventBus.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.event; 2 | 3 | import com.catkatpowered.katserver.event.interfaces.Blockable; 4 | import com.catkatpowered.katserver.event.interfaces.Cancellable; 5 | import com.catkatpowered.katserver.event.interfaces.EventHandler; 6 | import com.catkatpowered.katserver.event.interfaces.Listener; 7 | import java.lang.reflect.InvocationTargetException; 8 | import java.util.Map; 9 | import java.util.concurrent.ConcurrentHashMap; 10 | import java.util.stream.Stream; 11 | import lombok.Getter; 12 | 13 | /** 14 | * @author hanbings 15 | * @author Krystal 16 | */ 17 | @SuppressWarnings("unused") 18 | public class EventBus { 19 | 20 | @Getter 21 | private final Map, RegisteredListener> eventHandlers = new ConcurrentHashMap<>(); 22 | 23 | private static final EventBus instance = new EventBus(); 24 | 25 | private EventBus() {} 26 | 27 | public static EventBus getInstance() { 28 | return instance; 29 | } 30 | 31 | public void callEvent(Event event) { 32 | if (eventHandlers.containsKey(event.getClass())) { 33 | for (RegisteredHandler handler : eventHandlers 34 | .get(event.getClass()) 35 | .getHandlerList()) { 36 | if (event instanceof Blockable && ((Blockable) event).isBlocked()) { 37 | return; 38 | } 39 | // isIgnoreCancelled为 true 时继续执行 40 | if ( 41 | event instanceof Cancellable && 42 | ((Cancellable) event).isCancelled() && 43 | !handler.isIgnoreCancelled() 44 | ) { 45 | continue; 46 | } 47 | try { 48 | handler.getMethod().invoke(handler.getListener(), event); 49 | } catch (IllegalAccessException | InvocationTargetException e) { 50 | e.printStackTrace(); 51 | } 52 | } 53 | } 54 | } 55 | 56 | public RegisteredListener getEventHandler(Event event) { 57 | return eventHandlers.get(event.getClass()); 58 | } 59 | 60 | public void registerEvent(Event event) { 61 | if (!eventHandlers.containsKey(event.getClass())) { 62 | eventHandlers.put(event.getClass(), new RegisteredListener()); 63 | } 64 | } 65 | 66 | public void unregisterEvent(Event event) { 67 | eventHandlers.remove(event.getClass()); 68 | } 69 | 70 | public void registerListener(Listener listener) { 71 | Stream 72 | .of(listener.getClass().getDeclaredMethods()) 73 | .filter(method -> method.isAnnotationPresent(EventHandler.class)) 74 | .filter(method -> eventHandlers.containsKey(method.getParameterTypes()[0]) 75 | ) 76 | .forEach(method -> { 77 | method.setAccessible(true); 78 | 79 | var event = method.getParameterTypes()[0]; 80 | EventHandler annotation = method.getAnnotation(EventHandler.class); 81 | eventHandlers 82 | .get(event) 83 | .addHandler( 84 | new RegisteredHandler( 85 | annotation.priority(), 86 | annotation.ignoreCancelled(), 87 | listener, 88 | method 89 | ) 90 | ); 91 | 92 | method.setAccessible(false); 93 | }); 94 | } 95 | 96 | public void unregisterListener(Listener listener) { 97 | Stream 98 | .of(listener.getClass().getDeclaredMethods()) 99 | .filter(method -> method.isAnnotationPresent(EventHandler.class)) 100 | .filter(method -> eventHandlers.containsKey(method.getParameterTypes()[0]) 101 | ) 102 | .forEach(method -> { 103 | method.setAccessible(true); 104 | 105 | var event = method.getParameterTypes()[0]; 106 | EventHandler annotation = method.getAnnotation(EventHandler.class); 107 | eventHandlers.get(event).removeHandler(listener); 108 | 109 | method.setAccessible(false); 110 | }); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/common/utils/ReflectionSweet.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.common.utils; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Field; 5 | import java.lang.reflect.Method; 6 | import java.util.Arrays; 7 | import lombok.extern.slf4j.Slf4j; 8 | 9 | /** 10 | * 反射工具类 流式调用
    11 | * 根据返回值或返回工具类引用分为两类操作
    12 | * 流操作和返回操作
    13 | * 流操作返回工具类引用 可以继续调用
    14 | * 咱是说如果 如果反射也能这么爽 :D
    15 | * 返回操作值 16 | * 17 | * @author hanbings 18 | */ 19 | @Slf4j 20 | @SuppressWarnings("unused") 21 | public class ReflectionSweet { 22 | 23 | Class clazz = this.getClass(); 24 | 25 | /** 26 | * 初始化一个类型 27 | * 28 | * @param name 类名 29 | * @return 工具类引用 30 | */ 31 | public ReflectionSweet load(String name) { 32 | try { 33 | clazz = ReflectionSweet.class.getClassLoader().loadClass(name); 34 | } catch (ClassNotFoundException e) { 35 | log.error("ClassNotFoundException", e); 36 | } 37 | return this; 38 | } 39 | 40 | /** 41 | * 给予访问权限 42 | * 43 | * @return 工具类引用 44 | */ 45 | public ReflectionSweet access() { 46 | Arrays 47 | .stream(clazz.getFields()) 48 | .forEach(field -> field.setAccessible(true)); 49 | Arrays 50 | .stream(clazz.getMethods()) 51 | .forEach(method -> method.setAccessible(true)); 52 | return this; 53 | } 54 | 55 | /** 56 | * 给予类型某个变量或某个方法访问权限 57 | * 58 | * @param name 变量名 59 | * @return 工具类引用 60 | */ 61 | public ReflectionSweet access(String name) { 62 | Arrays 63 | .stream(clazz.getFields()) 64 | .filter(field -> field.getName().equals(name)) 65 | .forEach(field -> field.setAccessible(true)); 66 | Arrays 67 | .stream(clazz.getMethods()) 68 | .filter(method -> method.getName().equals(name)) 69 | .forEach(method -> method.setAccessible(true)); 70 | return this; 71 | } 72 | 73 | /** 74 | * 获取类型的所有变量 75 | * 76 | * @return 变量数组 77 | */ 78 | public Field[] fields() { 79 | return clazz.getFields(); 80 | } 81 | 82 | /** 83 | * 在全部的 类型 / 变量 / 方法 范围内
    84 | * 判断类型 / 变量 / 方法是否包含某个注解 85 | */ 86 | public boolean annotation(Class annotation) { 87 | return ( 88 | Arrays 89 | .stream(clazz.getDeclaredFields()) 90 | .anyMatch(field -> field.isAnnotationPresent(annotation)) || 91 | Arrays 92 | .stream(clazz.getDeclaredMethods()) 93 | .anyMatch(method -> method.isAnnotationPresent(annotation)) 94 | ); 95 | } 96 | 97 | /** 98 | * 给定一个 类型 / 变量 / 方法
    99 | * 在给定的范围内判断是否包含某个注解 100 | */ 101 | public boolean annotation( 102 | Object object, 103 | Class annotation 104 | ) { 105 | // 用过滤器过滤 object 到底是类型还是变量还是方法 106 | if (object instanceof Field) { 107 | return ((Field) object).isAnnotationPresent(annotation); 108 | } 109 | if (object instanceof Method) { 110 | return ((Method) object).isAnnotationPresent(annotation); 111 | } 112 | if (object instanceof Class) { 113 | return ((Class) object).isAnnotationPresent(annotation); 114 | } 115 | return false; 116 | } 117 | 118 | /** 119 | * 判断类型是否包含某个注解 120 | * 121 | * @param annotation 注解 122 | * @return 是否包含 123 | */ 124 | public boolean annotationClass(Class annotation) { 125 | return clazz.isAnnotationPresent(annotation); 126 | } 127 | 128 | /** 129 | * 获取包含某个注解的变量 130 | * 131 | * @param annotation 注解 132 | * @return 变量数组 133 | */ 134 | public Field[] annotationFields(Class annotation) { 135 | return Arrays 136 | .stream(clazz.getFields()) 137 | .filter(field -> field.isAnnotationPresent(annotation)) 138 | .toArray(Field[]::new); 139 | } 140 | 141 | /** 142 | * 获取包含某个注解的方法 143 | * 144 | * @param annotation 注解 145 | * @return 方法数组 146 | */ 147 | public Method[] annotationMethods(Class annotation) { 148 | return Arrays 149 | .stream(clazz.getMethods()) 150 | .filter(method -> method.isAnnotationPresent(annotation)) 151 | .toArray(Method[]::new); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/websocket/KatWebSocketIncome.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.websocket; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.constants.KatMiscConstants; 5 | import com.catkatpowered.katserver.common.constants.KatPacketTypeConstants; 6 | import com.catkatpowered.katserver.event.events.CustomPacketReceiveEvent; 7 | import com.catkatpowered.katserver.event.events.MessageSendEvent; 8 | import com.catkatpowered.katserver.message.KatUniMessage; 9 | import com.catkatpowered.katserver.network.KatNetwork; 10 | import com.catkatpowered.katserver.network.websocket.packet.*; 11 | import com.catkatpowered.katserver.storage.KatMessageStorage; 12 | import com.google.gson.Gson; 13 | import io.javalin.websocket.WsConfig; 14 | import java.util.List; 15 | import java.util.Optional; 16 | import org.eclipse.jetty.websocket.api.Session; 17 | 18 | public class KatWebSocketIncome { 19 | 20 | public static void KatNetworkIncomeHandler(WsConfig ws) { 21 | Gson gson = new Gson(); 22 | ws.onConnect(wsConnectContext -> { 23 | // 发送服务端描述包 24 | wsConnectContext.send( 25 | gson.toJson( 26 | ServerDescriptionPacket 27 | .builder() 28 | .version(KatMiscConstants.KAT_SERVER_VERSION) 29 | .build() 30 | ) 31 | ); 32 | List sessions = KatNetwork.getSessions(); 33 | sessions.add(wsConnectContext.session); 34 | KatNetwork.setSessions(sessions); 35 | }); 36 | ws.onClose(wsCloseContext -> 37 | KatNetwork.getSessions().remove(wsCloseContext.session) 38 | ); 39 | ws.onMessage(wsMessageContext -> { 40 | String type = gson 41 | .fromJson(wsMessageContext.message(), BasePacket.class) 42 | .getType(); 43 | switch (type) { 44 | case KatPacketTypeConstants.MESSAGE_PACKET -> { 45 | WebSocketMessagePacket webSocketMessagePacket = gson.fromJson( 46 | wsMessageContext.message(), 47 | WebSocketMessagePacket.class 48 | ); 49 | if ( 50 | webSocketMessagePacket.getMessage().isResource() && 51 | !KatServer.KatTokenPoolAPI.checkToken( 52 | webSocketMessagePacket.getMessage().resourceToken 53 | ) 54 | ) { 55 | wsMessageContext.send( 56 | gson.toJson( 57 | ErrorPacket.builder().error("Invalid Resource Token").build() 58 | ) 59 | ); 60 | return; 61 | } 62 | // 异步保存消息到数据库 63 | KatMessageStorage.createMessage(webSocketMessagePacket.getMessage()); 64 | // 处理消息发送事件 65 | KatServer.KatEventBusAPI.callEvent( 66 | MessageSendEvent 67 | .builder() 68 | .extensionId(webSocketMessagePacket.getMessage().extensionID) 69 | .message(webSocketMessagePacket.getMessage()) 70 | .build() 71 | ); 72 | 73 | return; 74 | } 75 | case KatPacketTypeConstants.MESSAGE_QUERY_PACKET -> { 76 | WebsocketMessageQueryPacket websocketMessageQueryPacket = gson.fromJson( 77 | wsMessageContext.message(), 78 | WebsocketMessageQueryPacket.class 79 | ); 80 | // 处理消息查询并返回 81 | Optional> messages = KatMessageStorage.searchMessage( 82 | websocketMessageQueryPacket.getExtensionId(), 83 | websocketMessageQueryPacket.getMessageGroup(), 84 | websocketMessageQueryPacket.getStartTimeStamp(), 85 | websocketMessageQueryPacket.getEndTimeStamp() 86 | ); 87 | websocketMessageQueryPacket.setMessages(messages.orElse(null)); 88 | wsMessageContext.send(websocketMessageQueryPacket); 89 | return; 90 | } 91 | case KatPacketTypeConstants.CUSTOM_PACKET -> { 92 | CustomPacket customPacket = gson.fromJson( 93 | wsMessageContext.message(), 94 | CustomPacket.class 95 | ); 96 | KatServer.KatEventBusAPI.callEvent( 97 | CustomPacketReceiveEvent 98 | .builder() 99 | .extensionId(customPacket.getExtensionId()) 100 | .content(customPacket.getContent()) 101 | .build() 102 | ); 103 | } 104 | } 105 | wsMessageContext.send( 106 | gson.toJson(ErrorPacket.builder().error("Unknown Packet").build()) 107 | ); 108 | }); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/message/KatUniMessage.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.message; 2 | 3 | import com.catkatpowered.katserver.common.constants.KatMessageTypeConstants; 4 | import com.google.gson.annotations.SerializedName; 5 | import java.net.URI; 6 | import java.util.ArrayList; 7 | import java.util.Objects; 8 | import lombok.Builder; 9 | import lombok.Builder.Default; 10 | import lombok.Data; 11 | 12 | /** 13 | * Kat 聚合消息 14 | * 15 | * @author suibing112233 16 | * @author hanbings 17 | * @author CatMoe 18 | */ 19 | @Data 20 | @Builder 21 | public class KatUniMessage { 22 | 23 | /** 24 | * MessageType 用于区分本级的消息类型,方便前端处理消息的展示以及KatServer对消息的储存和处理。
    25 | *

    26 | * 其中为了方便Extension的识别,这里采用的是字符串储存而不是enum
    27 | *

    28 | * 同时提供了KatUniMessageTypeManager方便Extension拓展消息的类型。 29 | * 30 | * @see KatMessageTypeConstants 31 | * @see KatUniMessageTypeManager 32 | */ 33 | @SerializedName("message_type") 34 | @Default 35 | public String messageType = 36 | KatMessageTypeConstants.KAT_MESSAGE_TYPE_PLAIN_MESSAGE; 37 | 38 | /** 39 | * ExtensionID 用于确定消息来源, 不可更改 40 | *

    41 | */ 42 | @SerializedName("extension_id") 43 | public String extensionID; 44 | 45 | /** 46 | * MessageGroup 用于本条消息的聚合特征,方便消息存入库处理 47 | *

    48 | */ 49 | @SerializedName("message_group") 50 | public String messageGroup; 51 | 52 | /** 53 | * MessageID 54 | * 是本级消息的唯一标识符,方便Extension对本层消息的处理以及KatServer对本层消息的存取。
    55 | *

    56 | * MessageIDKatServer提供算法进行分配。暂定为UUID
    57 | */ 58 | @SerializedName("message_id") 59 | public String messageID; 60 | 61 | /** 62 | * MessageContent 是本级消息的内容。
    63 | */ 64 | @SerializedName("message_content") 65 | public String messageContent; 66 | 67 | /** 68 | * MessageTimeStamp消息时间戳 69 | */ 70 | @SerializedName("message_timestamp") 71 | public Long messageTimeStamp; 72 | 73 | /** 74 | * MessageList 指向的是下一级消息列表。
    75 | *

    76 | * 当前假设情况如下
    77 | *

      78 | *
    1. 如果MessageTypeKAT_MESSAGE_TYPE_MIXED_MESSAGE,则MessageList中为顺序化的呈现
    2. 79 | *
    3. 如果MessageTypeKAT_MESSAGE_TYPE_COLLECTION_MESSAGE,则MessageList中为消息转发消息的列表
    4. 80 | *
    81 | */ 82 | @SerializedName("message_list") 83 | public ArrayList messageList; 84 | 85 | /** 86 | * ExtendedExtension对消息的额外补充内容
    87 | *

    88 | * KatServer对这部分消息是不敏感的,并不会对这段内容进行额外的补充 89 | */ 90 | @SerializedName("extended") 91 | public ArrayList extended; 92 | 93 | /** 94 | * ResourceHash 是资源文件的哈希值 95 | */ 96 | @SerializedName("resource_hash") 97 | public String resourceHash; 98 | 99 | /** 100 | * ResourceName 为资源文件的实际名称 101 | */ 102 | @SerializedName("resource_name") 103 | public String resourceName; 104 | 105 | /** 106 | * ResourceURI 为资源文件的下载地址 107 | */ 108 | @SerializedName("resource_uri") 109 | public URI resourceURI; 110 | 111 | /** 112 | * ResourceSize 为资源的大小 113 | * 114 | * 当为-1时,大小未知 115 | */ 116 | @SerializedName("resource_size") 117 | @Default 118 | public long resourceSize = -1; 119 | 120 | /** 121 | * ResourceToken 用于资源文件请求时的一次性鉴权 122 | */ 123 | @SerializedName("resource_token") 124 | public String resourceToken; 125 | 126 | /** 127 | * 判断是否包含资源信息
    128 | *

    129 | * 当前的条件为当MessageType等于以下任意类型
    130 | *

      131 | *
    1. KAT_MESSAGE_TYPE_FILE_MESSAGE
    2. 132 | *
    3. KAT_MESSAGE_TYPE_IMAGE_MESSAGE
    4. 133 | *
    5. KAT_MESSAGE_TYPE_AUDIO_MESSAGE
    6. 134 | *
    7. KAT_MESSAGE_TYPE_VIDEO_MESSAGE
    8. 135 | *
    136 | *

    137 | * 任意之一时则成立 138 | * 139 | * @return 当包含资源类信息时,返回true,否则返回false 140 | */ 141 | public boolean isResource() { 142 | return ( 143 | Objects.equals( 144 | this.messageType, 145 | KatMessageTypeConstants.KAT_MESSAGE_TYPE_FILE_MESSAGE 146 | ) || 147 | Objects.equals( 148 | this.messageType, 149 | KatMessageTypeConstants.KAT_MESSAGE_TYPE_IMAGE_MESSAGE 150 | ) || 151 | Objects.equals( 152 | this.messageType, 153 | KatMessageTypeConstants.KAT_MESSAGE_TYPE_AUDIO_MESSAGE 154 | ) || 155 | Objects.equals( 156 | this.messageType, 157 | KatMessageTypeConstants.KAT_MESSAGE_TYPE_VIDEO_MESSAGE 158 | ) 159 | ); 160 | } 161 | 162 | /** 163 | * 判断是否为全索引,当KatUniMessage.messageIDKatUniMessage.messageGroup均有值时则为全索引 164 | */ 165 | public boolean isFullIndex() { 166 | return (this.messageGroup == null || this.messageID == null); 167 | } 168 | 169 | public boolean isDownloadable() { 170 | return this.resourceURI != null; 171 | } 172 | 173 | public boolean isHashed() { 174 | return this.resourceHash != null; 175 | } 176 | 177 | public boolean isIdentified() { 178 | return this.messageGroup != null; 179 | } 180 | 181 | public boolean isUnknownSize() { 182 | return this.resourceSize == -1; 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Kat Server](https://s2.loli.net/2022/01/14/ApdrzBoIeFl6Mh8.png) 2 | 3 |

    🕊 Kat Server

    4 | 5 |
    6 | 7 | ![Github License](https://img.shields.io/github/license/catkatpowered/kat-server?style=for-the-badge) ![GitHub Last Commit](https://img.shields.io/github/last-commit/catkatpowered/kat-server?style=for-the-badge) ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/catkatpowered/kat-server/verify.yml?branch=main&style=for-the-badge) [![Website](https://img.shields.io/badge/WEBSITE-@CatKatPowered-blue.svg?style=for-the-badge)](https://catkatpowered.com) 8 | 9 |
    10 | 11 | ## 🎉 你好! 12 | 13 | 这是一个聊天软件的后端,或者说好几个聊天软件的后端 14 | 15 | 我们正在寻找一种数据表达方式处理在通常的 IM 中可表达的内容,并尝试消息的存储与进行数据处理 16 | 17 | 通俗来讲,我们正在探索如何将多个第三方即时通讯软件中消息表达成一组适合的数据的方法 18 | 19 | ## 👷 构建状态 20 | 21 | | 项目 | 状态 | 说明 | 22 | | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | 23 | | [Verify Build Github Actions](https://github.com/CatkatPowered/kat-server/actions/workflows/verify.yml) | ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/catkatpowered/kat-server/verify.yml?branch=main&style=flat) | 验证当前 commit 是否通过编译 | 24 | | [Tests for Database](https://github.com/CatkatPowered/kat-server/actions/workflows/test-database.yml) | ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/catkatpowered/kat-server/test-database.yml?branch=main&style=flat) | 测试数据库模块 | 25 | | [Tests for Config](https://github.com/CatkatPowered/kat-server/actions/workflows/test-config.yml) | ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/catkatpowered/kat-server/test-config.yml?branch=main&style=flat) | 测试配置文件模块 | 26 | | [Tests for Utils](https://github.com/CatkatPowered/kat-server/actions/workflows/test-utils.yml) | ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/catkatpowered/kat-server/test-utils.yml?branch=main&style=flat) | 测试工具类 | 27 | | [Tests for TokenPool](https://github.com/CatkatPowered/kat-server/actions/workflows/test-tokenpool.yml) | ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/catkatpowered/kat-server/test-tokenpool.yml?branch=main&style=flat) | 测试 Token 池 | 28 | | [Tests for EventBus](https://github.com/CatkatPowered/kat-server/actions/workflows/test-event.yml) | ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/catkatpowered/kat-server/test-event.yml?branch=main&style=flat) | 测试事件总线 | 29 | | [Tests for Network](https://github.com/CatkatPowered/kat-server/actions/workflows/test-network.yml) | ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/catkatpowered/kat-server/test-network.yml?branch=main&style=flat) | 测试网络模块 | 30 | | [FOSSA License Scan](https://app.fossa.com/projects/git%2Bgithub.com%2FCatkatPowered%2Fkat-server?utm_source=share_link) | [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FCatkatPowered%2Fkat-server.svg?type=small)](https://app.fossa.com/projects/git%2Bgithub.com%2FCatkatPowered%2Fkat-server?ref=badge_small) | 扫描项目以及依赖开源证书 | 31 | 32 | ## 🍉 条款与声明 33 | 34 | 本项目具有 [隐私政策](https://project.catkatpowered.com/#/privacy-policy)、[使用条款](https://project.catkatpowered.com/#/terms-of-use) 35 | 和 [开源声明](https://project.catkatpowered.com/#/open-source-license) 36 | 37 | ## ✨ Quick Start 38 | 39 | [千里之行,始于 Quick Start](https://project.catkatpowered.com/#/kat-server-quick-start) 将描述如何快速启动和调试 Kat Server 40 | 41 | ## 📝 文档 42 | 43 | 在 [这里](https://project.catkatpowered.com/#/README) 开始阅读完整文档,文档包含各个模块的设计思路、如何编写扩展等内容 44 | 45 | ## ⚖ 开源协议 46 | 47 | AGPLv3 -- 这意味着基于本项目开发或者二次开发本项目以及与本项目通过网络接触的项目**都需要通过 AGPLv3 开源**,由于项目开发以及使用的过程中有可能会接触到个人账号密码等敏感信息,使用 AGPLv3 48 | 开源可以保证这些信息的处理流程是透明的 49 | 50 | [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FCatkatPowered%2Fkat-server.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2FCatkatPowered%2Fkat-server?ref=badge_large) 51 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/network/utils/KatCertUtil.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network.utils; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 5 | import java.math.BigInteger; 6 | import java.security.*; 7 | import java.security.cert.Certificate; 8 | import java.util.Calendar; 9 | import java.util.Random; 10 | import org.bouncycastle.asn1.ASN1Sequence; 11 | import org.bouncycastle.asn1.x500.X500Name; 12 | import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; 13 | import org.bouncycastle.cert.X509CertificateHolder; 14 | import org.bouncycastle.cert.X509v3CertificateBuilder; 15 | import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; 16 | import org.bouncycastle.jce.provider.BouncyCastleProvider; 17 | import org.bouncycastle.operator.ContentSigner; 18 | import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; 19 | import org.eclipse.jetty.util.ssl.SslContextFactory; 20 | 21 | public class KatCertUtil { 22 | 23 | private static KeyStore keyStore; 24 | 25 | public static SslContextFactory.Server getSslContextFactory() { 26 | if ( 27 | KatServer.KatConfigAPI 28 | .getConfig( 29 | KatConfigNodeConstants.KAT_CONFIG_NETWORK_CUSTOM_CERT_ENABLED 30 | ) 31 | .get() 32 | ) { 33 | // 自定义证书 34 | SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); 35 | sslContextFactory.setKeyStorePath( 36 | KatServer.KatConfigAPI 37 | .getConfig( 38 | KatConfigNodeConstants.KAT_CONFIG_NETWORK_CUSTOM_CERT_PATH 39 | ) 40 | .get() 41 | ); 42 | sslContextFactory.setKeyStorePassword( 43 | KatServer.KatConfigAPI 44 | .getConfig( 45 | KatConfigNodeConstants.KAT_CONFIG_NETWORK_CUSTOM_CERT_PASSWORD 46 | ) 47 | .get() 48 | ); 49 | return sslContextFactory; 50 | } else { 51 | // 生成一次性自签证书 52 | SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); 53 | KeyStore keyStore = getKeyStore(); 54 | sslContextFactory.setKeyStore(keyStore); 55 | sslContextFactory.setKeyStorePassword("catmoe"); 56 | return sslContextFactory; 57 | } 58 | } 59 | 60 | @SuppressWarnings("SpellCheckingInspection") 61 | public static KeyStore getKeyStore() { 62 | if (keyStore == null) { 63 | String password = KatServer.KatConfigAPI 64 | .getConfig( 65 | KatConfigNodeConstants.KAT_CONFIG_NETWORK_SELFGEN_CERT_PASSWORD 66 | ) 67 | .get(); 68 | String alias = KatServer.KatConfigAPI 69 | .getConfig( 70 | KatConfigNodeConstants.KAT_CONFIG_NETWORK_SELFGEN_CERT_ALIAS 71 | ) 72 | .get(); 73 | Security.addProvider(new BouncyCastleProvider()); 74 | try { 75 | KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance( 76 | "RSA", 77 | BouncyCastleProvider.PROVIDER_NAME 78 | ); 79 | keyPairGenerator.initialize(2048); 80 | KeyPair keyPair = keyPairGenerator.generateKeyPair(); 81 | PublicKey publicKey = keyPair.getPublic(); 82 | PrivateKey privateKey = keyPair.getPrivate(); 83 | Certificate CAcertificate = new JcaX509CertificateConverter() 84 | .setProvider(BouncyCastleProvider.PROVIDER_NAME) 85 | .getCertificate( 86 | createCertificate("CN=CA", "CN=CA", publicKey, privateKey) 87 | ); 88 | Certificate CLcertificate = new JcaX509CertificateConverter() 89 | .setProvider(BouncyCastleProvider.PROVIDER_NAME) 90 | .getCertificate( 91 | createCertificate("CN=CA", "CN=CA", publicKey, privateKey) 92 | ); 93 | 94 | java.security.cert.Certificate[] outChain = { 95 | CLcertificate, 96 | CAcertificate, 97 | }; 98 | KeyStore outStore = KeyStore.getInstance("PKCS12"); 99 | outStore.load(null, password.toCharArray()); 100 | outStore.setKeyEntry( 101 | alias, 102 | privateKey, 103 | password.toCharArray(), 104 | outChain 105 | ); 106 | return outStore; 107 | } catch (Exception e) { 108 | e.printStackTrace(); 109 | } 110 | } else { 111 | return keyStore; 112 | } 113 | return null; 114 | } 115 | 116 | private static X509CertificateHolder createCertificate( 117 | String dn, 118 | String issuer, 119 | PublicKey publicKey, 120 | PrivateKey privateKey 121 | ) throws Exception { 122 | X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( 123 | new X500Name(dn), 124 | BigInteger.valueOf(Math.abs(new Random().nextLong())), 125 | Calendar.getInstance().getTime(), 126 | Calendar.getInstance().getTime(), 127 | new X500Name(dn), 128 | SubjectPublicKeyInfo.getInstance( 129 | ASN1Sequence.getInstance(publicKey.getEncoded()) 130 | ) 131 | ); 132 | 133 | ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA") 134 | .setProvider("BC") 135 | .build(privateKey); 136 | return certificateBuilder.build(contentSigner); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/extension/KatExtensionLoader.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.extension; 2 | 3 | import com.catkatpowered.katserver.KatServer; 4 | import com.catkatpowered.katserver.common.constants.KatMiscConstants; 5 | import com.catkatpowered.katserver.extension.event.DisableExtensionEvent; 6 | import com.catkatpowered.katserver.extension.event.EnableExtensionEvent; 7 | import com.catkatpowered.katserver.extension.event.LoadExtensionEvent; 8 | import com.google.gson.Gson; 9 | import java.io.*; 10 | import java.lang.reflect.InvocationTargetException; 11 | import java.net.MalformedURLException; 12 | import java.net.URL; 13 | import java.net.URLClassLoader; 14 | import java.util.*; 15 | import java.util.jar.JarFile; 16 | import java.util.stream.Collectors; 17 | import lombok.extern.slf4j.Slf4j; 18 | 19 | /** 20 | * 读取 扩展 排序 并按依赖排序加载 21 | * 22 | * @author hanbings 23 | * @author suibing112233 24 | */ 25 | @Slf4j 26 | public class KatExtensionLoader { 27 | 28 | private static final KatExtensionLoader Instance = new KatExtensionLoader(); 29 | private final Gson gson = new Gson(); 30 | // 扩展映射图与扩展实例图以及一个描述文件索引 31 | private final Map index = new HashMap<>(); 32 | private final Map> mapping = new HashMap<>(); 33 | private final Map extensions = new HashMap<>(); 34 | 35 | private KatExtensionLoader() {} 36 | 37 | public static KatExtensionLoader getInstance() { 38 | return Instance; 39 | } 40 | 41 | /** 42 | * 加载扩展流程
    43 | * 扫描扩展目录 找到文件名符合的扩展
    44 | * -> 读取扩展的描述文件
    45 | * -> TODO: 根据描述文件中所定义的依赖顺序排列扩展加载顺序
    46 | * -> 通过 ClassLoader 加载描述文件中所定义的主类
    47 | * -> 在 onLoad 以前注入所需的模块
    48 | * -> 分别执行 onLoad onEnable onDisable
    49 | * -> 释放无用资源
    50 | * 加载完成
    51 | *

    52 | * 此方法为入口方法 53 | */ 54 | public void loadExtensions() { 55 | // 获取扩展文件 56 | for (File jar : this.getExtensions()) { 57 | loadExtension(jar); 58 | } 59 | } 60 | 61 | /** 62 | * 注入扩展依赖并调用单个扩展方法 63 | */ 64 | public void loadExtension(File jar) { 65 | // 扩展描述文件 66 | KatExtensionInfo info = this.getExtensionInfo(jar); 67 | // 建立描述文件索引 68 | index.put(info.extension, info); 69 | // 获取扩展主类 70 | Class clazz = loadJar(jar, info.main); 71 | // 保留映射 72 | mapping.put(info, clazz); 73 | // 加载 74 | try { 75 | // 新对象 76 | Object extension = clazz.getDeclaredConstructor().newInstance(); 77 | extensions.put(info, extension); 78 | // 获取方法 -> 按顺序调用 79 | // 广播事件 80 | KatServer.KatEventBusAPI.callEvent(new LoadExtensionEvent(info)); 81 | clazz.getMethod("onLoad").invoke(extension); 82 | // 广播事件 83 | KatServer.KatEventBusAPI.callEvent(new EnableExtensionEvent(info)); 84 | clazz.getMethod("onEnable").invoke(extension); 85 | } catch ( 86 | InstantiationException 87 | | IllegalAccessException 88 | | InvocationTargetException 89 | | NoSuchMethodException exception 90 | ) { 91 | log.error( 92 | "unknown error. cloud not load extension {}.", 93 | info.extension, 94 | exception 95 | ); 96 | } 97 | } 98 | 99 | /** 100 | * 卸载所有扩展 101 | */ 102 | public void unloadExtensions() { 103 | for (Map.Entry entry : index.entrySet()) { 104 | this.unloadExtension(entry.getKey()); 105 | } 106 | } 107 | 108 | /** 109 | * 卸载一个扩展 110 | * 111 | * @param extension 扩展名 112 | */ 113 | public void unloadExtension(String extension) { 114 | KatExtensionInfo info = index.get(extension); 115 | try { 116 | if (index.containsKey(extension)) { 117 | // 获取扩展 118 | KatServer.KatEventBusAPI.callEvent(new DisableExtensionEvent(info)); 119 | } 120 | mapping.get(info).getMethod("onDisable").invoke(extensions.get(info)); 121 | // 卸载成功后移除索引与图 122 | extensions.remove(info); 123 | mapping.remove(info); 124 | index.remove(extension); 125 | } catch ( 126 | IllegalAccessException 127 | | InvocationTargetException 128 | | NoSuchMethodException exception 129 | ) { 130 | log.error("unload {} extension error.", info.extension, exception); 131 | } 132 | } 133 | 134 | /** 135 | * 卸载一个扩展 136 | * 137 | * @param extension 扩展实例 138 | */ 139 | public void unloadExtension(KatExtension extension) { 140 | // extension 表获取描述文件实体类 141 | KatExtensionInfo info = (KatExtensionInfo) extensions 142 | .entrySet() 143 | .stream() 144 | .filter(kvEntry -> Objects.equals(kvEntry.getValue(), extension)) 145 | .map(Map.Entry::getKey) 146 | .collect(Collectors.toSet()); 147 | KatServer.KatEventBusAPI.callEvent(new DisableExtensionEvent(info)); 148 | try { 149 | mapping.get(info).getMethod("onDisable").invoke(extensions.get(info)); 150 | // 卸载成功后移除索引与图 151 | extensions.remove(info); 152 | mapping.remove(info); 153 | index.remove(info.extension); 154 | } catch ( 155 | IllegalAccessException 156 | | InvocationTargetException 157 | | NoSuchMethodException exception 158 | ) { 159 | log.error("unload {} extension error.", info.extension, exception); 160 | } 161 | } 162 | 163 | /** 164 | * 正式加载扩类文件 165 | * 166 | * @param extension 扩展文件 167 | * @param main 主类 168 | * @return 扩展类 169 | */ 170 | public Class loadJar(File extension, String main) { 171 | try { 172 | URLClassLoader loader = new URLClassLoader( 173 | new URL[] { extension.toURI().toURL() } 174 | ); 175 | return loader.loadClass(main); 176 | } catch (MalformedURLException | ClassNotFoundException exception) { 177 | log.error("cloud not load {} extension.", extension.getName(), exception); 178 | } 179 | return null; 180 | } 181 | 182 | /** 183 | * 获取描述文件实体类 184 | * 185 | * @param extension 扩展文件对象 186 | * @return 描述文件实体类或者失败时返回 null 187 | */ 188 | public KatExtensionInfo getExtensionInfo(File extension) { 189 | try { 190 | JarFile jar = new JarFile(extension); 191 | // 获得 Input Stream 192 | InputStream stream = jar.getInputStream( 193 | jar.getJarEntry("extension.json") 194 | ); 195 | // 转 String 196 | String json = new BufferedReader(new InputStreamReader(stream)) 197 | .lines() 198 | .collect(Collectors.joining(System.lineSeparator())); 199 | // 关闭流 200 | stream.close(); 201 | jar.close(); 202 | // 注入依赖 203 | return gson.fromJson(json, KatExtensionInfo.class); 204 | } catch (IOException exception) { 205 | log.error( 206 | "Are you sure {} is a extension?", 207 | extension.getName(), 208 | exception 209 | ); 210 | } 211 | return null; 212 | } 213 | 214 | /** 215 | * 扫描扩展目录 寻找可加载扩展
    216 | * 这里仅检查文件后缀名 217 | * 218 | * @return 包含符合要求可能的扩展文件 219 | */ 220 | public List getExtensions() { 221 | List list = new ArrayList<>(); 222 | File path = new File(KatMiscConstants.KAT_EXTENSIONS_ROOT); 223 | File[] files = path.listFiles(); 224 | if (files != null) { 225 | for (File file : files) { 226 | if (file.isFile() && file.getName().endsWith(".jar")) { 227 | list.add(file); 228 | } 229 | } 230 | } 231 | return list; 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /src/main/java/com/catkatpowered/katserver/KatServer.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver; 2 | 3 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 4 | import com.catkatpowered.katserver.config.KatConfigManager; 5 | import com.catkatpowered.katserver.database.KatDatabaseManager; 6 | import com.catkatpowered.katserver.database.interfaces.DatabaseConnector; 7 | import com.catkatpowered.katserver.event.Event; 8 | import com.catkatpowered.katserver.event.KatEventManager; 9 | import com.catkatpowered.katserver.event.RegisteredListener; 10 | import com.catkatpowered.katserver.event.interfaces.Listener; 11 | import com.catkatpowered.katserver.extension.KatExtension; 12 | import com.catkatpowered.katserver.extension.KatExtensionManager; 13 | import com.catkatpowered.katserver.message.KatUniMessageTypeManager; 14 | import com.catkatpowered.katserver.storage.KatStorageManager; 15 | import com.catkatpowered.katserver.storage.providers.KatStorageProvider; 16 | import com.catkatpowered.katserver.task.KatTaskManager; 17 | import com.catkatpowered.katserver.tokenpool.KatTokenPoolManager; 18 | import java.io.File; 19 | import java.io.InputStream; 20 | import java.util.List; 21 | import java.util.Map; 22 | import java.util.Optional; 23 | import java.util.concurrent.Callable; 24 | import java.util.concurrent.Future; 25 | 26 | /** 27 | * Kat API 入口 28 | * 29 | * @author hanbings 30 | * @author suibing112233 31 | */ 32 | @SuppressWarnings("unused") 33 | public class KatServer { 34 | 35 | // EventBus API 36 | public static final class KatEventBusAPI { 37 | 38 | /** 39 | * 注册事件监听器 40 | * 41 | * @param listener 42 | */ 43 | public static void registerListener(Listener listener) { 44 | KatEventManager.registerListener(listener); 45 | } 46 | 47 | /** 48 | * 注销事件监听器 49 | * 50 | * @param listener 51 | */ 52 | public static void unregisterListener(Listener listener) { 53 | KatEventManager.unregisterListener(listener); 54 | } 55 | 56 | /** 57 | * 调用事件,当事件发生时需要调用此方法 58 | * 59 | * @param event 60 | */ 61 | public static void callEvent(Event event) { 62 | KatEventManager.callEvent(event); 63 | } 64 | 65 | /** 66 | * 获取事件句柄。所有已经注册的事件 67 | * 68 | * @param event 69 | * @return 70 | */ 71 | public static RegisteredListener getEventHandler(Event event) { 72 | return KatEventManager.getEventHandler(event); 73 | } 74 | 75 | /** 76 | * 注册事件 77 | * 78 | * @param event 79 | */ 80 | public static void registerEvent(Event event) { 81 | KatEventManager.registerEvent(event); 82 | } 83 | 84 | /** 85 | * 注销事件 86 | * 87 | * @param event 88 | */ 89 | public static void unregisterEvent(Event event) { 90 | KatEventManager.unregisterEvent(event); 91 | } 92 | } 93 | 94 | // 扩展 API 95 | public static final class KatExtensionAPI { 96 | 97 | public static void loadExtensions() { 98 | KatExtensionManager.loadExtensions(); 99 | } 100 | 101 | public static void loadExtension(File jar) { 102 | KatExtensionManager.loadExtension(jar); 103 | } 104 | 105 | public static void unloadExtensions() { 106 | KatExtensionManager.unloadExtensions(); 107 | } 108 | 109 | public static void unloadExtension(String extension) { 110 | KatExtensionManager.unloadExtension(extension); 111 | } 112 | 113 | public static void unloadExtension(KatExtension extension) { 114 | KatExtensionManager.unloadExtension(extension); 115 | } 116 | } 117 | 118 | // KatUniMessageType API 119 | public static final class KatUniMessageTypeAPI { 120 | 121 | public static boolean addMessageType(String msgType) { 122 | return KatUniMessageTypeManager.addMessageType(msgType); 123 | } 124 | } 125 | 126 | // KatConfig API 127 | public static final class KatConfigAPI { 128 | 129 | public static Map getConfig() { 130 | return KatConfigManager.getAllConfig(); 131 | } 132 | 133 | /** 134 | * 通过节点表达方式获取配置文件内容,参照 {@link KatConfigNodeConstants} 135 | * 136 | * @param 配置内容的具体类型 137 | * @param configNode 配置文件的节点表示方法 138 | * @return 由 {@link Optional} 包装的配置内容 139 | */ 140 | public static Optional getConfig(String configNode) { 141 | return KatConfigManager.getConfig(configNode); 142 | } 143 | } 144 | 145 | // KatDatabase API 146 | 147 | /** 148 | * 封装对数据库的操作 149 | */ 150 | public static final class KatDatabaseAPI { 151 | 152 | /** 153 | * 注册自定义 {@link DatabaseConnector} 154 | * 155 | * @param connector 准备注册的DatabaseConnector 156 | * @see DatabaseConnector 157 | */ 158 | public static void register(DatabaseConnector connector) { 159 | KatDatabaseManager.register(connector); 160 | } 161 | 162 | /** 163 | * 在集合中创建新的对象 164 | * 165 | * @param collection 166 | * @param data 167 | */ 168 | public static void create(String collection, Object... data) { 169 | for (Object object : data) { 170 | KatDatabaseManager.create(collection, object); 171 | } 172 | } 173 | 174 | /** 175 | * 在集合中创建新的对象 176 | * 177 | * @param collection 178 | * @param data 179 | */ 180 | public static void create(String collection, List data) { 181 | KatDatabaseManager.create(collection, data); 182 | } 183 | 184 | /** 185 | * 更新数据库中的对象 186 | * 187 | * @param collection 188 | * @param index 189 | * @param data 190 | */ 191 | public static void update( 192 | String collection, 193 | Map index, 194 | Object data 195 | ) { 196 | KatDatabaseManager.update(collection, index, data); 197 | } 198 | 199 | /** 200 | * 删除数据库中的对象 201 | * 202 | * @param collection 203 | * @param index 204 | */ 205 | public static void delete(String collection, Map index) { 206 | KatDatabaseManager.delete(collection, index); 207 | } 208 | 209 | /** 210 | * 读取数据库中的对象 211 | * 212 | * @param 213 | * @param collection 214 | * @param index 215 | * @param type 216 | * @return 217 | */ 218 | public static List read( 219 | String collection, 220 | Map index, 221 | Class type 222 | ) { 223 | return KatDatabaseManager.read(collection, index, type); 224 | } 225 | 226 | /** 227 | * 查询数据库中的对象 228 | */ 229 | public static List search( 230 | String collection, 231 | String data, 232 | V top, 233 | V bottom, 234 | int limit, 235 | Class type 236 | ) { 237 | return KatDatabaseManager.search( 238 | collection, 239 | data, 240 | top, 241 | bottom, 242 | limit, 243 | type 244 | ); 245 | } 246 | } 247 | 248 | /** 249 | * 封装对任务的操作 250 | */ 251 | public static final class KatTaskAPI { 252 | 253 | public static Future addTask(Runnable task) { 254 | return KatTaskManager.addTask(task); 255 | } 256 | 257 | public static Future addTask(Callable task) { 258 | return KatTaskManager.addTask(task); 259 | } 260 | 261 | public static Future addTask(Runnable task, T result) { 262 | return KatTaskManager.addTask(task, result); 263 | } 264 | 265 | public static void exec(Runnable task) { 266 | KatTaskManager.exec(task); 267 | } 268 | } 269 | 270 | /** 271 | * 封装对TokenPool的操作 272 | */ 273 | public static final class KatTokenPoolAPI { 274 | 275 | /** 276 | * 生成新的 token 277 | * 278 | * @return 返回 token 内容 279 | */ 280 | public static String newToken() { 281 | return KatTokenPoolManager.newToken(); 282 | } 283 | 284 | /** 285 | * 撤销token 286 | * 287 | * @param tokeString 288 | * @return 撤销状态 289 | */ 290 | public static boolean revokeToken(String tokeString) { 291 | return KatTokenPoolManager.revokeToken(tokeString); 292 | } 293 | 294 | /** 295 | * 检查token是否过期 296 | * 297 | * @param token 298 | * @return 过期状态 299 | */ 300 | public static boolean checkToken(String token) { 301 | return KatTokenPoolManager.checkToken(token); 302 | } 303 | } 304 | 305 | public static final class KatStorageAPI { 306 | 307 | /** 308 | * 获取当前的 StorageProvider 309 | * 310 | * @return 311 | */ 312 | public static KatStorageProvider getStorageProvider() { 313 | return KatStorageManager.getStorageProvider(); 314 | } 315 | 316 | /** 317 | * 注册新的储存提供者 318 | * 319 | * @param name 储存提供者名称 320 | * @param newKatStorageProvider 储存提供者实现 321 | * @see KatStorageProviderManager 322 | */ 323 | public static void registerStorageProvider( 324 | String name, 325 | KatStorageProvider newKatStorageProvider 326 | ) { 327 | KatStorageManager.registerStorageProvider(name, newKatStorageProvider); 328 | } 329 | 330 | /** 331 | * 拉取资源文件。 332 | * 333 | * @param hashString 334 | * @return 335 | */ 336 | public static InputStream fetch(String hashString) { 337 | return KatStorageManager.fetch(hashString); 338 | } 339 | 340 | /** 341 | * 校验文件是否正确 342 | * 343 | * @param hashString 344 | * @return 345 | */ 346 | public static boolean validate(String hashString) { 347 | return KatStorageManager.validate(hashString); 348 | } 349 | 350 | /** 351 | * 上传文件 352 | * 353 | * @param resource 包含信息的容器 354 | * @return 355 | */ 356 | public static void upload(String fileHash, InputStream inputStream) { 357 | KatStorageManager.upload(fileHash, inputStream); 358 | } 359 | 360 | /** 361 | * 删除文件。 362 | * 363 | * @param hashString 文件hash值 364 | * @return 365 | */ 366 | public static boolean delete(String hashString) { 367 | return KatStorageManager.delete(hashString); 368 | } 369 | } 370 | } 371 | -------------------------------------------------------------------------------- /src/test/java/com/catkatpowered/katserver/network/TestKatNetwork.java: -------------------------------------------------------------------------------- 1 | package com.catkatpowered.katserver.network; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import com.catkatpowered.katserver.KatServer; 7 | import com.catkatpowered.katserver.common.constants.KatConfigNodeConstants; 8 | import com.catkatpowered.katserver.config.KatConfig; 9 | import com.catkatpowered.katserver.database.KatDatabaseManager; 10 | import com.catkatpowered.katserver.event.KatEventManager; 11 | import com.catkatpowered.katserver.event.events.MessageReceiveEvent; 12 | import com.catkatpowered.katserver.event.events.MessageSendEvent; 13 | import com.catkatpowered.katserver.event.interfaces.EventHandler; 14 | import com.catkatpowered.katserver.event.interfaces.Listener; 15 | import com.catkatpowered.katserver.extension.KatExtensionManager; 16 | import com.catkatpowered.katserver.message.KatUniMessage; 17 | import com.catkatpowered.katserver.network.utils.KatCertUtil; 18 | import com.catkatpowered.katserver.storage.KatStorageManager; 19 | import com.catkatpowered.katserver.task.KatTaskManager; 20 | import com.google.gson.Gson; 21 | import java.security.KeyStore; 22 | import java.security.SecureRandom; 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | import java.util.concurrent.TimeUnit; 26 | import javax.net.ssl.HostnameVerifier; 27 | import javax.net.ssl.KeyManagerFactory; 28 | import javax.net.ssl.SSLContext; 29 | import javax.net.ssl.SSLSession; 30 | import javax.net.ssl.TrustManager; 31 | import javax.net.ssl.X509TrustManager; 32 | import okhttp3.OkHttpClient; 33 | import okhttp3.Request; 34 | import okhttp3.Response; 35 | import okhttp3.WebSocket; 36 | import okhttp3.WebSocketListener; 37 | import org.jetbrains.annotations.NotNull; 38 | import org.junit.jupiter.api.BeforeAll; 39 | import org.junit.jupiter.api.Test; 40 | import org.tomlj.Toml; 41 | import org.tomlj.TomlParseResult; 42 | 43 | public class TestKatNetwork { 44 | 45 | private static OkHttpClient wsClient; 46 | private static Boolean connected = null; 47 | private static final KatUniMessage plainTextMessage = KatUniMessage 48 | .builder() 49 | .extensionID("testExtension") 50 | .messageType("PlainMessage") 51 | .messageGroup("101010101") 52 | .messageID("uuid") 53 | .messageContent("欸嘿~") 54 | .messageTimeStamp(1652881882L) 55 | .build(); 56 | 57 | @SuppressWarnings("SpellCheckingInspection") 58 | private static final String defaultConfig = 59 | """ 60 | ######################### Network ############################# 61 | [network] 62 | network_port = 25565 63 | 64 | [network.selfgen_cert] 65 | cert_password = "catmoe" 66 | cert_alias = "catmoe" 67 | 68 | [network.custom_cert] 69 | enabled = false 70 | cert_path = "./cert.jks" 71 | cert_password = "catmoe" 72 | 73 | ######################### Database ############################ 74 | [database] 75 | # default support mongodb 76 | # demo database_url: 77 | # mongodb: mongodb://localhost:27017/database_name 78 | # 79 | # Note: No need to carry username and password in url 80 | database_url = "mongodb://localhost:27017/kat-server" 81 | database_username = "" 82 | database_password = "" 83 | 84 | ####################### Storage ############################### 85 | # The resource file storage 86 | [resource] 87 | # You can choose those type of storage_provider 88 | # 1.local 89 | storage_provider = "local" 90 | 91 | # If you choose `local`, 92 | # you can set the resource file where to store. 93 | data_folder_path = "./data" 94 | 95 | ####################### ExecThreads ############################ 96 | [exec] 97 | exec_threads = 16 98 | 99 | ####################### TokenPool ############################## 100 | # This section are the settings of token pool 101 | 102 | [tokenpool] 103 | # You can set the token how long to live 104 | # 105 | # Unit: Millisecond 106 | outdated = 10000 107 | """; 108 | 109 | @BeforeAll 110 | public static void start() { 111 | // 启动配置文件模块 112 | Map config = new HashMap<>(); 113 | TomlParseResult toml = Toml.parse(defaultConfig); 114 | for (Map.Entry entry : toml.dottedEntrySet()) { 115 | config.put(entry.getKey(), entry.getValue()); 116 | } 117 | KatConfig.getInstance().setConfigContent(config); 118 | // 启动事件总线模块 119 | KatEventManager.init(); 120 | // 启动网络模块 121 | KatNetworkManager.init(); 122 | // 启动数据库 123 | KatDatabaseManager.init(); 124 | // 启动储存模块 125 | KatStorageManager.init(); 126 | // 启动多线程模块 127 | KatTaskManager.init(); 128 | // 启动扩展模块 129 | KatExtensionManager.init(); 130 | 131 | KeyStore keyStore = KatCertUtil.getKeyStore(); 132 | SSLContext sslContext = null; 133 | 134 | X509TrustManager trustManager = null; 135 | try { 136 | trustManager = 137 | new X509TrustManager() { 138 | @Override 139 | public void checkClientTrusted( 140 | java.security.cert.X509Certificate[] chain, 141 | String authType 142 | ) {} 143 | 144 | @Override 145 | public void checkServerTrusted( 146 | java.security.cert.X509Certificate[] chain, 147 | String authType 148 | ) {} 149 | 150 | @Override 151 | public java.security.cert.X509Certificate[] getAcceptedIssuers() { 152 | return new java.security.cert.X509Certificate[] {}; 153 | } 154 | }; 155 | } catch (Exception e) { 156 | e.printStackTrace(); 157 | } 158 | 159 | try { 160 | sslContext = SSLContext.getInstance("SSL"); 161 | KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( 162 | KeyManagerFactory.getDefaultAlgorithm() 163 | ); 164 | keyManagerFactory.init(keyStore, "catmoe".toCharArray()); 165 | sslContext.init( 166 | keyManagerFactory.getKeyManagers(), 167 | new TrustManager[] { trustManager }, 168 | new SecureRandom() 169 | ); 170 | } catch (Exception e) { 171 | e.printStackTrace(); 172 | } 173 | // 初始化客户端 174 | wsClient = 175 | new OkHttpClient.Builder() 176 | .readTimeout(0, TimeUnit.MILLISECONDS) 177 | .sslSocketFactory(sslContext.getSocketFactory(), trustManager) 178 | .hostnameVerifier( 179 | new HostnameVerifier() { 180 | @Override 181 | public boolean verify(String hostname, SSLSession session) { 182 | return true; 183 | } 184 | } 185 | ) 186 | .build(); 187 | } 188 | 189 | @Test 190 | public void connection() throws InterruptedException { 191 | Request request = new Request.Builder() 192 | .url( 193 | "wss://localhost:" + 194 | KatServer.KatConfigAPI 195 | .getConfig(KatConfigNodeConstants.KAT_CONFIG_NETWORK_PORT) 196 | .get() + 197 | "/websocket" 198 | ) 199 | .build(); 200 | class Listener extends WebSocketListener { 201 | 202 | @Override 203 | public void onOpen( 204 | @NotNull WebSocket webSocket, 205 | @NotNull Response response 206 | ) { 207 | connected = true; 208 | } 209 | 210 | @Override 211 | public void onClosed( 212 | @NotNull WebSocket webSocket, 213 | int code, 214 | @NotNull String reason 215 | ) { 216 | connected = false; 217 | } 218 | 219 | @Override 220 | public void onFailure( 221 | WebSocket webSocket, 222 | Throwable t, 223 | Response response 224 | ) { 225 | connected = false; 226 | } 227 | } 228 | wsClient.newWebSocket(request, new Listener()); 229 | while (true) { 230 | Thread.currentThread().join(1000); 231 | if (connected != null) break; 232 | } 233 | assertTrue(connected); 234 | connected = null; 235 | } 236 | 237 | @Test 238 | public void newMessageBroadcast() throws InterruptedException { 239 | connected = false; 240 | Request request = new Request.Builder() 241 | .url( 242 | "wss://localhost:" + 243 | KatServer.KatConfigAPI 244 | .getConfig(KatConfigNodeConstants.KAT_CONFIG_NETWORK_PORT) 245 | .get() + 246 | "/websocket" 247 | ) 248 | .build(); 249 | class Listener extends WebSocketListener { 250 | 251 | @Override 252 | public void onMessage(@NotNull WebSocket webSocket, String text) { 253 | if (text.contains("server_description")) { 254 | connected = true; 255 | return; 256 | } 257 | // {"message":{"message_type":"testExtension","extension_id":"PlainMessage","message_group":"101010101","message_id":"uuid","message_content":"欸嘿~","message_timestamp":1652881882},"type":"websocket_message"} 258 | assertEquals( 259 | text, 260 | "{\"message\":{\"message_type\":\"testExtension\",\"extension_id\":\"PlainMessage\",\"message_group\":\"101010101\",\"message_id\":\"uuid\",\"message_content\":\"欸嘿~\",\"message_timestamp\":1652881882},\"type\":\"websocket_message\"}" 261 | ); 262 | connected = null; 263 | } 264 | } 265 | 266 | wsClient.newWebSocket(request, new Listener()); 267 | while (true) { 268 | Thread.currentThread().join(2000); 269 | if (connected) break; 270 | } 271 | KatEventManager.callEvent( 272 | MessageReceiveEvent.builder().message(plainTextMessage).build() 273 | ); 274 | } 275 | 276 | @Test 277 | public void newMessageIncome() { 278 | Request request = new Request.Builder() 279 | .url( 280 | "wss://localhost:" + 281 | KatServer.KatConfigAPI 282 | .getConfig(KatConfigNodeConstants.KAT_CONFIG_NETWORK_PORT) 283 | .get() + 284 | "/websocket" 285 | ) 286 | .build(); 287 | WebSocket webSocket = wsClient.newWebSocket( 288 | request, 289 | new WebSocketListener() {} 290 | ); 291 | Gson gson = new Gson(); 292 | class eventListener implements Listener { 293 | 294 | @EventHandler 295 | public void onMessage(MessageSendEvent event) { 296 | assertEquals( 297 | gson.toJson(event.getMessage()), 298 | "{\"message\":{\"message_type\":\"PlainMessage\",\"extension_id\":\"testExtension\",\"message_group\":\"101010101\",\"message_id\":\"uuid\",\"message_content\":\"欸嘿~\",\"message_timestamp\":1652881882},\"type\":\"websocket_message\"}" 299 | ); 300 | } 301 | } 302 | KatServer.KatEventBusAPI.registerListener(new eventListener()); 303 | webSocket.send( 304 | "{\"message\":{\"message_type\":\"PlainMessage\",\"extension_id\":\"testExtension\",\"message_group\":\"101010101\",\"message_id\":\"uuid\",\"message_content\":\"欸嘿~\",\"message_timestamp\":1652881882},\"type\":\"websocket_message\"}" 305 | ); 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------