diff --git a/src/main/java/glous/kleebot/KleeBot.java b/src/main/java/glous/kleebot/KleeBot.java index 5a8190d..dc553bd 100644 --- a/src/main/java/glous/kleebot/KleeBot.java +++ b/src/main/java/glous/kleebot/KleeBot.java @@ -25,6 +25,8 @@ import glous.kleebot.log.Logger; import java.io.*; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; @@ -49,6 +51,7 @@ public static void stop(){ public static Bot botInstance; public static final String ip=(getLocalhost()==null?"127.0.0.1":getLocalhost()); public static List plugins=new ArrayList<>(); + public static boolean ENBALE_DEBUG=null == null ? false : true; static String getLocalhost(){ try { @@ -115,6 +118,7 @@ public static void main(String[] args) throws IOException { System.out.println("NOT SUPPORTED SYSTEM"); System.exit(-1); } + Logger.init(); logger= Logger.getLogger(KleeBot.class); logger.info("Logger已完成初始化"); @@ -138,8 +142,10 @@ public static void main(String[] args) throws IOException { Configuration configuration=new Configuration(); KleeBot.configurationInstance=configuration; configuration.load(new File("kleebot.configuration")); - logger.debug("配置文件: "+configuration.toString()); + System.out.println("配置文件: "+ configuration); config=configuration.serializeToClass(BotConfig.class); + //change debug status + KleeBot.ENBALE_DEBUG=configuration.getBoolean("EnableDebug"); File cacheDir=new File(KleeBot.config.getCacheDir()); if (!cacheDir.exists()){ cacheDir.mkdir(); @@ -181,6 +187,7 @@ public static void main(String[] args) throws IOException { ServiceRegistry.register(GenshinAbyssService.class); ServiceRegistry.register(MCWikiSearchService.class); ServiceRegistry.register(AutoPostService.class); + ServiceRegistry.register(SyncService.class); //start to load plugins File pluginDir=new File("plugins"); if (!pluginDir.exists()){ @@ -219,13 +226,14 @@ public static void main(String[] args) throws IOException { if (mode==1){ for (String service: services) { - configuration.setValue(service,true); + configuration.setValue(service,true,"是否启用 %s 服务".formatted(service)); } configuration.saveToFile(); logger.info("配置文件生成完毕,请修改配置文件以继续。"); System.exit(0); } ServiceRegistry.init(); + System.out.println(Arrays.toString(ServiceRegistry.getAllEnabledService())); ChromeInstance.initialize(); logger.trace("Chrome Driver初始化完成"); Timer.init(); diff --git a/src/main/java/glous/kleebot/config/Configuration.java b/src/main/java/glous/kleebot/config/Configuration.java index 07e2e2b..e363241 100644 --- a/src/main/java/glous/kleebot/config/Configuration.java +++ b/src/main/java/glous/kleebot/config/Configuration.java @@ -19,9 +19,7 @@ public class Configuration { private static final int STATUS_COMMENT=2; private File configFile; private String configContent; - //Integer Key is just a list-like map impl - private Map configNodes; - private Map linear_search_impl; + private Map configNodes; public Configuration(){ } public Configuration(File file){ @@ -29,7 +27,7 @@ public Configuration(File file){ } public String toString(){ StringBuilder builder=new StringBuilder(); - for (Map.Entry entry : + for (Map.Entry entry : configNodes.entrySet()) { builder.append("Key : %s Value: %s(%s) Comment: %s\n".formatted(entry.getKey(),entry.getValue().getValue(),entry.getValue().getValue().getClass().getName(),entry.getValue().getComment())); } @@ -47,7 +45,7 @@ public void load() throws IOException { this.parse(); } - public Map getConfigNodes() { + public Map getConfigNodes() { return configNodes; } @@ -85,9 +83,9 @@ public void mergeClass(Object obj){ } public String save(){ StringBuilder builder=new StringBuilder(); - for (Map.Entry entry : + for (Map.Entry entry : configNodes.entrySet()) { - if (entry.getValue().getKey().equals("__SINGLE_LINE_COMMENT")&&entry.getValue().getValue().equals("__SINGLE_LINE_COMMENT")) + if (entry.getValue().getKey().startsWith("__SINGLE_LINE_COMMENT")&&entry.getValue().getValue().toString().startsWith("__SINGLE_LINE_COMMENT")) builder.append("# ").append(entry.getValue().getComment()).append("\n"); else if (!entry.getValue().getComment().isEmpty()) @@ -101,33 +99,34 @@ public void saveToFile() throws IOException { if (configFile!=null){ FileUtils.writeFile(configFile.getAbsolutePath(),save()); } else{ - exception(0,0,"saveToFile() can be only used in load(java.io.File) method."); + exception(0,0,"saveToFile() can only be used in load(java.io.File) method."); } } public boolean contains(String key){ - return getNode(key)==null; + return getNode(key)!=null; } public void setValue(String key,ConfigNode node){ - int index=this.linear_search_impl.get(key); - this.configNodes.put(index,node); + this.configNodes.put(key, node); } public void setValue(String key,Object value,String comment){ - this.setValue(key, new ConfigNode(key, value, Objects.requireNonNullElse(comment, ""))); - + if(key.equals("")&&value.equals("")&&!comment.equals("")) + this.setValue("__SINGLE_LINE_COMMENT"+comment, new ConfigNode("__SINGLE_LINE_COMMENT"+comment, "__SINGLE_LINE_COMMENT"+comment, comment)); + else + this.setValue(key, new ConfigNode(key, value, comment)); } public void setValue(String key,Object value){ - this.setValue(key,value,""); + this.setValue(key,value,""); } public T get(String key) throws IOException { return (T)getObject(key); } public ConfigNode getNode(String key){ - if (this.linear_search_impl.containsKey(key)){ - int index=this.linear_search_impl.get(key); - return this.configNodes.get(index); - } else{ - return null; + for (Map.Entry entry: + this.configNodes.entrySet()){ + if (entry.getKey().equals(key)) + return entry.getValue(); } + return null; } public String getComment(String key) throws IOException { ConfigNode node=getNode(key); @@ -196,8 +195,7 @@ private void parse() throws IOException { char[] chars=configContent.toCharArray(); int line=0; int col=0; - Map nodes=new LinkedHashMap<>(); - Map linear_search_impl=new LinkedHashMap<>(); + Map nodes=new LinkedHashMap<>(); String key=""; String val=""; String comment=""; @@ -229,14 +227,12 @@ private void parse() throws IOException { } if (!val.equals("")||!key.equals("")) { Object oVal = getVal(val); - nodes.put(serialCode,new ConfigNode(key,oVal,comment)); - linear_search_impl.put(key,serialCode); + nodes.put(key,new ConfigNode(key,oVal,comment)); } //judge if is a single line comment if (val.equals("") && key.equals("")) { //save as a single line comment - nodes.put(serialCode,new SingleLineCommentNode("","",comment)); - } + nodes.put("__SINGLE_LINE_COMMENT"+comment,new ConfigNode("__SINGLE_LINE_COMMENT"+comment,"__SINGLE_LINE_COMMENT"+comment,comment)); } key=""; val=""; comment=""; @@ -259,13 +255,13 @@ private void parse() throws IOException { } if (!val.equals("")||!key.equals("")) { Object oVal = getVal(val); - nodes.put(serialCode,new ConfigNode(key,oVal,comment)); - linear_search_impl.put(key,serialCode); + + nodes.put(key,new ConfigNode(key,oVal,comment)); } //judge if is a single line comment if (val.equals("") && key.equals("")) { //save as a single line comment - nodes.put(serialCode,new SingleLineCommentNode("","",comment)); + nodes.put("__SINGLE_LINE_COMMENT"+comment,new ConfigNode("__SINGLE_LINE_COMMENT"+comment,"__SINGLE_LINE_COMMENT"+comment,comment)); } key=""; val=""; @@ -282,7 +278,6 @@ private void parse() throws IOException { } } this.configNodes=nodes; - this.linear_search_impl=linear_search_impl; } private Object getVal(String origin) throws IOException { //parse val line by line diff --git a/src/main/java/glous/kleebot/features/pixiv/PixivAPI.java b/src/main/java/glous/kleebot/features/pixiv/PixivAPI.java index 45340dd..23d44d8 100644 --- a/src/main/java/glous/kleebot/features/pixiv/PixivAPI.java +++ b/src/main/java/glous/kleebot/features/pixiv/PixivAPI.java @@ -65,19 +65,28 @@ public HashMap getArtwork(int illustid) { return artwork; } public HashMap> getDailyRanking() throws IOException { - return getRanking(References.PIXIV_RANKING_DAILY); + return getRanking(References.PIXIV_RANKING_DAILY,true); } public HashMap> getWeeklyRanking() throws IOException { - return getRanking(References.PIXIV_RANKING_WEEKLY); + return getRanking(References.PIXIV_RANKING_WEEKLY,true); } public HashMap> getMonthlyRanking() throws IOException { - return getRanking(References.PIXIV_RANKING_MONTHLY); + return getRanking(References.PIXIV_RANKING_MONTHLY,true); } - public HashMap> getRanking(String url) throws IOException { + public HashMap> getDailyRanking(boolean useCache) throws IOException { + return getRanking(References.PIXIV_RANKING_DAILY,useCache); + } + public HashMap> getWeeklyRanking(boolean useCache) throws IOException { + return getRanking(References.PIXIV_RANKING_WEEKLY,useCache); + } + public HashMap> getMonthlyRanking(boolean useCache) throws IOException { + return getRanking(References.PIXIV_RANKING_MONTHLY,useCache); + } + public HashMap> getRanking(String url,boolean useCache) throws IOException { HashMap> result=new HashMap<>(); String retApi; byte[] cacheContent; - if ((cacheContent=CacheFactory.getCache(url))!=null){ + if ((cacheContent=CacheFactory.getCache(url))!=null&&useCache){ retApi=new String(cacheContent,StandardCharsets.UTF_8); } else{ retApi= new String(FileUtils.download(url,proxy), StandardCharsets.UTF_8); diff --git a/src/main/java/glous/kleebot/log/Logger.java b/src/main/java/glous/kleebot/log/Logger.java index 72ae6ae..5922860 100644 --- a/src/main/java/glous/kleebot/log/Logger.java +++ b/src/main/java/glous/kleebot/log/Logger.java @@ -1,5 +1,7 @@ package glous.kleebot.log; +import glous.kleebot.KleeBot; + import java.io.*; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; @@ -73,12 +75,14 @@ public void trace(String message){ } } public void debug(String message){ - String formattedMessage=getFormattedMessage("DEBUG",message); - System.out.print(formattedMessage); - try { - writer.write(formattedMessage); - } catch (IOException e) { - e.printStackTrace(); + if (KleeBot.ENBALE_DEBUG){ + String formattedMessage=getFormattedMessage("DEBUG",message); + System.out.print(formattedMessage); + try { + writer.write(formattedMessage); + } catch (IOException e) { + e.printStackTrace(); + } } } public void error(String message){ diff --git a/src/main/java/glous/kleebot/services/GroupService.java b/src/main/java/glous/kleebot/services/GroupService.java index ddeacc3..7bad1bb 100644 --- a/src/main/java/glous/kleebot/services/GroupService.java +++ b/src/main/java/glous/kleebot/services/GroupService.java @@ -1,5 +1,6 @@ package glous.kleebot.services; +import glous.kleebot.KleeBot; import net.mamoe.mirai.event.events.GroupMessageEvent; import net.mamoe.mirai.message.data.At; import net.mamoe.mirai.message.data.MessageChainBuilder; @@ -9,6 +10,32 @@ public boolean process(GroupMessageEvent event){ return false; } public boolean execute(GroupMessageEvent event) throws Exception{ return true; } + private boolean atTrigger(String raw,String cond){ + return raw.startsWith(new At(KleeBot.config.getBotAccount())+cond); + } + private boolean containsTrigger(String raw,String cond){ + return raw.contains(cond); + } + private boolean anyCondition(boolean ...args){ + boolean cond=false; + for (boolean arg : + args) { + if (arg) { + cond=true; + } + } + return cond; + } + private boolean allCondition(boolean ...args){ + boolean cond=true; + for (boolean arg: + args) { + if (!arg) { + cond=false; + } + } + return cond; + } public static void sendMessage(String msg, GroupMessageEvent event){ MessageChainBuilder builder=new MessageChainBuilder(); builder.append(new At(event.getSender().getId())); diff --git a/src/main/java/glous/kleebot/services/ServiceRegistry.java b/src/main/java/glous/kleebot/services/ServiceRegistry.java index c88c2a1..cdf9b57 100644 --- a/src/main/java/glous/kleebot/services/ServiceRegistry.java +++ b/src/main/java/glous/kleebot/services/ServiceRegistry.java @@ -29,7 +29,7 @@ public static void init() throws IOException { } } public static String[] getAllEnabledService(){ - return enabledServiceMap.keySet().toArray(new String[0]); + return enabledServiceMap.keySet().toArray(new String[enabledServiceMap.size()]); } public static String[] getAllRegisteredServices(){ return serviceMap.keySet().toArray(new String[0]); diff --git a/src/main/java/glous/kleebot/services/impl/PixivService.java b/src/main/java/glous/kleebot/services/impl/PixivService.java index 9e7bd6f..2b19624 100644 --- a/src/main/java/glous/kleebot/services/impl/PixivService.java +++ b/src/main/java/glous/kleebot/services/impl/PixivService.java @@ -100,7 +100,7 @@ else if (type.equals("monthly")) if (serialNum>ranking.size()+1||serialNum<1){ return false; } - HashMap artwork=ranking.get(serialNum+1); + HashMap artwork=ranking.get(serialNum-1); sendRankMessage(event, artwork); } else{ String illustid=method; diff --git a/src/main/java/glous/kleebot/services/impl/SyncService.java b/src/main/java/glous/kleebot/services/impl/SyncService.java new file mode 100644 index 0000000..56b3e6b --- /dev/null +++ b/src/main/java/glous/kleebot/services/impl/SyncService.java @@ -0,0 +1,71 @@ +package glous.kleebot.services.impl; + +import glous.kleebot.KleeBot; +import glous.kleebot.cache.CacheFactory; +import glous.kleebot.features.pixiv.PixivAPI; +import glous.kleebot.services.GroupService; +import net.mamoe.mirai.event.events.GroupMessageEvent; +import net.mamoe.mirai.message.data.At; + +import java.util.Arrays; +import java.util.HashMap; + +public class SyncService extends GroupService { + @Override + public boolean process(GroupMessageEvent event) { + return event.getMessage().serializeToMiraiCode().startsWith(new At(KleeBot.config.getBotAccount())+" sync "); + } + + @Override + public boolean execute(GroupMessageEvent event) throws Exception { + String message=event.getMessage().serializeToMiraiCode(); + String[] args=message.substring(message.indexOf("sync")+5).split(" "); + if (args[0].equals("info")){ + //pixiv rank sync info + PixivAPI api=new PixivAPI(KleeBot.config.getProxyHost(),KleeBot.config.getProxyPort()); + HashMap> daily=api.getDailyRanking(false); + HashMap> weekly=api.getWeeklyRanking(false); + HashMap> monthly=api.getMonthlyRanking(false); + StringBuilder builder=new StringBuilder(); + builder.append("Pixiv Synchronization Info:\n"); + for (HashMap artwork : + daily.values()) { + String syncInfo= + """ + %s\040""".formatted(artwork.get("title")); + builder.append(syncInfo); + if (CacheFactory.getCache(artwork.get("imageUrl"))==null) + builder.append("\uD83D\uDD34\n"); + else + builder.append("\uD83D\uDFE2\n"); + } + for (HashMap artwork : + weekly.values()) { + String syncInfo= + """ + %s\040""".formatted(artwork.get("title")); + builder.append(syncInfo); + if (CacheFactory.getCache(artwork.get("imageUrl"))==null) + builder.append("\uD83D\uDD34\n"); + else + builder.append("\uD83D\uDFE2\n"); + } + for (HashMap artwork : + monthly.values()) { + String syncInfo= + """ + %s\040""".formatted(artwork.get("title")); + builder.append(syncInfo); + if (CacheFactory.getCache(artwork.get("imageUrl"))==null) + builder.append("\uD83D\uDD34\n"); + else + builder.append("\uD83D\uDFE2\n"); + } + builder.append("END"); + System.out.println(builder.toString()); + sendMessage(builder.toString(),event); + return true ; + } + return false; + } +} diff --git a/src/main/java/glous/kleebot/utils/FileUtils.java b/src/main/java/glous/kleebot/utils/FileUtils.java index b2c9743..f602ec9 100644 --- a/src/main/java/glous/kleebot/utils/FileUtils.java +++ b/src/main/java/glous/kleebot/utils/FileUtils.java @@ -1,6 +1,8 @@ package glous.kleebot.utils; +import glous.kleebot.log.Logger; + import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; @@ -18,6 +20,7 @@ public class FileUtils { public static void enableDebug(int port){ DEBUG_PORT=port; } + private static final Logger logger=Logger.getLogger(FileUtils.class); public static byte[] readFile(String fileName) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName)); ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -81,6 +84,7 @@ public static void writeFile(String fileName, String content) throws IOException writeFile(fileName, content.getBytes(StandardCharsets.UTF_8)); } public static byte[] download(String _url, Proxy proxy, Map extraHeaders) { + long start=System.currentTimeMillis(); try { URL url = new URL(_url); HttpURLConnection conn; @@ -108,11 +112,14 @@ public static byte[] download(String _url, Proxy proxy, Map extra } in.close(); out.close(); + long end=System.currentTimeMillis(); + logger.debug("Total: %d ms".formatted(end-start)); return out.toByteArray(); } catch (Exception e){ e.printStackTrace(); return null; } + } public static byte[] download(String _url) throws IOException { diff --git a/src/main/resources/default.configuration b/src/main/resources/default.configuration index 2474405..69a36fd 100644 --- a/src/main/resources/default.configuration +++ b/src/main/resources/default.configuration @@ -11,4 +11,5 @@ ServicePort: 80 #设置Http服务开放端口 CookieFile: cookie.dat #设置米游社Cookie文件 ResourcePackDir: pages #设置Http静态服务资源包路径 ResourcePackFileDir: resourcePacks #设置Http静态服务资源包释放路径 -SilentMode: true #设置是否输出群内消息 \ No newline at end of file +SilentMode: true #设置是否输出群内消息 +EnableDebug : false #设置是否启用调试模式 \ No newline at end of file diff --git a/src/test/java/shandiankulishe/kleebot/tests/ConfigTest.java b/src/test/java/shandiankulishe/kleebot/tests/ConfigTest.java index b39892d..39ac950 100644 --- a/src/test/java/shandiankulishe/kleebot/tests/ConfigTest.java +++ b/src/test/java/shandiankulishe/kleebot/tests/ConfigTest.java @@ -29,10 +29,10 @@ public void testConfig() throws IOException { """; Configuration configuration=new Configuration(); configuration.load(defaultConfig); - Map map=configuration.getConfigNodes(); - for (Map.Entry entry : + Map map=configuration.getConfigNodes(); + for (Map.Entry entry : map.entrySet()) { - System.out.printf("SerialCode: %d Key: %s Value: %s ValueType: %s Comment: %s\n",entry.getKey(),entry.getValue().getKey(),entry.getValue().getValue(),entry.getValue().getValue().getClass().getName(),entry.getValue().getComment()); + System.out.printf("Key: %s Value: %s ValueType: %s Comment: %s\n",entry.getValue().getKey(),entry.getValue().getValue(),entry.getValue().getValue().getClass().getName(),entry.getValue().getComment()); } System.out.println((String) configuration.get("ProxyHost")); System.out.println(configuration.getString("ProxyHost")); @@ -40,5 +40,7 @@ public void testConfig() throws IOException { config.setQueueSize(128); configuration.mergeClass(config); System.out.println(configuration.save()); + System.out.println(configuration.getBoolean("SilentMode")); + System.out.println(config.isSilentMode()); } } diff --git a/src/test/java/shandiankulishe/kleebot/tests/SkijaTest.java b/src/test/java/shandiankulishe/kleebot/tests/SkijaTest.java deleted file mode 100644 index 07d8c66..0000000 --- a/src/test/java/shandiankulishe/kleebot/tests/SkijaTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package shandiankulishe.kleebot.tests; - -import glous.kleebot.utils.FileUtils; -import org.jetbrains.skija.*; -import org.jetbrains.skija.Canvas; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.ByteChannel; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; - -public class SkijaTest { - @Test - public void testShow() throws IOException { - byte[]bytes=FileUtils.readFile("background.jpg"); - long start=System.currentTimeMillis(); - Surface surface=Surface.makeRasterN32Premul(7340,4200); - Canvas canvas=surface.getCanvas(); - canvas.drawImage(Image.makeFromEncoded(bytes),0,0); - Image image=surface.makeImageSnapshot(); - Data pngData=image.encodeToData(EncodedImageFormat.JPEG); - ByteBuffer byteBuf=pngData.toByteBuffer(); - Path path=Path.of("out.jpg"); - ByteChannel channel=Files.newByteChannel(path,StandardOpenOption.CREATE,StandardOpenOption.TRUNCATE_EXISTING,StandardOpenOption.WRITE); - channel.write(byteBuf); - channel.close(); - Long end=System.currentTimeMillis(); - System.out.println(end-start); - } -}