Skip to content

Commit

Permalink
fix configuration bugs
Browse files Browse the repository at this point in the history
add single line comment
small changes
  • Loading branch information
shandiankulishe committed Apr 23, 2022
1 parent df40394 commit 0196e26
Show file tree
Hide file tree
Showing 12 changed files with 172 additions and 81 deletions.
12 changes: 10 additions & 2 deletions src/main/java/glous/kleebot/KleeBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<Plugin> plugins=new ArrayList<>();
public static boolean ENBALE_DEBUG=null == null ? false : true;
static String getLocalhost(){
try {

Expand Down Expand Up @@ -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已完成初始化");
Expand All @@ -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();
Expand Down Expand Up @@ -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()){
Expand Down Expand Up @@ -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();
Expand Down
53 changes: 24 additions & 29 deletions src/main/java/glous/kleebot/config/Configuration.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,15 @@ 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<Integer,ConfigNode> configNodes;
private Map<String,Integer> linear_search_impl;
private Map<String,ConfigNode> configNodes;
public Configuration(){
}
public Configuration(File file){
this.configFile=file;
}
public String toString(){
StringBuilder builder=new StringBuilder();
for (Map.Entry<Integer,ConfigNode> entry :
for (Map.Entry<String,ConfigNode> 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()));
}
Expand All @@ -47,7 +45,7 @@ public void load() throws IOException {
this.parse();
}

public Map<Integer, ConfigNode> getConfigNodes() {
public Map<String, ConfigNode> getConfigNodes() {
return configNodes;
}

Expand Down Expand Up @@ -85,9 +83,9 @@ public void mergeClass(Object obj){
}
public String save(){
StringBuilder builder=new StringBuilder();
for (Map.Entry<Integer, ConfigNode> entry :
for (Map.Entry<String, ConfigNode> 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())
Expand All @@ -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> 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<String, ConfigNode> 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);
Expand Down Expand Up @@ -196,8 +195,7 @@ private void parse() throws IOException {
char[] chars=configContent.toCharArray();
int line=0;
int col=0;
Map<Integer,ConfigNode> nodes=new LinkedHashMap<>();
Map<String,Integer> linear_search_impl=new LinkedHashMap<>();
Map<String,ConfigNode> nodes=new LinkedHashMap<>();
String key="";
String val="";
String comment="";
Expand Down Expand Up @@ -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="";
Expand All @@ -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="";
Expand All @@ -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
Expand Down
19 changes: 14 additions & 5 deletions src/main/java/glous/kleebot/features/pixiv/PixivAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,19 +65,28 @@ public HashMap<String,String> getArtwork(int illustid) {
return artwork;
}
public HashMap<Integer,HashMap<String,String>> getDailyRanking() throws IOException {
return getRanking(References.PIXIV_RANKING_DAILY);
return getRanking(References.PIXIV_RANKING_DAILY,true);
}
public HashMap<Integer,HashMap<String,String>> getWeeklyRanking() throws IOException {
return getRanking(References.PIXIV_RANKING_WEEKLY);
return getRanking(References.PIXIV_RANKING_WEEKLY,true);
}
public HashMap<Integer,HashMap<String,String>> getMonthlyRanking() throws IOException {
return getRanking(References.PIXIV_RANKING_MONTHLY);
return getRanking(References.PIXIV_RANKING_MONTHLY,true);
}
public HashMap<Integer,HashMap<String,String>> getRanking(String url) throws IOException {
public HashMap<Integer,HashMap<String,String>> getDailyRanking(boolean useCache) throws IOException {
return getRanking(References.PIXIV_RANKING_DAILY,useCache);
}
public HashMap<Integer,HashMap<String,String>> getWeeklyRanking(boolean useCache) throws IOException {
return getRanking(References.PIXIV_RANKING_WEEKLY,useCache);
}
public HashMap<Integer,HashMap<String,String>> getMonthlyRanking(boolean useCache) throws IOException {
return getRanking(References.PIXIV_RANKING_MONTHLY,useCache);
}
public HashMap<Integer,HashMap<String,String>> getRanking(String url,boolean useCache) throws IOException {
HashMap<Integer,HashMap<String,String>> 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);
Expand Down
16 changes: 10 additions & 6 deletions src/main/java/glous/kleebot/log/Logger.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package glous.kleebot.log;

import glous.kleebot.KleeBot;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
Expand Down Expand Up @@ -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){
Expand Down
27 changes: 27 additions & 0 deletions src/main/java/glous/kleebot/services/GroupService.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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()));
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/glous/kleebot/services/ServiceRegistry.java
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ else if (type.equals("monthly"))
if (serialNum>ranking.size()+1||serialNum<1){
return false;
}
HashMap<String,String> artwork=ranking.get(serialNum+1);
HashMap<String,String> artwork=ranking.get(serialNum-1);
sendRankMessage(event, artwork);
} else{
String illustid=method;
Expand Down
71 changes: 71 additions & 0 deletions src/main/java/glous/kleebot/services/impl/SyncService.java
Original file line number Diff line number Diff line change
@@ -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<Integer, HashMap<String,String>> daily=api.getDailyRanking(false);
HashMap<Integer,HashMap<String,String>> weekly=api.getWeeklyRanking(false);
HashMap<Integer,HashMap<String,String>> monthly=api.getMonthlyRanking(false);
StringBuilder builder=new StringBuilder();
builder.append("Pixiv Synchronization Info:\n");
for (HashMap<String, String> 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<String, String> 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<String, String> 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;
}
}
Loading

1 comment on commit 0196e26

@vercel
Copy link

@vercel vercel bot commented on 0196e26 Apr 23, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

kleebot – ./

kleebot-git-master-youfantan.vercel.app
kleebot-youfantan.vercel.app

Please sign in to comment.