Skip to content

Commit

Permalink
4.9 / httpapi新增post方法, 调整版本号结构
Browse files Browse the repository at this point in the history
  • Loading branch information
Dituon committed Oct 6, 2022
1 parent 85cf5c8 commit 789feef
Show file tree
Hide file tree
Showing 13 changed files with 222 additions and 74 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ apply plugin: "java"


group = 'xmmt.dituon'
version = '4.8'
version = '4.9'

repositories {
maven { url 'https://maven.aliyun.com/repository/public' }
Expand Down
76 changes: 51 additions & 25 deletions config/xmmt.dituon.petpet/PetPet.yml
Original file line number Diff line number Diff line change
@@ -1,25 +1,51 @@
content:
command: pet
probability: 30
antialias: true
disabled: []
commandHead: ''
respondSelfNudge: false
respondReply: true
cachePoolSize: 10000
keyListFormat: FORWARD
disablePolicy: FULL
disabledGroups: []
fuzzy: false
strictCommand: true
synchronized: false
gifEncoder: ANIMATED_LIB
gifMaxSize:
- 200
- 200
- 32
gifQuality: 90
headless: true
autoUpdate: true
repositoryUrl: 'https://raw.githubusercontent.com/Dituon/petpet/main'
devMode: false
# 触发 petpet 的指令
command: pet
# 使用 戳一戳 的触发概率
probability: 30
# 是否使用抗锯齿
antialias: true
# 禁用列表
disabled: []
# keyCommand前缀
commandHead: ''
# 是否响应机器人发出的戳一戳
respondSelfNudge: false
# 是否使用响应回复
respondReply: true
# 消息缓存池容量
cachePoolSize: 10000
# keyList响应格式
keyListFormat: FORWARD
# 禁用策略
disablePolicy: FULL
# 禁用群聊列表
disabledGroups: []
# 是否使用模糊匹配用户名
fuzzy: false
# 是否使用严格匹配模式
strictCommand: true
# 是否使用消息事件同步锁
synchronized: false
# GIF编码器
gifEncoder: ANIMATED_LIB
# GIF缩放阈值/尺寸
gifMaxSize:
- 200
- 200
- 32
# GIF质量, 仅适用于ANIMATED_LIB编码器
gifQuality: 90
# 是否使用headless模式
headless: true
# 是否自动从仓库同步PetData
autoUpdate: true
# 用于自动更新的仓库地址
repositoryUrl: 'https://raw.githubusercontent.com/Dituon/petpet/main'
# 是否启用开发模式(支持热重载)
devMode: false
# 触发图片生成后的用户冷却时长(填入-1则禁用,单位为秒)
coolDown: 10
# 触发图片生成后的群聊冷却时长
groupCoolDown: -1
# 触发冷却后的回复消息, '[nudge]'为戳一戳
inCoolDownMessage: 技能冷却中...
25 changes: 18 additions & 7 deletions editor/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,24 @@ function Text(text) {
}

this.id = textList.length
$('#elementBar').append(`<div class="element text" id="t${this.id}"><div class="typeText">Text ${this.id}</div>` +
'<div class="check" title="">color<input type="color" class="color"></div>' +
'<div class="check">size<input type="number" class="typein size" value="8"></div>' +
'<select class="textAlign"><option value="LEFT">左对齐</option><option value="RIGHT">右对齐</option><option value="CENTER">居中</option></select>' +
'<select class="textWrap"><option value="NONE">不换行</option><option value="BREAK">自动换行</option><option value="ZOOM">自动缩放</option></select>' +
'<div class="check setWidth" style="display: none">maxWidth<input type="number" class="typein width" value="0"></div>' +
'<div class="check deleteText">delete</div></div>')
$('#elementBar').append(`
<div class="element text" id="t${this.id}">
<div class="typeText">Text ${this.id}</div>
<div class="check" title="">color<input type="color" class="color"></div>
<div class="check">size<input type="number" class="typein size" value="8"></div>
<select class="textAlign">
<option value="LEFT">左对齐</option>
<option value="RIGHT">右对齐</option>
<option value="CENTER">居中</option>
</select>
<select class="textWrap">
<option value="NONE">不换行</option>
<option value="BREAK">自动换行</option>
<option value="ZOOM">自动缩放</option>
</select>
<div class="check setWidth" style="display: none">maxWidth<input type="number" class="typein width" value="0"></div>
<div class="check deleteText">delete</div>
</div>`)
}

$('#elementBar').on('change', '.text .color', function () {
Expand Down
2 changes: 1 addition & 1 deletion index.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": 4.8,
"version": 4.9,
"dataList": [
"peep",
"watch_tv",
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/xmmt/dituon/plugin/DataUpdater.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ public static void updateData() {
public static boolean checkUpdate() {
UpdateIndex update = UpdateIndex.getUpdate(
Objects.requireNonNull(getUrlText(Petpet.service.repositoryUrl + "/index.json")));
if (Petpet.VERSION != update.getVersion())
if (BasePetService.VERSION != update.getVersion())
System.out.println("PetpetPlugin可更新到最新版本: " + update.getVersion() +
" (当前版本 " + Petpet.VERSION + ") 要养成经常更新的好习惯哦 (*/ω\*)");
" (当前版本 " + BasePetService.VERSION + ") 要养成经常更新的好习惯哦 (*/ω\*)");
for (String pet : update.getDataList()) {
if (Petpet.service.getDataMap().containsKey(pet)
|| Petpet.service.disabledKey.contains(pet)) continue;
Expand Down
7 changes: 3 additions & 4 deletions src/main/java/xmmt/dituon/plugin/Petpet.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import net.mamoe.mirai.event.events.NudgeEvent;
import net.mamoe.mirai.message.data.*;
import xmmt.dituon.share.BaseConfigFactory;
import xmmt.dituon.share.BasePetService;
import xmmt.dituon.share.TextExtraData;

import java.io.File;
Expand All @@ -21,8 +22,6 @@

public final class Petpet extends JavaPlugin {
public static final Petpet INSTANCE = new Petpet();
public static final float VERSION = 4.8F;

private static List<Long> disabledGroup;
public static PluginPetService service;
public static File dataFolder;
Expand All @@ -35,7 +34,7 @@ public final class Petpet extends JavaPlugin {
public static final Random random = new Random();

private Petpet() {
super(new JvmPluginDescriptionBuilder("xmmt.dituon.petpet", String.valueOf(VERSION))
super(new JvmPluginDescriptionBuilder("xmmt.dituon.petpet", String.valueOf(BasePetService.VERSION))
.name("PetPet")
.author("Dituon")
.build());
Expand All @@ -60,7 +59,7 @@ public void onEnable() {

getLogger().info("\n _ _ \n _ __ ___| |_ _ __ ___| |_ \n" +
" | '_ \\ / _ \\ __| | '_ \\ / _ \\ __|\n | |_) | __/ |_ | |_) | __/ |_ \n" +
" | .__/ \\___|\\__| | .__/ \\___|\\__|\n |_| |_| v" + VERSION + " (*^▽^*)");
" | .__/ \\___|\\__| | .__/ \\___|\\__|\n |_| |_| v" + BasePetService.VERSION + " (*^▽^*)");

if (service.probability > 0) GlobalEventChannel.INSTANCE.subscribeAlways(NudgeEvent.class,
service.messageSynchronized ? this::onNudgeSynchronized : this::onNudge);
Expand Down
37 changes: 37 additions & 0 deletions src/main/java/xmmt/dituon/server/PetDataDTO.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package xmmt.dituon.server

import kotlinx.serialization.Serializable
import kotlinx.serialization.Serializer
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import xmmt.dituon.share.AvatarType
import xmmt.dituon.share.BasePetService.VERSION
import xmmt.dituon.share.KeyData
import kotlin.streams.toList

@Serializable
data class PetDataDTO(
val version: Float = VERSION,
val petData: List<PetDataObject>
) {
companion object {
@JvmStatic
fun encodeToString(dataMap: Map<String, KeyData>): String{
val dataList: ArrayList<PetDataObject> = ArrayList()
dataMap.forEach { (key, data) ->
dataList.add(PetDataObject(key, data.avatar.stream().map { a -> a.type }.toList()))
}
return Json.encodeToString(
PetDataDTO(VERSION, dataList)
)
}
}
}

@Serializable
data class PetDataObject(
val key: String,
val types: List<AvatarType>
)


47 changes: 27 additions & 20 deletions src/main/java/xmmt/dituon/server/PetHttpHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,43 @@
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class PetHttpHandler implements HttpHandler {
@Override
public void handle(HttpExchange httpExchange) {
try {
String query = httpExchange.getRequestURI().getRawQuery();
if (query == null) {
StringBuilder json = new StringBuilder("{\"petData\": [");
WebServer.petService.getDataMap().forEach((key, data) -> {
json.append("{\"key\": \"").append(key).append("\", ").append("\"types\": [");
data.getAvatar().forEach(avatar -> { //necessary data
json.append("\"").append(avatar.getType()).append("\", ");
});
if (!data.getAvatar().isEmpty()) json.delete(json.length() - 2, json.length());
json.append("]}, ");
});
if (!WebServer.petService.getDataMap().isEmpty()) json.delete(json.length() - 2, json.length());
json.append("]}");
handleResponse(httpExchange, json.toString());
return;
RequestParser parser;
if (httpExchange.getRequestMethod().equals("GET")) { //GET

String requestParam = httpExchange.getRequestURI().getRawQuery();
if (requestParam == null) {
handleResponse(httpExchange, WebServer.petService.getIndexJson());
return;
}

parser = new GETParser(requestParam);
} else {
//POST
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(httpExchange.getRequestBody(), StandardCharsets.UTF_8)
);

StringBuilder requestBodyContent = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
requestBodyContent.append(line);
}

parser = new POSTParser(requestBodyContent.toString());
}

CommandParser parser = new CommandParser(query);
handleResponse(httpExchange, parser.getImagePair().getFirst(), parser.getImagePair().getSecond());
parser.close();
} catch (Exception ignored) {

} catch (Exception e) {
e.printStackTrace();
handleResponse(httpExchange, 400);
}
}
Expand Down
28 changes: 28 additions & 0 deletions src/main/java/xmmt/dituon/server/RequestDTO.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package xmmt.dituon.server

import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

@Serializable
data class RequestDTO(
val key: String,
val form: TargetDTO = TargetDTO("form", ""),
val to: TargetDTO = TargetDTO("to", ""),
val group: TargetDTO = TargetDTO("group", ""),
val bot: TargetDTO = TargetDTO("bot", ""),
val textList: List<String> = emptyList()
) {
companion object {
@JvmStatic
fun decodeFromString(json: String): RequestDTO {
return Json.decodeFromString(json)
}
}
}

@Serializable
data class TargetDTO(
val name: String,
val avatar: String
)
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,23 @@
import java.util.HashMap;
import java.util.List;

public class CommandParser {
private HashMap<String, String> parameterList = new HashMap<>();
private Pair<InputStream, String> imagePair;
abstract class RequestParser {
Pair<InputStream, String> imagePair;

public CommandParser(String command) {
String[] queryList = command.split("&");
public Pair<InputStream, String> getImagePair() {
return imagePair;
}

public void close() {
imagePair = null;
}
}

class GETParser extends RequestParser {
HashMap<String, String> parameterList = new HashMap<>();
public GETParser(String param) {
System.out.println("DEBUG[GET URL]: " + param);
String[] queryList = param.split("&");
for (String query : queryList) {
String[] parameter = query.split("=");
parameterList.put(parameter[0], URLDecoder.decode(parameter[1], StandardCharsets.UTF_8));
Expand All @@ -29,7 +40,7 @@ private void parser() {
List<String> textList = get("textList") != null ?
Arrays.asList(get("textList").split("\\s+")) : new ArrayList<>();

imagePair = WebServer.petService.generateImage(
super.imagePair = WebServer.petService.generateImage(
get("key"),
BaseConfigFactory.getGifAvatarExtraDataFromUrls(
get("fromAvatar"), get("toAvatar"), get("groupAvatar"), get("botAvatar")
Expand All @@ -42,17 +53,34 @@ private void parser() {
);
}

public String get(String key) {
System.out.println("DEBUG: input: " + key + '=' + parameterList.get(key));
private String get(String key) {
return parameterList.get(key);
}

public Pair<InputStream, String> getImagePair() {
return imagePair;
@Override
public void close(){
super.imagePair = null;
parameterList = null;
}
}

public void close() {
parameterList = null;
imagePair = null;
class POSTParser extends RequestParser{
public POSTParser(String postBody){
System.out.println("DEBUG[POST BODY]: " + postBody);
RequestDTO request = RequestDTO.decodeFromString(postBody);
super.imagePair = WebServer.petService.generateImage(
request.getKey(),
BaseConfigFactory.getGifAvatarExtraDataFromUrls(
request.getForm().getAvatar(),
request.getTo().getAvatar(),
request.getGroup().getAvatar(),
request.getBot().getAvatar()
), new TextExtraData(
request.getForm().getName(),
request.getTo().getName(),
request.getGroup().getName(),
request.getTextList()
), null
);
}
}
Loading

0 comments on commit 789feef

Please sign in to comment.