mirror of
https://github.com/LamGC/ContentGrabbingJi.git
synced 2025-07-03 22:07:26 +00:00
Compare commits
36 Commits
v2.5.2-202
...
v2.5.2-202
Author | SHA1 | Date | |
---|---|---|---|
968a616595
|
|||
6443ba68ab
|
|||
cbe0a38f59
|
|||
eadfacb7d0 | |||
572189d906 | |||
811694587d | |||
419f2de055 | |||
368c78e171 | |||
bccf47db6e | |||
cf351074cc | |||
c4ce18d37a | |||
26fd18917d | |||
acbd990181 | |||
6db9cda08a | |||
1c742bfb6f | |||
2f30fe1696 | |||
32db952e63 | |||
bd6b825704 | |||
3943963505 | |||
08822f68eb | |||
2f647ee9fa | |||
44a7f49510 | |||
85088e1b2c | |||
8dfb858b9f | |||
0e76cebc31 | |||
c64320ad78 | |||
91e065f657 | |||
91f8b0070f | |||
ad54dbfbf3 | |||
ebb3dea99e | |||
abcd26f21b | |||
d9b08f8ad9 | |||
5e030c12b2 | |||
62eabce8f6 | |||
64bca3c8f7 | |||
3b3f97e638 |
13
pom.xml
13
pom.xml
@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
<groupId>net.lamgc</groupId>
|
<groupId>net.lamgc</groupId>
|
||||||
<artifactId>ContentGrabbingJi</artifactId>
|
<artifactId>ContentGrabbingJi</artifactId>
|
||||||
<version>2.5.2-20200611.1-SNAPSHOT</version>
|
<version>2.5.2-20200630.1-SNAPSHOT</version>
|
||||||
|
|
||||||
<licenses>
|
<licenses>
|
||||||
<license>
|
<license>
|
||||||
@ -162,11 +162,6 @@
|
|||||||
<artifactId>ktor-server-core</artifactId>
|
<artifactId>ktor-server-core</artifactId>
|
||||||
<version>${ktor.version}</version>
|
<version>${ktor.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>net.lamgc</groupId>
|
|
||||||
<artifactId>PixivLoginProxyServer</artifactId>
|
|
||||||
<version>1.1.1</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.squareup</groupId>
|
<groupId>com.squareup</groupId>
|
||||||
<artifactId>gifencoder</artifactId>
|
<artifactId>gifencoder</artifactId>
|
||||||
@ -177,6 +172,12 @@
|
|||||||
<artifactId>jline</artifactId>
|
<artifactId>jline</artifactId>
|
||||||
<version>3.15.0</version>
|
<version>3.15.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.inject</groupId>
|
||||||
|
<artifactId>guice</artifactId>
|
||||||
|
<version>4.2.3</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
@ -1,7 +1,5 @@
|
|||||||
package net.lamgc.cgj;
|
package net.lamgc.cgj;
|
||||||
|
|
||||||
import com.github.monkeywie.proxyee.proxy.ProxyConfig;
|
|
||||||
import com.github.monkeywie.proxyee.proxy.ProxyType;
|
|
||||||
import com.google.common.base.Strings;
|
import com.google.common.base.Strings;
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.JsonArray;
|
import com.google.gson.JsonArray;
|
||||||
@ -13,12 +11,12 @@ import net.lamgc.cgj.bot.framework.cli.ConsoleMain;
|
|||||||
import net.lamgc.cgj.bot.framework.coolq.CQConfig;
|
import net.lamgc.cgj.bot.framework.coolq.CQConfig;
|
||||||
import net.lamgc.cgj.bot.framework.mirai.MiraiMain;
|
import net.lamgc.cgj.bot.framework.mirai.MiraiMain;
|
||||||
import net.lamgc.cgj.pixiv.PixivDownload;
|
import net.lamgc.cgj.pixiv.PixivDownload;
|
||||||
import net.lamgc.cgj.pixiv.PixivSearchBuilder;
|
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
|
||||||
import net.lamgc.cgj.pixiv.PixivURL;
|
import net.lamgc.cgj.pixiv.PixivURL;
|
||||||
import net.lamgc.plps.PixivLoginProxyServer;
|
|
||||||
import net.lamgc.utils.base.runner.Argument;
|
import net.lamgc.utils.base.runner.Argument;
|
||||||
import net.lamgc.utils.base.runner.ArgumentsRunner;
|
import net.lamgc.utils.base.runner.ArgumentsRunner;
|
||||||
import net.lamgc.utils.base.runner.Command;
|
import net.lamgc.utils.base.runner.Command;
|
||||||
|
import net.lamgc.utils.encrypt.MessageDigestUtils;
|
||||||
import org.apache.http.HttpHost;
|
import org.apache.http.HttpHost;
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
import org.apache.http.client.CookieStore;
|
import org.apache.http.client.CookieStore;
|
||||||
@ -52,6 +50,14 @@ public class Main {
|
|||||||
private static HttpHost proxy;
|
private static HttpHost proxy;
|
||||||
|
|
||||||
public static void main(String[] args) throws IOException, ClassNotFoundException {
|
public static void main(String[] args) throws IOException, ClassNotFoundException {
|
||||||
|
if(args.length != 0 && args[0].equalsIgnoreCase("buildpassword")) {
|
||||||
|
ArgumentsRunner.run(Main.class, args);
|
||||||
|
} else {
|
||||||
|
standardStart(args);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void standardStart(String[] args) throws IOException, ClassNotFoundException {
|
||||||
log.info("ContentGrabbingJi 正在启动...");
|
log.info("ContentGrabbingJi 正在启动...");
|
||||||
log.debug("Args: {}, LogsPath: {}", Arrays.toString(args), System.getProperty("cgj.logsPath"));
|
log.debug("Args: {}, LogsPath: {}", Arrays.toString(args), System.getProperty("cgj.logsPath"));
|
||||||
log.debug("运行目录: {}", System.getProperty("user.dir"));
|
log.debug("运行目录: {}", System.getProperty("user.dir"));
|
||||||
@ -62,17 +68,10 @@ public class Main {
|
|||||||
proxy = BotGlobal.getGlobal().getProxy();
|
proxy = BotGlobal.getGlobal().getProxy();
|
||||||
File cookieStoreFile = new File(BotGlobal.getGlobal().getDataStoreDir(), "cookies.store");
|
File cookieStoreFile = new File(BotGlobal.getGlobal().getDataStoreDir(), "cookies.store");
|
||||||
if(!cookieStoreFile.exists()) {
|
if(!cookieStoreFile.exists()) {
|
||||||
log.warn("未找到cookies.store文件, 是否启动PixivLoginProxyServer? (yes/no)");
|
log.warn("未找到cookies.store文件, 请检查数据存放目录下是否存在'cookies.store'文件!");
|
||||||
try(Scanner scanner = new Scanner(System.in)) {
|
|
||||||
if(scanner.nextLine().trim().equalsIgnoreCase("yes")) {
|
|
||||||
startPixivLoginProxyServer();
|
|
||||||
} else {
|
|
||||||
System.exit(1);
|
System.exit(1);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cookieStoreFile));
|
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cookieStoreFile));
|
||||||
cookieStore = (CookieStore) ois.readObject();
|
cookieStore = (CookieStore) ois.readObject();
|
||||||
BotGlobal.getGlobal().setCookieStore(cookieStore);
|
BotGlobal.getGlobal().setCookieStore(cookieStore);
|
||||||
@ -85,6 +84,13 @@ public class Main {
|
|||||||
System.exit(0);
|
System.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Command
|
||||||
|
public static void buildPassword(@Argument(name = "password") String password) {
|
||||||
|
System.out.println("Password: " +
|
||||||
|
Base64.getEncoder().encodeToString(MessageDigestUtils.encrypt(password.getBytes(),
|
||||||
|
MessageDigestUtils.Algorithm.MD5)));
|
||||||
|
}
|
||||||
|
|
||||||
@Command
|
@Command
|
||||||
public static void botMode(@Argument(name = "args", force = false) String argsStr) {
|
public static void botMode(@Argument(name = "args", force = false) String argsStr) {
|
||||||
MiraiMain main = new MiraiMain();
|
MiraiMain main = new MiraiMain();
|
||||||
@ -254,24 +260,24 @@ public class Main {
|
|||||||
@Argument(name = "excludeKeywords", force = false) String excludeKeywords,
|
@Argument(name = "excludeKeywords", force = false) String excludeKeywords,
|
||||||
@Argument(name = "contentOption", force = false) String contentOption
|
@Argument(name = "contentOption", force = false) String contentOption
|
||||||
) throws IOException {
|
) throws IOException {
|
||||||
PixivSearchBuilder searchBuilder = new PixivSearchBuilder(Strings.isNullOrEmpty(content) ? "" : content);
|
PixivSearchLinkBuilder searchBuilder = new PixivSearchLinkBuilder(Strings.isNullOrEmpty(content) ? "" : content);
|
||||||
if (type != null) {
|
if (type != null) {
|
||||||
try {
|
try {
|
||||||
searchBuilder.setSearchType(PixivSearchBuilder.SearchType.valueOf(type.toUpperCase()));
|
searchBuilder.setSearchType(PixivSearchLinkBuilder.SearchType.valueOf(type.toUpperCase()));
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("不支持的SearchType: {}", type);
|
log.warn("不支持的SearchType: {}", type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(area != null) {
|
if(area != null) {
|
||||||
try {
|
try {
|
||||||
searchBuilder.setSearchArea(PixivSearchBuilder.SearchArea.valueOf(area));
|
searchBuilder.setSearchArea(PixivSearchLinkBuilder.SearchArea.valueOf(area));
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("不支持的SearchArea: {}", area);
|
log.warn("不支持的SearchArea: {}", area);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(contentOption != null) {
|
if(contentOption != null) {
|
||||||
try {
|
try {
|
||||||
searchBuilder.setSearchContentOption(PixivSearchBuilder.SearchContentOption.valueOf(contentOption));
|
searchBuilder.setSearchContentOption(PixivSearchLinkBuilder.SearchContentOption.valueOf(contentOption));
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("不支持的SearchContentOption: {}", contentOption);
|
log.warn("不支持的SearchContentOption: {}", contentOption);
|
||||||
}
|
}
|
||||||
@ -310,7 +316,7 @@ public class Main {
|
|||||||
|
|
||||||
JsonObject resultBody = jsonObject.getAsJsonObject("body");
|
JsonObject resultBody = jsonObject.getAsJsonObject("body");
|
||||||
|
|
||||||
for(PixivSearchBuilder.SearchArea searchArea : PixivSearchBuilder.SearchArea.values()) {
|
for(PixivSearchLinkBuilder.SearchArea searchArea : PixivSearchLinkBuilder.SearchArea.values()) {
|
||||||
if(!resultBody.has(searchArea.jsonKey) || resultBody.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data").size() == 0) {
|
if(!resultBody.has(searchArea.jsonKey) || resultBody.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data").size() == 0) {
|
||||||
//log.info("返回数据不包含 {}", searchArea.jsonKey);
|
//log.info("返回数据不包含 {}", searchArea.jsonKey);
|
||||||
continue;
|
continue;
|
||||||
@ -349,57 +355,6 @@ public class Main {
|
|||||||
log.info("这里啥都没有哟w");
|
log.info("这里啥都没有哟w");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void saveCookieStoreToFile() throws IOException {
|
|
||||||
log.info("正在保存CookieStore...");
|
|
||||||
File outputFile = new File(BotGlobal.getGlobal().getDataStoreDir(), "cookies.store");
|
|
||||||
if(!outputFile.exists() && !outputFile.createNewFile()){
|
|
||||||
log.error("保存CookieStore失败.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(outputFile));
|
|
||||||
stream.writeObject(cookieStore);
|
|
||||||
stream.flush();
|
|
||||||
stream.close();
|
|
||||||
log.info("CookieStore保存成功.");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void startPixivLoginProxyServer(){
|
|
||||||
ProxyConfig proxyConfig = null;
|
|
||||||
if(proxy != null) {
|
|
||||||
proxyConfig = new ProxyConfig(ProxyType.HTTP, proxy.getHostName(), proxy.getPort());
|
|
||||||
}
|
|
||||||
PixivLoginProxyServer proxyServer = new PixivLoginProxyServer(proxyConfig);
|
|
||||||
Thread proxyServerStartThread = new Thread(() -> {
|
|
||||||
log.info("启动代理服务器...");
|
|
||||||
proxyServer.start(1006);
|
|
||||||
log.info("代理服务器已关闭.");
|
|
||||||
});
|
|
||||||
proxyServerStartThread.setName("LoginProxyServerThread");
|
|
||||||
proxyServerStartThread.start();
|
|
||||||
//System.console().readLine();
|
|
||||||
|
|
||||||
log.info("登录完成后, 使用\"done\"命令结束登录过程.");
|
|
||||||
try(Scanner scanner = new Scanner(System.in)) {
|
|
||||||
while(true) {
|
|
||||||
if (scanner.nextLine().equalsIgnoreCase("done")) {
|
|
||||||
log.info("关闭PLPS服务器...");
|
|
||||||
proxyServer.close();
|
|
||||||
cookieStore = proxyServer.getCookieStore();
|
|
||||||
try {
|
|
||||||
log.info("正在保存CookieStore...");
|
|
||||||
saveCookieStoreToFile();
|
|
||||||
log.info("CookieStore保存完成.");
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.error("CookieStore保存时发生异常, 本次CookieStore仅可在本次运行使用.", e);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
} else {
|
|
||||||
log.warn("要结束登录过程, 请使用\"done\"命令.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static File getStoreDir() {
|
private static File getStoreDir() {
|
||||||
if(!storeDir.exists() && !storeDir.mkdirs()) {
|
if(!storeDir.exists() && !storeDir.mkdirs()) {
|
||||||
log.error("创建文件夹失败!");
|
log.error("创建文件夹失败!");
|
||||||
|
@ -270,7 +270,7 @@ public class BotAdminCommandProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
AutoSender sender = new RandomRankingArtworksSender(
|
AutoSender sender = new RandomRankingArtworksSender(
|
||||||
MessageSenderBuilder.getMessageSender(MessageSource.Group, id),
|
MessageSenderBuilder.getMessageSender(MessageSource.GROUP, id),
|
||||||
id,
|
id,
|
||||||
rankingStart,
|
rankingStart,
|
||||||
rankingEnd,
|
rankingEnd,
|
||||||
|
@ -8,11 +8,12 @@ import net.lamgc.cgj.bot.boot.BotGlobal;
|
|||||||
import net.lamgc.cgj.bot.cache.CacheStore;
|
import net.lamgc.cgj.bot.cache.CacheStore;
|
||||||
import net.lamgc.cgj.bot.cache.CacheStoreCentral;
|
import net.lamgc.cgj.bot.cache.CacheStoreCentral;
|
||||||
import net.lamgc.cgj.bot.cache.JsonRedisCacheStore;
|
import net.lamgc.cgj.bot.cache.JsonRedisCacheStore;
|
||||||
import net.lamgc.cgj.bot.event.BufferMessageEvent;
|
import net.lamgc.cgj.bot.event.BufferedMessageSender;
|
||||||
import net.lamgc.cgj.bot.sort.PreLoadDataComparator;
|
import net.lamgc.cgj.bot.sort.PreLoadDataAttribute;
|
||||||
|
import net.lamgc.cgj.bot.sort.PreLoadDataAttributeComparator;
|
||||||
import net.lamgc.cgj.pixiv.PixivDownload;
|
import net.lamgc.cgj.pixiv.PixivDownload;
|
||||||
import net.lamgc.cgj.pixiv.PixivDownload.PageQuality;
|
import net.lamgc.cgj.pixiv.PixivDownload.PageQuality;
|
||||||
import net.lamgc.cgj.pixiv.PixivSearchBuilder;
|
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
|
||||||
import net.lamgc.cgj.pixiv.PixivURL;
|
import net.lamgc.cgj.pixiv.PixivURL;
|
||||||
import net.lamgc.utils.base.runner.Argument;
|
import net.lamgc.utils.base.runner.Argument;
|
||||||
import net.lamgc.utils.base.runner.Command;
|
import net.lamgc.utils.base.runner.Command;
|
||||||
@ -91,7 +92,8 @@ public class BotCommandProcess {
|
|||||||
*/
|
*/
|
||||||
@Command(commandName = "info")
|
@Command(commandName = "info")
|
||||||
public static String artworkInfo(@Argument(name = "$fromGroup") long fromGroup,
|
public static String artworkInfo(@Argument(name = "$fromGroup") long fromGroup,
|
||||||
@Argument(name = "id") int illustId) {
|
@Argument(name = "id") int illustId)
|
||||||
|
throws InterruptedException {
|
||||||
if(illustId <= 0) {
|
if(illustId <= 0) {
|
||||||
return "这个作品Id是错误的!";
|
return "这个作品Id是错误的!";
|
||||||
}
|
}
|
||||||
@ -108,11 +110,11 @@ public class BotCommandProcess {
|
|||||||
"\n作品标题:" + illustPreLoadData.get("illustTitle").getAsString() +
|
"\n作品标题:" + illustPreLoadData.get("illustTitle").getAsString() +
|
||||||
"\n作者(作者Id):" + illustPreLoadData.get("userName").getAsString() +
|
"\n作者(作者Id):" + illustPreLoadData.get("userName").getAsString() +
|
||||||
"(" + illustPreLoadData.get("userId").getAsInt() + ")" +
|
"(" + illustPreLoadData.get("userId").getAsInt() + ")" +
|
||||||
"\n点赞数:" + illustPreLoadData.get(PreLoadDataComparator.Attribute.LIKE.attrName).getAsInt() +
|
"\n点赞数:" + illustPreLoadData.get(PreLoadDataAttribute.LIKE.attrName).getAsInt() +
|
||||||
"\n收藏数:" + illustPreLoadData.get(PreLoadDataComparator.Attribute.BOOKMARK.attrName).getAsInt() +
|
"\n收藏数:" + illustPreLoadData.get(PreLoadDataAttribute.BOOKMARK.attrName).getAsInt() +
|
||||||
"\n围观数:" + illustPreLoadData.get(PreLoadDataComparator.Attribute.VIEW.attrName).getAsInt() +
|
"\n围观数:" + illustPreLoadData.get(PreLoadDataAttribute.VIEW.attrName).getAsInt() +
|
||||||
"\n评论数:" + illustPreLoadData.get(PreLoadDataComparator.Attribute.COMMENT.attrName).getAsInt() +
|
"\n评论数:" + illustPreLoadData.get(PreLoadDataAttribute.COMMENT.attrName).getAsInt() +
|
||||||
"\n页数:" + illustPreLoadData.get(PreLoadDataComparator.Attribute.PAGE.attrName).getAsInt() + "页" +
|
"\n页数:" + illustPreLoadData.get(PreLoadDataAttribute.PAGE.attrName).getAsInt() + "页" +
|
||||||
"\n作品链接:" + artworksLink(fromGroup, illustId) + "\n" +
|
"\n作品链接:" + artworksLink(fromGroup, illustId) + "\n" +
|
||||||
"---------------- 作品图片 ----------------\n" +
|
"---------------- 作品图片 ----------------\n" +
|
||||||
CacheStoreCentral.getCentral().getImageById(fromGroup, illustId, PageQuality.REGULAR, 1) + "\n" +
|
CacheStoreCentral.getCentral().getImageById(fromGroup, illustId, PageQuality.REGULAR, 1) + "\n" +
|
||||||
@ -141,8 +143,8 @@ public class BotCommandProcess {
|
|||||||
@Argument(force = false, name = "date") Date queryTime,
|
@Argument(force = false, name = "date") Date queryTime,
|
||||||
@Argument(force = false, name = "force") boolean force,
|
@Argument(force = false, name = "force") boolean force,
|
||||||
@Argument(force = false, name = "mode", defaultValue = "DAILY") String contentMode,
|
@Argument(force = false, name = "mode", defaultValue = "DAILY") String contentMode,
|
||||||
@Argument(force = false, name = "type", defaultValue = "ILLUST") String contentType
|
@Argument(force = false, name = "type", defaultValue = "ALL") String contentType
|
||||||
) {
|
) throws InterruptedException {
|
||||||
Date queryDate = queryTime;
|
Date queryDate = queryTime;
|
||||||
if (queryDate == null) {
|
if (queryDate == null) {
|
||||||
queryDate = new Date();
|
queryDate = new Date();
|
||||||
@ -280,12 +282,12 @@ public class BotCommandProcess {
|
|||||||
return "参数无效, 请查看帮助信息";
|
return "参数无效, 请查看帮助信息";
|
||||||
}
|
}
|
||||||
|
|
||||||
BufferMessageEvent event = new BufferMessageEvent();
|
BufferedMessageSender bufferedSender = new BufferedMessageSender();
|
||||||
RandomRankingArtworksSender artworksSender =
|
RandomRankingArtworksSender artworksSender =
|
||||||
new RandomRankingArtworksSender(event, fromGroup, 1, 200, mode, type,
|
new RandomRankingArtworksSender(bufferedSender, fromGroup, 1, 200, mode, type,
|
||||||
PageQuality.ORIGINAL);
|
PageQuality.ORIGINAL);
|
||||||
artworksSender.send();
|
artworksSender.send();
|
||||||
return event.getBufferMessage();
|
return bufferedSender.getBufferContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -310,11 +312,11 @@ public class BotCommandProcess {
|
|||||||
@Argument(name = "in", force = false) String includeKeywords,
|
@Argument(name = "in", force = false) String includeKeywords,
|
||||||
@Argument(name = "ex", force = false) String excludeKeywords,
|
@Argument(name = "ex", force = false) String excludeKeywords,
|
||||||
@Argument(name = "option", force = false) String contentOption,
|
@Argument(name = "option", force = false) String contentOption,
|
||||||
@Argument(name = "page", force = false, defaultValue = "1") int pagesIndex
|
@Argument(name = "p", force = false, defaultValue = "1") int pagesIndex
|
||||||
) throws IOException {
|
) throws IOException, InterruptedException {
|
||||||
log.info("正在执行搜索...");
|
log.debug("正在执行搜索...");
|
||||||
JsonObject resultBody = CacheStoreCentral.getCentral()
|
JsonObject resultBody = CacheStoreCentral.getCentral()
|
||||||
.getSearchBody(content, type, area, includeKeywords, excludeKeywords, contentOption);
|
.getSearchBody(content, type, area, includeKeywords, excludeKeywords, contentOption, pagesIndex);
|
||||||
|
|
||||||
StringBuilder result = new StringBuilder("内容 " + content + " 的搜索结果:\n");
|
StringBuilder result = new StringBuilder("内容 " + content + " 的搜索结果:\n");
|
||||||
log.debug("正在处理信息...");
|
log.debug("正在处理信息...");
|
||||||
@ -326,7 +328,7 @@ public class BotCommandProcess {
|
|||||||
log.warn("参数转换异常!将使用默认值(" + limit + ")", e);
|
log.warn("参数转换异常!将使用默认值(" + limit + ")", e);
|
||||||
}
|
}
|
||||||
int totalCount = 0;
|
int totalCount = 0;
|
||||||
for (PixivSearchBuilder.SearchArea searchArea : PixivSearchBuilder.SearchArea.values()) {
|
for (PixivSearchLinkBuilder.SearchArea searchArea : PixivSearchLinkBuilder.SearchArea.values()) {
|
||||||
if (!resultBody.has(searchArea.jsonKey) ||
|
if (!resultBody.has(searchArea.jsonKey) ||
|
||||||
resultBody.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data").size() == 0) {
|
resultBody.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data").size() == 0) {
|
||||||
log.debug("返回数据不包含 {}", searchArea.jsonKey);
|
log.debug("返回数据不包含 {}", searchArea.jsonKey);
|
||||||
@ -336,9 +338,9 @@ public class BotCommandProcess {
|
|||||||
.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data");
|
.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data");
|
||||||
ArrayList<JsonElement> illustsList = new ArrayList<>();
|
ArrayList<JsonElement> illustsList = new ArrayList<>();
|
||||||
illustsArray.forEach(illustsList::add);
|
illustsArray.forEach(illustsList::add);
|
||||||
illustsList.sort(new PreLoadDataComparator(PreLoadDataComparator.Attribute.LIKE));
|
illustsList.sort(new PreLoadDataAttributeComparator(PreLoadDataAttribute.BOOKMARK));
|
||||||
|
|
||||||
log.info("已找到与 {} 相关插图信息({}):", content, searchArea.name().toLowerCase());
|
log.debug("已找到与 {} 相关插图信息({}):", content, searchArea.name().toLowerCase());
|
||||||
int count = 1;
|
int count = 1;
|
||||||
for (JsonElement jsonElement : illustsList) {
|
for (JsonElement jsonElement : illustsList) {
|
||||||
if (count > limit) {
|
if (count > limit) {
|
||||||
@ -366,8 +368,17 @@ public class BotCommandProcess {
|
|||||||
PixivURL.getPixivRefererLink(illustId)
|
PixivURL.getPixivRefererLink(illustId)
|
||||||
);
|
);
|
||||||
|
|
||||||
String imageMsg = CacheStoreCentral.getCentral()
|
String imageMsg;
|
||||||
|
try {
|
||||||
|
imageMsg = CacheStoreCentral.getCentral()
|
||||||
.getImageById(fromGroup, illustId, PixivDownload.PageQuality.REGULAR, 1);
|
.getImageById(fromGroup, illustId, PixivDownload.PageQuality.REGULAR, 1);
|
||||||
|
} catch (NoSuchElementException e) {
|
||||||
|
if(e.getMessage().startsWith("No work found: ")) {
|
||||||
|
log.warn("作品 {} 不存在, 跳过该作品...", illustId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
if (isNoSafe(illustId, SettingProperties.getProperties(fromGroup), false)) {
|
if (isNoSafe(illustId, SettingProperties.getProperties(fromGroup), false)) {
|
||||||
log.warn("作品Id {} 为R-18作品, 跳过.", illustId);
|
log.warn("作品Id {} 为R-18作品, 跳过.", illustId);
|
||||||
continue;
|
continue;
|
||||||
@ -384,13 +395,13 @@ public class BotCommandProcess {
|
|||||||
.append("\n\t作品标题: ").append(illustObj.get("illustTitle").getAsString())
|
.append("\n\t作品标题: ").append(illustObj.get("illustTitle").getAsString())
|
||||||
.append("\n\t作品页数: ").append(illustObj.get("pageCount").getAsInt()).append("页")
|
.append("\n\t作品页数: ").append(illustObj.get("pageCount").getAsInt()).append("页")
|
||||||
.append("\n\t点赞数:")
|
.append("\n\t点赞数:")
|
||||||
.append(illustPreLoadData.get(PreLoadDataComparator.Attribute.LIKE.attrName).getAsInt())
|
.append(illustPreLoadData.get(PreLoadDataAttribute.LIKE.attrName).getAsInt())
|
||||||
.append("\n\t收藏数:")
|
.append("\n\t收藏数:")
|
||||||
.append(illustPreLoadData.get(PreLoadDataComparator.Attribute.BOOKMARK.attrName).getAsInt())
|
.append(illustPreLoadData.get(PreLoadDataAttribute.BOOKMARK.attrName).getAsInt())
|
||||||
.append("\n\t围观数:")
|
.append("\n\t围观数:")
|
||||||
.append(illustPreLoadData.get(PreLoadDataComparator.Attribute.VIEW.attrName).getAsInt())
|
.append(illustPreLoadData.get(PreLoadDataAttribute.VIEW.attrName).getAsInt())
|
||||||
.append("\n\t评论数:")
|
.append("\n\t评论数:")
|
||||||
.append(illustPreLoadData.get(PreLoadDataComparator.Attribute.COMMENT.attrName).getAsInt())
|
.append(illustPreLoadData.get(PreLoadDataAttribute.COMMENT.attrName).getAsInt())
|
||||||
.append("\n").append(imageMsg).append("\n");
|
.append("\n").append(imageMsg).append("\n");
|
||||||
count++;
|
count++;
|
||||||
totalCount++;
|
totalCount++;
|
||||||
@ -484,8 +495,8 @@ public class BotCommandProcess {
|
|||||||
@Argument(name = "$fromGroup") long fromGroup,
|
@Argument(name = "$fromGroup") long fromGroup,
|
||||||
@Argument(name = "id") int illustId,
|
@Argument(name = "id") int illustId,
|
||||||
@Argument(name = "quality", force = false) PixivDownload.PageQuality quality,
|
@Argument(name = "quality", force = false) PixivDownload.PageQuality quality,
|
||||||
@Argument(name = "page", force = false, defaultValue = "1") int pageIndex
|
@Argument(name = "p", force = false, defaultValue = "1") int pageIndex
|
||||||
) {
|
) throws InterruptedException {
|
||||||
return CacheStoreCentral.getCentral().getImageById(fromGroup, illustId, quality, pageIndex);
|
return CacheStoreCentral.getCentral().getImageById(fromGroup, illustId, quality, pageIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -13,7 +13,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
|||||||
*/
|
*/
|
||||||
public class RandomIntervalSendTimer extends TimerTask {
|
public class RandomIntervalSendTimer extends TimerTask {
|
||||||
|
|
||||||
private final static Timer timer = new Timer("Thread-RIST", true);
|
private final static Timer timer = new Timer("Thread-RandomIntervalSendTimer", true);
|
||||||
private final static Logger log = LoggerFactory.getLogger(RandomIntervalSendTimer.class);
|
private final static Logger log = LoggerFactory.getLogger(RandomIntervalSendTimer.class);
|
||||||
private final static Map<Long, RandomIntervalSendTimer> timerMap = new HashMap<>();
|
private final static Map<Long, RandomIntervalSendTimer> timerMap = new HashMap<>();
|
||||||
|
|
||||||
@ -77,7 +77,13 @@ public class RandomIntervalSendTimer extends TimerTask {
|
|||||||
* @param startNow 现在开始
|
* @param startNow 现在开始
|
||||||
* @param loop 是否循环
|
* @param loop 是否循环
|
||||||
*/
|
*/
|
||||||
private RandomIntervalSendTimer(long timerId, AutoSender sender, long time, int floatTime, boolean startNow, boolean loop) {
|
private RandomIntervalSendTimer(
|
||||||
|
long timerId,
|
||||||
|
AutoSender sender,
|
||||||
|
long time,
|
||||||
|
int floatTime,
|
||||||
|
boolean startNow,
|
||||||
|
boolean loop) {
|
||||||
this.timerId = timerId;
|
this.timerId = timerId;
|
||||||
this.sender = sender;
|
this.sender = sender;
|
||||||
this.time = time;
|
this.time = time;
|
||||||
@ -119,11 +125,15 @@ public class RandomIntervalSendTimer extends TimerTask {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
|
log.info("定时器 {} 开始执行...(Sender: {}@{})", this.hashId, sender.getClass().getSimpleName(), sender.hashCode());
|
||||||
try {
|
try {
|
||||||
sender.send();
|
sender.send();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("定时器 {} 执行时发生异常:\n{}", Integer.toHexString(this.hashCode()), Throwables.getStackTraceAsString(e));
|
log.error("定时器 {} 执行时发生异常:\n{}",
|
||||||
|
Integer.toHexString(this.hashCode()),
|
||||||
|
Throwables.getStackTraceAsString(e));
|
||||||
}
|
}
|
||||||
|
log.info("定时器 {} 执行结束.", this.hashId);
|
||||||
if (this.loop.get()) {
|
if (this.loop.get()) {
|
||||||
start();
|
start();
|
||||||
}
|
}
|
||||||
|
@ -27,7 +27,7 @@ public final class BotGlobal {
|
|||||||
|
|
||||||
public static BotGlobal getGlobal() {
|
public static BotGlobal getGlobal() {
|
||||||
if(instance == null) {
|
if(instance == null) {
|
||||||
throw new IllegalStateException("");
|
throw new IllegalStateException("BotGlobal has not been initialized");
|
||||||
}
|
}
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,7 @@ public class AutoCleanTimer extends TimerTask {
|
|||||||
private final static Logger log = LoggerFactory.getLogger(AutoCleanTimer.class);
|
private final static Logger log = LoggerFactory.getLogger(AutoCleanTimer.class);
|
||||||
|
|
||||||
static {
|
static {
|
||||||
cleanTimer.schedule(new AutoCleanTimer(), 100L);
|
cleanTimer.schedule(new AutoCleanTimer(), 100L, 100L);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -8,9 +8,12 @@ import net.lamgc.cgj.bot.BotCode;
|
|||||||
import net.lamgc.cgj.bot.BotCommandProcess;
|
import net.lamgc.cgj.bot.BotCommandProcess;
|
||||||
import net.lamgc.cgj.bot.SettingProperties;
|
import net.lamgc.cgj.bot.SettingProperties;
|
||||||
import net.lamgc.cgj.bot.boot.BotGlobal;
|
import net.lamgc.cgj.bot.boot.BotGlobal;
|
||||||
|
import net.lamgc.cgj.exception.HttpRequestException;
|
||||||
import net.lamgc.cgj.pixiv.PixivDownload;
|
import net.lamgc.cgj.pixiv.PixivDownload;
|
||||||
import net.lamgc.cgj.pixiv.PixivSearchBuilder;
|
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
|
||||||
import net.lamgc.cgj.pixiv.PixivURL;
|
import net.lamgc.cgj.pixiv.PixivURL;
|
||||||
|
import net.lamgc.cgj.util.Locker;
|
||||||
|
import net.lamgc.cgj.util.LockerMap;
|
||||||
import net.lamgc.cgj.util.URLs;
|
import net.lamgc.cgj.util.URLs;
|
||||||
import net.lamgc.utils.encrypt.MessageDigestUtils;
|
import net.lamgc.utils.encrypt.MessageDigestUtils;
|
||||||
import net.lz1998.cq.utils.CQCode;
|
import net.lz1998.cq.utils.CQCode;
|
||||||
@ -50,6 +53,8 @@ public final class CacheStoreCentral {
|
|||||||
central = new CacheStoreCentral();
|
central = new CacheStoreCentral();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private final LockerMap<String> lockerMap = new LockerMap<>();
|
||||||
|
|
||||||
private CacheStoreCentral() {}
|
private CacheStoreCentral() {}
|
||||||
|
|
||||||
private final Hashtable<String, File> imageCache = new Hashtable<>();
|
private final Hashtable<String, File> imageCache = new Hashtable<>();
|
||||||
@ -58,6 +63,13 @@ public final class CacheStoreCentral {
|
|||||||
new JsonRedisCacheStore(BotGlobal.getGlobal().getRedisServer(),
|
new JsonRedisCacheStore(BotGlobal.getGlobal().getRedisServer(),
|
||||||
"imageChecksum", BotGlobal.getGlobal().getGson());
|
"imageChecksum", BotGlobal.getGlobal().getGson());
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 注意:
|
||||||
|
* 在启用了远端缓存的情况下, 不允许滥用本地缓存
|
||||||
|
* 只有在处理命令中需要短时间大量存取的缓存项才能进行本地缓存(例如PreLoadData需要在排序中大量获取);
|
||||||
|
* 如果没有短时间大量存取的需要, 切勿使用本地缓存
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 作品信息缓存 - 不过期
|
* 作品信息缓存 - 不过期
|
||||||
*/
|
*/
|
||||||
@ -66,13 +78,14 @@ public final class CacheStoreCentral {
|
|||||||
"illustInfo", BotGlobal.getGlobal().getGson());
|
"illustInfo", BotGlobal.getGlobal().getGson());
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 作品信息预加载数据 - 有效期 2 小时, 本地缓存有效期1 ± 0.25
|
* 作品信息预加载数据 - 有效期 2 小时, 本地缓存有效期 0.5 ± 0.25 小时
|
||||||
*/
|
*/
|
||||||
private final CacheStore<JsonElement> illustPreLoadDataCache =
|
private final CacheStore<JsonElement> illustPreLoadDataCache =
|
||||||
CacheStoreUtils.hashLocalHotDataStore(
|
CacheStoreUtils.hashLocalHotDataStore(
|
||||||
new JsonRedisCacheStore(BotGlobal.getGlobal().getRedisServer(),
|
new JsonRedisCacheStore(BotGlobal.getGlobal().getRedisServer(),
|
||||||
"illustPreLoadData", BotGlobal.getGlobal().getGson()),
|
"illustPreLoadData", BotGlobal.getGlobal().getGson()),
|
||||||
3600000, 900000);
|
// 600000, 120000);
|
||||||
|
60000, 1);
|
||||||
/**
|
/**
|
||||||
* 搜索内容缓存, 有效期 2 小时
|
* 搜索内容缓存, 有效期 2 小时
|
||||||
*/
|
*/
|
||||||
@ -113,7 +126,7 @@ public final class CacheStoreCentral {
|
|||||||
* @param pageIndex 指定页面索引, 从1开始
|
* @param pageIndex 指定页面索引, 从1开始
|
||||||
* @return 如果成功, 返回BotCode, 否则返回错误信息.
|
* @return 如果成功, 返回BotCode, 否则返回错误信息.
|
||||||
*/
|
*/
|
||||||
public String getImageById(long fromGroup, int illustId, PixivDownload.PageQuality quality, int pageIndex) {
|
public String getImageById(long fromGroup, int illustId, PixivDownload.PageQuality quality, int pageIndex) throws InterruptedException {
|
||||||
log.debug("IllustId: {}, Quality: {}, PageIndex: {}", illustId, quality.name(), pageIndex);
|
log.debug("IllustId: {}, Quality: {}, PageIndex: {}", illustId, quality.name(), pageIndex);
|
||||||
if(pageIndex <= 0) {
|
if(pageIndex <= 0) {
|
||||||
log.warn("指定的页数不能小于或等于0: {}", pageIndex);
|
log.warn("指定的页数不能小于或等于0: {}", pageIndex);
|
||||||
@ -188,7 +201,7 @@ public final class CacheStoreCentral {
|
|||||||
}
|
}
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
log.warn("图片缓存被中断", e);
|
log.warn("图片缓存被中断", e);
|
||||||
return "(错误:图片获取超时)";
|
throw e;
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
log.error("图片 {} 获取失败:\n{}", illustId + "p" + pageIndex, Throwables.getStackTraceAsString(e));
|
log.error("图片 {} 获取失败:\n{}", illustId + "p" + pageIndex, Throwables.getStackTraceAsString(e));
|
||||||
return "(错误: 图片获取出错)";
|
return "(错误: 图片获取出错)";
|
||||||
@ -227,15 +240,21 @@ public final class CacheStoreCentral {
|
|||||||
*/
|
*/
|
||||||
public JsonObject getIllustInfo(int illustId, boolean flushCache)
|
public JsonObject getIllustInfo(int illustId, boolean flushCache)
|
||||||
throws IOException, NoSuchElementException {
|
throws IOException, NoSuchElementException {
|
||||||
String illustIdStr = buildSyncKey(Integer.toString(illustId));
|
Locker<String> locker = buildSyncKey(Integer.toString(illustId));
|
||||||
|
String illustIdStr = locker.getKey();
|
||||||
JsonObject illustInfoObj = null;
|
JsonObject illustInfoObj = null;
|
||||||
if (!illustInfoCache.exists(illustIdStr) || flushCache) {
|
if (!illustInfoCache.exists(illustIdStr) || flushCache) {
|
||||||
synchronized (illustIdStr) {
|
try {
|
||||||
|
locker.lock();
|
||||||
|
synchronized (locker) {
|
||||||
if (!illustInfoCache.exists(illustIdStr) || flushCache) {
|
if (!illustInfoCache.exists(illustIdStr) || flushCache) {
|
||||||
illustInfoObj = BotGlobal.getGlobal().getPixivDownload().getIllustInfoByIllustId(illustId);
|
illustInfoObj = BotGlobal.getGlobal().getPixivDownload().getIllustInfoByIllustId(illustId);
|
||||||
illustInfoCache.update(illustIdStr, illustInfoObj, null);
|
illustInfoCache.update(illustIdStr, illustInfoObj, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
locker.unlock();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(Objects.isNull(illustInfoObj)) {
|
if(Objects.isNull(illustInfoObj)) {
|
||||||
@ -254,10 +273,13 @@ public final class CacheStoreCentral {
|
|||||||
* @throws IOException 当Http请求处理发生异常时抛出
|
* @throws IOException 当Http请求处理发生异常时抛出
|
||||||
*/
|
*/
|
||||||
public JsonObject getIllustPreLoadData(int illustId, boolean flushCache) throws IOException {
|
public JsonObject getIllustPreLoadData(int illustId, boolean flushCache) throws IOException {
|
||||||
String illustIdStr = buildSyncKey(Integer.toString(illustId));
|
Locker<String> locker = buildSyncKey(Integer.toString(illustId));
|
||||||
|
String illustIdStr = locker.getKey();
|
||||||
JsonObject result = null;
|
JsonObject result = null;
|
||||||
if (!illustPreLoadDataCache.exists(illustIdStr) || flushCache) {
|
if (!illustPreLoadDataCache.exists(illustIdStr) || flushCache) {
|
||||||
synchronized (illustIdStr) {
|
try {
|
||||||
|
locker.lock();
|
||||||
|
synchronized (locker) {
|
||||||
if (!illustPreLoadDataCache.exists(illustIdStr) || flushCache) {
|
if (!illustPreLoadDataCache.exists(illustIdStr) || flushCache) {
|
||||||
log.trace("IllustId {} 缓存失效, 正在更新...", illustId);
|
log.trace("IllustId {} 缓存失效, 正在更新...", illustId);
|
||||||
JsonObject preLoadDataObj = BotGlobal.getGlobal().getPixivDownload()
|
JsonObject preLoadDataObj = BotGlobal.getGlobal().getPixivDownload()
|
||||||
@ -280,6 +302,9 @@ public final class CacheStoreCentral {
|
|||||||
log.trace("作品Id {} preLoadData缓存已更新(有效时间: {})", illustId, expire);
|
log.trace("作品Id {} preLoadData缓存已更新(有效时间: {})", illustId, expire);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
locker.unlock();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(Objects.isNull(result)) {
|
if(Objects.isNull(result)) {
|
||||||
@ -291,10 +316,14 @@ public final class CacheStoreCentral {
|
|||||||
|
|
||||||
public List<String> getIllustPages(int illustId, PixivDownload.PageQuality quality, boolean flushCache)
|
public List<String> getIllustPages(int illustId, PixivDownload.PageQuality quality, boolean flushCache)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
String pagesSign = buildSyncKey(Integer.toString(illustId), ".", quality.name());
|
Locker<String> locker
|
||||||
|
= buildSyncKey(Integer.toString(illustId), ".", quality.name());
|
||||||
|
String pagesSign = locker.getKey();
|
||||||
List<String> result = null;
|
List<String> result = null;
|
||||||
if (!pagesCache.exists(pagesSign) || flushCache) {
|
if (!pagesCache.exists(pagesSign) || flushCache) {
|
||||||
synchronized (pagesSign) {
|
try {
|
||||||
|
locker.lock();
|
||||||
|
synchronized (locker) {
|
||||||
if (!pagesCache.exists(pagesSign) || flushCache) {
|
if (!pagesCache.exists(pagesSign) || flushCache) {
|
||||||
List<String> linkList = PixivDownload
|
List<String> linkList = PixivDownload
|
||||||
.getIllustAllPageDownload(BotGlobal.getGlobal().getPixivDownload().getHttpClient(),
|
.getIllustAllPageDownload(BotGlobal.getGlobal().getPixivDownload().getHttpClient(),
|
||||||
@ -303,6 +332,9 @@ public final class CacheStoreCentral {
|
|||||||
pagesCache.update(pagesSign, linkList, null);
|
pagesCache.update(pagesSign, linkList, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
locker.unlock();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if(Objects.isNull(result)) {
|
if(Objects.isNull(result)) {
|
||||||
@ -341,16 +373,20 @@ public final class CacheStoreCentral {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String date = new SimpleDateFormat("yyyyMMdd").format(queryDate);
|
String date = new SimpleDateFormat("yyyyMMdd").format(queryDate);
|
||||||
String requestSign = buildSyncKey(contentType.name(), ".", mode.name(), ".", date);
|
Locker<String> locker
|
||||||
|
= buildSyncKey(contentType.name(), ".", mode.name(), ".", date);
|
||||||
|
String requestSign = locker.getKey();
|
||||||
List<JsonObject> result = null;
|
List<JsonObject> result = null;
|
||||||
if(!rankingCache.exists(requestSign) || flushCache) {
|
if(!rankingCache.exists(requestSign) || flushCache) {
|
||||||
synchronized(requestSign) {
|
try {
|
||||||
if(!rankingCache.exists(requestSign) || flushCache) {
|
locker.lock();
|
||||||
|
synchronized (locker) {
|
||||||
|
if (!rankingCache.exists(requestSign) || flushCache) {
|
||||||
log.trace("Ranking缓存失效, 正在更新...(RequestSign: {})", requestSign);
|
log.trace("Ranking缓存失效, 正在更新...(RequestSign: {})", requestSign);
|
||||||
List<JsonObject> rankingResult = BotGlobal.getGlobal().getPixivDownload()
|
List<JsonObject> rankingResult = BotGlobal.getGlobal().getPixivDownload()
|
||||||
.getRanking(contentType, mode, queryDate, 1, 500);
|
.getRanking(contentType, mode, queryDate, 1, 500);
|
||||||
long expireTime = 0;
|
long expireTime = 0;
|
||||||
if(rankingResult.size() == 0) {
|
if (rankingResult.size() == 0) {
|
||||||
expireTime = 5400000 + expireTimeFloatRandom.nextInt(1800000);
|
expireTime = 5400000 + expireTimeFloatRandom.nextInt(1800000);
|
||||||
log.warn("数据获取失败, 将设置浮动有效时间以准备下次更新. (ExpireTime: {}ms)", expireTime);
|
log.warn("数据获取失败, 将设置浮动有效时间以准备下次更新. (ExpireTime: {}ms)", expireTime);
|
||||||
}
|
}
|
||||||
@ -359,6 +395,9 @@ public final class CacheStoreCentral {
|
|||||||
log.trace("Ranking缓存更新完成.(RequestSign: {})", requestSign);
|
log.trace("Ranking缓存更新完成.(RequestSign: {})", requestSign);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
locker.unlock();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Objects.isNull(result)) {
|
if (Objects.isNull(result)) {
|
||||||
@ -385,25 +424,28 @@ public final class CacheStoreCentral {
|
|||||||
String area,
|
String area,
|
||||||
String includeKeywords,
|
String includeKeywords,
|
||||||
String excludeKeywords,
|
String excludeKeywords,
|
||||||
String contentOption) throws IOException {
|
String contentOption,
|
||||||
PixivSearchBuilder searchBuilder = new PixivSearchBuilder(Strings.isNullOrEmpty(content) ? "" : content);
|
int pageIndex
|
||||||
|
) throws IOException {
|
||||||
|
PixivSearchLinkBuilder searchBuilder = new PixivSearchLinkBuilder(Strings.isNullOrEmpty(content) ? "" : content);
|
||||||
if (type != null) {
|
if (type != null) {
|
||||||
try {
|
try {
|
||||||
searchBuilder.setSearchType(PixivSearchBuilder.SearchType.valueOf(type.toUpperCase()));
|
searchBuilder.setSearchType(PixivSearchLinkBuilder.SearchType.valueOf(type.toUpperCase()));
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("不支持的SearchType: {}", type);
|
log.warn("不支持的SearchType: {}", type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (area != null) {
|
if (area != null) {
|
||||||
try {
|
try {
|
||||||
searchBuilder.setSearchArea(PixivSearchBuilder.SearchArea.valueOf(area));
|
searchBuilder.setSearchArea(PixivSearchLinkBuilder.SearchArea.valueOf(area));
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("不支持的SearchArea: {}", area);
|
log.warn("不支持的SearchArea: {}", area);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (contentOption != null) {
|
if (contentOption != null) {
|
||||||
try {
|
try {
|
||||||
searchBuilder.setSearchContentOption(PixivSearchBuilder.SearchContentOption.valueOf(contentOption));
|
searchBuilder.setSearchContentOption(
|
||||||
|
PixivSearchLinkBuilder.SearchContentOption.valueOf(contentOption.trim().toUpperCase()));
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("不支持的SearchContentOption: {}", contentOption);
|
log.warn("不支持的SearchContentOption: {}", contentOption);
|
||||||
}
|
}
|
||||||
@ -424,13 +466,21 @@ public final class CacheStoreCentral {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log.info("正在搜索作品, 条件: {}", searchBuilder.getSearchCondition());
|
if(pageIndex > 0) {
|
||||||
|
searchBuilder.setPage(pageIndex);
|
||||||
|
}
|
||||||
|
|
||||||
String requestUrl = searchBuilder.buildURL().intern();
|
log.debug("正在搜索作品, 条件: {}", searchBuilder.getSearchCondition());
|
||||||
|
|
||||||
|
Locker<String> locker
|
||||||
|
= buildSyncKey(searchBuilder.buildURL());
|
||||||
|
String requestUrl = locker.getKey();
|
||||||
log.debug("RequestUrl: {}", requestUrl);
|
log.debug("RequestUrl: {}", requestUrl);
|
||||||
JsonObject resultBody = null;
|
JsonObject resultBody = null;
|
||||||
if(!searchBodyCache.exists(requestUrl)) {
|
if(!searchBodyCache.exists(requestUrl)) {
|
||||||
synchronized (requestUrl) {
|
try {
|
||||||
|
locker.lock();
|
||||||
|
synchronized (locker) {
|
||||||
if (!searchBodyCache.exists(requestUrl)) {
|
if (!searchBodyCache.exists(requestUrl)) {
|
||||||
log.trace("searchBody缓存失效, 正在更新...");
|
log.trace("searchBody缓存失效, 正在更新...");
|
||||||
JsonObject jsonObject;
|
JsonObject jsonObject;
|
||||||
@ -445,7 +495,7 @@ public final class CacheStoreCentral {
|
|||||||
|
|
||||||
if (jsonObject.get("error").getAsBoolean()) {
|
if (jsonObject.get("error").getAsBoolean()) {
|
||||||
log.error("接口请求错误, 错误信息: {}", jsonObject.get("message").getAsString());
|
log.error("接口请求错误, 错误信息: {}", jsonObject.get("message").getAsString());
|
||||||
throw new IOException("Interface Request Error: " + jsonObject.get("message").getAsString());
|
throw new HttpRequestException(response.getStatusLine(), responseBody);
|
||||||
}
|
}
|
||||||
|
|
||||||
long expire = 7200 * 1000;
|
long expire = 7200 * 1000;
|
||||||
@ -463,6 +513,9 @@ public final class CacheStoreCentral {
|
|||||||
log.trace("搜索缓存命中.");
|
log.trace("搜索缓存命中.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
locker.unlock();
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
log.trace("搜索缓存命中.");
|
log.trace("搜索缓存命中.");
|
||||||
}
|
}
|
||||||
@ -492,12 +545,12 @@ public final class CacheStoreCentral {
|
|||||||
* @param keys String对象
|
* @param keys String对象
|
||||||
* @return 合并后, 如果常量池存在合并后的结果, 则返回常量池中的对象, 否则存入常量池后返回.
|
* @return 合并后, 如果常量池存在合并后的结果, 则返回常量池中的对象, 否则存入常量池后返回.
|
||||||
*/
|
*/
|
||||||
private static String buildSyncKey(String... keys) {
|
private Locker<String> buildSyncKey(String... keys) {
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
for (String string : keys) {
|
for (String string : keys) {
|
||||||
sb.append(string);
|
sb.append(string);
|
||||||
}
|
}
|
||||||
return sb.toString().intern();
|
return lockerMap.createLocker(sb.toString(), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -75,6 +75,9 @@ public class HotDataCacheStore<T> implements CacheStore<T>, Cleanable {
|
|||||||
log.trace("Current缓存库更新完成.");
|
log.trace("Current缓存库更新完成.");
|
||||||
result = parentResult;
|
result = parentResult;
|
||||||
} else {
|
} else {
|
||||||
|
// 更新该Key的过期时间
|
||||||
|
current.update(key, result,
|
||||||
|
expireTime + (expireFloatRange <= 0 ? 0 : random.nextInt(expireFloatRange)));
|
||||||
log.trace("Current缓存库缓存命中.");
|
log.trace("Current缓存库缓存命中.");
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
@ -138,11 +141,15 @@ public class HotDataCacheStore<T> implements CacheStore<T>, Cleanable {
|
|||||||
* <p>该方法仅清理Current缓存库, 不会对上游缓存库造成影响.</p>
|
* <p>该方法仅清理Current缓存库, 不会对上游缓存库造成影响.</p>
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void clean() {
|
public void clean() throws Exception {
|
||||||
|
if(current instanceof Cleanable) {
|
||||||
|
((Cleanable) current).clean();
|
||||||
|
} else {
|
||||||
for(String key : this.current.keys()) {
|
for(String key : this.current.keys()) {
|
||||||
if(current.exists(key)) {
|
if (!current.exists(key)) {
|
||||||
current.remove(key);
|
current.remove(key);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package net.lamgc.cgj.bot.cache;
|
package net.lamgc.cgj.bot.cache;
|
||||||
|
|
||||||
import net.lamgc.cgj.bot.boot.BotGlobal;
|
import net.lamgc.cgj.bot.boot.BotGlobal;
|
||||||
import net.lamgc.cgj.bot.cache.exception.HttpRequestException;
|
import net.lamgc.cgj.exception.HttpRequestException;
|
||||||
import net.lamgc.cgj.pixiv.PixivURL;
|
import net.lamgc.cgj.pixiv.PixivURL;
|
||||||
import net.lamgc.cgj.util.URLs;
|
import net.lamgc.cgj.util.URLs;
|
||||||
import net.lamgc.utils.event.EventHandler;
|
import net.lamgc.utils.event.EventHandler;
|
||||||
|
@ -7,7 +7,7 @@ import com.google.gson.JsonObject;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import net.lamgc.cgj.bot.cache.exception.HttpRequestException;
|
import net.lamgc.cgj.exception.HttpRequestException;
|
||||||
|
|
||||||
import java.util.Hashtable;
|
import java.util.Hashtable;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@ -66,17 +66,17 @@ public final class ImageCacheStore {
|
|||||||
// 置任务状态
|
// 置任务状态
|
||||||
task.taskState.set(TaskState.RUNNING);
|
task.taskState.set(TaskState.RUNNING);
|
||||||
|
|
||||||
Throwable throwable = null;
|
Future<Throwable> future = imageCacheExecutor.submit(() -> {
|
||||||
try {
|
|
||||||
throwable = imageCacheExecutor.submit(() -> {
|
|
||||||
try {
|
try {
|
||||||
handler.getImageToCache(cacheObject);
|
handler.getImageToCache(cacheObject);
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}).get();
|
});
|
||||||
|
Throwable throwable;
|
||||||
|
try {
|
||||||
|
throwable = future.get();
|
||||||
if(throwable == null) {
|
if(throwable == null) {
|
||||||
task.taskState.set(TaskState.COMPLETE);
|
task.taskState.set(TaskState.COMPLETE);
|
||||||
} else {
|
} else {
|
||||||
@ -84,6 +84,12 @@ public final class ImageCacheStore {
|
|||||||
}
|
}
|
||||||
} catch (ExecutionException e) {
|
} catch (ExecutionException e) {
|
||||||
log.error("执行图片缓存任务时发生异常", e);
|
log.error("执行图片缓存任务时发生异常", e);
|
||||||
|
task.taskState.set(TaskState.ERROR);
|
||||||
|
return e.getCause();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
future.cancel(true);
|
||||||
|
task.taskState.set(TaskState.ERROR);
|
||||||
|
throw e;
|
||||||
}
|
}
|
||||||
return throwable;
|
return throwable;
|
||||||
} finally {
|
} finally {
|
||||||
|
@ -2,10 +2,7 @@ package net.lamgc.cgj.bot.cache;
|
|||||||
|
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
|
||||||
import java.util.Date;
|
import java.util.*;
|
||||||
import java.util.Hashtable;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -151,11 +148,14 @@ public class LocalHashCacheStore<T> implements CacheStore<T>, Cleanable {
|
|||||||
@Override
|
@Override
|
||||||
public void clean() {
|
public void clean() {
|
||||||
Date currentDate = new Date();
|
Date currentDate = new Date();
|
||||||
|
Set<String> expireKeySet = new HashSet<>();
|
||||||
cache.forEach((key, value) -> {
|
cache.forEach((key, value) -> {
|
||||||
if(value.isExpire(currentDate)) {
|
if(value.isExpire(currentDate)) {
|
||||||
cache.remove(key);
|
expireKeySet.add(key);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expireKeySet.forEach(cache::remove);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class CacheObject<T> implements Comparable<CacheObject<T>> {
|
public static class CacheObject<T> implements Comparable<CacheObject<T>> {
|
||||||
|
@ -51,27 +51,27 @@ abstract class RedisPoolCacheStore<T> implements CacheStore<T> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void update(String key, T value, Date expire) {
|
public void update(String key, T value, Date expire) {
|
||||||
try (Jedis jedis = jedisPool.getResource()) {
|
executeJedisCommand(jedis -> {
|
||||||
jedis.set(keyPrefix + key, parse(value));
|
jedis.set(keyPrefix + key, parse(value));
|
||||||
if(expire != null) {
|
if(expire != null) {
|
||||||
jedis.pexpireAt(keyPrefix + key, expire.getTime());
|
jedis.pexpireAt(keyPrefix + key, expire.getTime());
|
||||||
log.debug("已设置Key {} 的过期时间(Expire: {})", key, expire.getTime());
|
log.debug("已设置Key {} 的过期时间(Expire: {})", key, expire.getTime());
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public T getCache(String key) {
|
public T getCache(String key) {
|
||||||
try (Jedis jedis = jedisPool.getResource()) {
|
return executeJedisCommand(jedis -> {
|
||||||
return analysis(jedis.get(keyPrefix + key));
|
return analysis(jedis.get(keyPrefix + key));
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean exists(String key) {
|
public boolean exists(String key) {
|
||||||
try (Jedis jedis = jedisPool.getResource()) {
|
return executeJedisCommand(jedis -> {
|
||||||
return jedis.exists(keyPrefix + key);
|
return jedis.exists(keyPrefix + key);
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -81,23 +81,21 @@ abstract class RedisPoolCacheStore<T> implements CacheStore<T> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean clear() {
|
public boolean clear() {
|
||||||
try (Jedis jedis = jedisPool.getResource()) {
|
return executeJedisCommand(jedis -> {
|
||||||
return jedis.flushDB().equalsIgnoreCase("ok");
|
return jedis.flushDB().equalsIgnoreCase("ok");
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Set<String> keys() {
|
public Set<String> keys() {
|
||||||
try (Jedis jedis = jedisPool.getResource()) {
|
return executeJedisCommand(jedis -> {
|
||||||
return jedis.keys(keyPrefix + "*");
|
return jedis.keys(keyPrefix + "*");
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean remove(String key) {
|
public boolean remove(String key) {
|
||||||
try (Jedis jedis = jedisPool.getResource()) {
|
return executeJedisCommand(jedis -> jedis.del(keyPrefix + key) == 1);
|
||||||
return jedis.del(keyPrefix + key) == 1;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -46,9 +46,9 @@ public class BotEventHandler implements EventHandler {
|
|||||||
* 消息事件执行器
|
* 消息事件执行器
|
||||||
*/
|
*/
|
||||||
private final static EventExecutor executor = new EventExecutor(new TimeLimitThreadPoolExecutor(
|
private final static EventExecutor executor = new EventExecutor(new TimeLimitThreadPoolExecutor(
|
||||||
0,
|
180000, // 3minThr
|
||||||
Math.max(Runtime.getRuntime().availableProcessors(), 4),
|
Math.max(Runtime.getRuntime().availableProcessors(), 4),
|
||||||
Math.max(Math.max(Runtime.getRuntime().availableProcessors() * 2, 4), 32),
|
Math.min(Math.max(Runtime.getRuntime().availableProcessors(), 4), 32),
|
||||||
30L,
|
30L,
|
||||||
TimeUnit.SECONDS,
|
TimeUnit.SECONDS,
|
||||||
new LinkedBlockingQueue<>(1536),
|
new LinkedBlockingQueue<>(1536),
|
||||||
@ -69,11 +69,15 @@ public class BotEventHandler implements EventHandler {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
executor.setEnableEventResend(true);
|
||||||
executor.setEventUncaughtExceptionHandler(new EventUncaughtExceptionHandler() {
|
executor.setEventUncaughtExceptionHandler(new EventUncaughtExceptionHandler() {
|
||||||
private final Logger log = LoggerFactory.getLogger(this.getClass());
|
private final Logger log = LoggerFactory.getLogger(this.getClass());
|
||||||
@Override
|
@Override
|
||||||
public void exceptionHandler(Thread executeThread, EventHandler handler, Method handlerMethod, EventObject event, Throwable cause) {
|
public void exceptionHandler(Thread executeThread, EventHandler handler, Method handlerMethod, EventObject event, Throwable cause) {
|
||||||
log.error("发生未捕获异常:\nThread:{}, EventHandler: {}, HandlerMethod: {}, EventObject: {}\n{}",
|
log.error("EventExecutor@{} 发生未捕获异常:\n\t" +
|
||||||
|
"Thread:{}\n\tEventHandler: {}\n\tHandlerMethod: {}\n\tEventObject: {}\n" +
|
||||||
|
"------------------ Stack Trace ------------------\n{}",
|
||||||
|
executor.hashCode(),
|
||||||
executeThread.getName(),
|
executeThread.getName(),
|
||||||
handler.toString(),
|
handler.toString(),
|
||||||
handlerMethod.getName(),
|
handlerMethod.getName(),
|
||||||
@ -128,6 +132,7 @@ public class BotEventHandler implements EventHandler {
|
|||||||
/**
|
/**
|
||||||
* 投递消息事件
|
* 投递消息事件
|
||||||
* @param event 事件对象
|
* @param event 事件对象
|
||||||
|
* @param sync 是否同步执行事件
|
||||||
*/
|
*/
|
||||||
@NotAccepted
|
@NotAccepted
|
||||||
public static void executeMessageEvent(MessageEvent event, boolean sync) throws InterruptedException {
|
public static void executeMessageEvent(MessageEvent event, boolean sync) throws InterruptedException {
|
||||||
@ -219,8 +224,8 @@ public class BotEventHandler implements EventHandler {
|
|||||||
} catch(DeveloperRunnerException e) {
|
} catch(DeveloperRunnerException e) {
|
||||||
Throwable cause = e.getCause();
|
Throwable cause = e.getCause();
|
||||||
if (cause instanceof InterruptedException) {
|
if (cause instanceof InterruptedException) {
|
||||||
log.error("命令执行超时, 终止执行.");
|
log.error("命令执行超时, 终止执行.", cause);
|
||||||
result = "色图姬发现这个命令的处理时间太久了!所以打断了这个命令。";
|
result = "色图姬查阅图库太久,被赶出来了!";
|
||||||
} else if(cause instanceof NoSuchElementException && cause.getMessage().startsWith("No work found: ")) {
|
} else if(cause instanceof NoSuchElementException && cause.getMessage().startsWith("No work found: ")) {
|
||||||
String message = cause.getMessage();
|
String message = cause.getMessage();
|
||||||
log.error("指定作品不存在.(Id: {})", message.substring(message.lastIndexOf(": ") + 2));
|
log.error("指定作品不存在.(Id: {})", message.substring(message.lastIndexOf(": ") + 2));
|
||||||
@ -234,9 +239,12 @@ public class BotEventHandler implements EventHandler {
|
|||||||
if(!Objects.isNull(result) && result instanceof String && !isMute(event.getFromGroup())) {
|
if(!Objects.isNull(result) && result instanceof String && !isMute(event.getFromGroup())) {
|
||||||
try {
|
try {
|
||||||
int sendResult = event.sendMessage((String) result);
|
int sendResult = event.sendMessage((String) result);
|
||||||
if(sendResult < 0) {
|
if (sendResult < 0) {
|
||||||
log.warn("消息发送失败, Sender {} 返回错误代码: {}", event.getClass().getName(), sendResult);
|
log.warn("消息发送失败, Sender {} 返回错误代码: {}", event.getClass().getName(), sendResult);
|
||||||
}
|
}
|
||||||
|
} catch(InterruptedException e) {
|
||||||
|
log.info("事件在发送消息时超时, 重新投递该事件.(Event: {})", event);
|
||||||
|
EventExecutor.resendCurrentEvent();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("发送消息时发生异常", e);
|
log.error("发送消息时发生异常", e);
|
||||||
}
|
}
|
||||||
@ -258,6 +266,11 @@ public class BotEventHandler implements EventHandler {
|
|||||||
return !message.startsWith(COMMAND_PREFIX) && !message.startsWith(ADMIN_COMMAND_PREFIX);
|
return !message.startsWith(COMMAND_PREFIX) && !message.startsWith(ADMIN_COMMAND_PREFIX);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询某群组中Bot是否被禁言
|
||||||
|
* @param groupId 待查询的群组号
|
||||||
|
* @return 如果被禁言, 返回true, 如果未被禁言或禁言情况未知, 返回false
|
||||||
|
*/
|
||||||
private static boolean isMute(long groupId) {
|
private static boolean isMute(long groupId) {
|
||||||
Boolean mute = isMute(groupId, false);
|
Boolean mute = isMute(groupId, false);
|
||||||
return mute != null && mute;
|
return mute != null && mute;
|
||||||
|
@ -1,70 +0,0 @@
|
|||||||
package net.lamgc.cgj.bot.event;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
public class BufferMessageEvent extends MessageEvent {
|
|
||||||
|
|
||||||
private final StringBuffer buffer = new StringBuffer();
|
|
||||||
|
|
||||||
private final MessageEvent parent;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 以空消息空Id生成BufferMessageEvent
|
|
||||||
*/
|
|
||||||
public BufferMessageEvent() {
|
|
||||||
super(0, 0, "");
|
|
||||||
parent = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 提供消息内容构造BufferMessageEvent
|
|
||||||
* @param message 传入的消息内容
|
|
||||||
*/
|
|
||||||
public BufferMessageEvent(String message) {
|
|
||||||
super(0, 0, message);
|
|
||||||
parent = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 提供消息内容构和Id信息造BufferMessageEvent
|
|
||||||
* @param groupId 群组Id
|
|
||||||
* @param qqId 发送者Id
|
|
||||||
* @param message 传入的消息内容
|
|
||||||
*/
|
|
||||||
public BufferMessageEvent(int groupId, int qqId, String message) {
|
|
||||||
super(groupId, qqId, message);
|
|
||||||
parent = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 使用事件构造BufferMessageEvent
|
|
||||||
* @param parentEvent 父级消息事件对象
|
|
||||||
*/
|
|
||||||
public BufferMessageEvent(MessageEvent parentEvent) {
|
|
||||||
super(parentEvent.getFromGroup(), parentEvent.getFromQQ(), parentEvent.getMessage());
|
|
||||||
parent = parentEvent;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int sendMessage(String message) {
|
|
||||||
buffer.append(message);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 当提供了父级消息事件时, 本方法调用父级消息事件对象的{@code getImageUrl(String)}, 如果没有, 返回{@code null}
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public String getImageUrl(String image) {
|
|
||||||
return Objects.isNull(this.parent) ? null : this.parent.getImageUrl(image);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取缓冲区消息内容
|
|
||||||
* @return 消息内容
|
|
||||||
*/
|
|
||||||
public String getBufferMessage() {
|
|
||||||
return buffer.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -0,0 +1,23 @@
|
|||||||
|
package net.lamgc.cgj.bot.event;
|
||||||
|
|
||||||
|
import net.lamgc.cgj.bot.message.MessageSender;
|
||||||
|
|
||||||
|
public class BufferedMessageSender implements MessageSender {
|
||||||
|
|
||||||
|
private final StringBuffer buffer = new StringBuffer();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int sendMessage(String message) {
|
||||||
|
buffer.append(message);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从缓冲区中取出消息内容.
|
||||||
|
* @return 返回事件发送的消息内容.
|
||||||
|
*/
|
||||||
|
public String getBufferContent() {
|
||||||
|
return buffer.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -57,7 +57,7 @@ public abstract class MessageEvent implements EventObject, MessageSender {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return this.getClass().getSimpleName() + "{" +
|
return this.getClass().getSimpleName() + "@" + this.hashCode() + "{" +
|
||||||
"fromGroup=" + getFromGroup() +
|
"fromGroup=" + getFromGroup() +
|
||||||
", fromQQ=" + getFromQQ() +
|
", fromQQ=" + getFromQQ() +
|
||||||
", message='" + getMessage() + '\'' +
|
", message='" + getMessage() + '\'' +
|
||||||
|
@ -31,7 +31,7 @@ public class ConsoleMain {
|
|||||||
long groupId = Long.parseLong(lineReader.readLine("会话群组号:"));
|
long groupId = Long.parseLong(lineReader.readLine("会话群组号:"));
|
||||||
boolean isGroup = false;
|
boolean isGroup = false;
|
||||||
do {
|
do {
|
||||||
String input = lineReader.readLine("App " + qqId + (isGroup ? "@" + groupId : "$private") + " >");
|
String input = lineReader.readLine("App " + qqId + (isGroup ? "@" + groupId : "#private") + " >");
|
||||||
if(input.equalsIgnoreCase("#exit")) {
|
if(input.equalsIgnoreCase("#exit")) {
|
||||||
System.out.println("退出应用...");
|
System.out.println("退出应用...");
|
||||||
break;
|
break;
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
package net.lamgc.cgj.bot.framework.cli.message;
|
package net.lamgc.cgj.bot.framework.cli.message;
|
||||||
|
|
||||||
import net.lamgc.cgj.bot.event.MessageEvent;
|
import net.lamgc.cgj.bot.event.MessageEvent;
|
||||||
|
import net.lamgc.cgj.bot.message.MessageSenderBuilder;
|
||||||
import java.util.Date;
|
import net.lamgc.cgj.bot.message.MessageSource;
|
||||||
|
|
||||||
public class ConsoleMessageEvent extends MessageEvent {
|
public class ConsoleMessageEvent extends MessageEvent {
|
||||||
|
|
||||||
@ -11,9 +11,15 @@ public class ConsoleMessageEvent extends MessageEvent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int sendMessage(String message) {
|
public int sendMessage(String message) throws Exception {
|
||||||
System.out.println(new Date() + " Bot: " + message);
|
if(getFromGroup() <= 0) {
|
||||||
return 0;
|
return MessageSenderBuilder
|
||||||
|
.getMessageSender(MessageSource.PRIVATE, getFromQQ()).sendMessage(message);
|
||||||
|
} else {
|
||||||
|
return MessageSenderBuilder
|
||||||
|
.getMessageSender(MessageSource.GROUP, getFromQQ()).sendMessage(message);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -1,13 +1,26 @@
|
|||||||
package net.lamgc.cgj.bot.framework.cli.message;
|
package net.lamgc.cgj.bot.framework.cli.message;
|
||||||
|
|
||||||
import net.lamgc.cgj.bot.message.MessageSender;
|
import net.lamgc.cgj.bot.message.MessageSender;
|
||||||
|
import net.lamgc.cgj.bot.message.MessageSource;
|
||||||
|
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
public class ConsoleMessageSender implements MessageSender {
|
public class ConsoleMessageSender implements MessageSender {
|
||||||
|
|
||||||
|
private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
|
||||||
|
private final MessageSource source;
|
||||||
|
private final long id;
|
||||||
|
|
||||||
|
ConsoleMessageSender(MessageSource source, long id) {
|
||||||
|
this.source = source;
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public synchronized int sendMessage(String message) {
|
public synchronized int sendMessage(String message) {
|
||||||
System.out.println(new Date() + " Bot: " + message);
|
System.out.println(dateFormat.format(new Date()) + " Bot -> " +
|
||||||
|
(source == MessageSource.PRIVATE ? "#" : "@") + id + ": " + message);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,10 +6,8 @@ import net.lamgc.cgj.bot.message.MessageSource;
|
|||||||
|
|
||||||
public class ConsoleMessageSenderFactory implements MessageSenderFactory {
|
public class ConsoleMessageSenderFactory implements MessageSenderFactory {
|
||||||
|
|
||||||
private final static ConsoleMessageSender sender = new ConsoleMessageSender();
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public MessageSender createMessageSender(MessageSource source, long id) {
|
public MessageSender createMessageSender(MessageSource source, long id) {
|
||||||
return sender;
|
return new ConsoleMessageSender(source, id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -26,13 +26,13 @@ public class SpringCQMessageEvent extends MessageEvent {
|
|||||||
this.cq = Objects.requireNonNull(cq);
|
this.cq = Objects.requireNonNull(cq);
|
||||||
MessageSource source;
|
MessageSource source;
|
||||||
if(messageEvent instanceof CQGroupMessageEvent) {
|
if(messageEvent instanceof CQGroupMessageEvent) {
|
||||||
source = MessageSource.Group;
|
source = MessageSource.GROUP;
|
||||||
} else if (messageEvent instanceof CQDiscussMessageEvent) {
|
} else if (messageEvent instanceof CQDiscussMessageEvent) {
|
||||||
source = MessageSource.Discuss;
|
source = MessageSource.DISCUSS;
|
||||||
} else {
|
} else {
|
||||||
source = MessageSource.Private;
|
source = MessageSource.PRIVATE;
|
||||||
}
|
}
|
||||||
messageSender = new SpringCQMessageSender(cq, source, source == MessageSource.Private ? getFromQQ() : getFromGroup());
|
messageSender = new SpringCQMessageSender(cq, source, source == MessageSource.PRIVATE ? getFromQQ() : getFromGroup());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -19,11 +19,11 @@ public class SpringCQMessageSender implements MessageSender {
|
|||||||
@Override
|
@Override
|
||||||
public int sendMessage(String message) {
|
public int sendMessage(String message) {
|
||||||
switch (source) {
|
switch (source) {
|
||||||
case Private:
|
case PRIVATE:
|
||||||
return coolQ.sendPrivateMsg(target, message, false).getData().getMessageId();
|
return coolQ.sendPrivateMsg(target, message, false).getData().getMessageId();
|
||||||
case Group:
|
case GROUP:
|
||||||
return coolQ.sendGroupMsg(target, message, false).getData().getMessageId();
|
return coolQ.sendGroupMsg(target, message, false).getData().getMessageId();
|
||||||
case Discuss:
|
case DISCUSS:
|
||||||
return coolQ.sendDiscussMsg(target, message, false).getData().getMessageId();
|
return coolQ.sendDiscussMsg(target, message, false).getData().getMessageId();
|
||||||
default:
|
default:
|
||||||
return -1;
|
return -1;
|
||||||
|
@ -28,9 +28,9 @@ public class MiraiMessageEvent extends net.lamgc.cgj.bot.event.MessageEvent {
|
|||||||
message.getSender().getId(), getMessageBodyWithoutSource(message.getMessage().toString()));
|
message.getSender().getId(), getMessageBodyWithoutSource(message.getMessage().toString()));
|
||||||
this.messageObject = Objects.requireNonNull(message);
|
this.messageObject = Objects.requireNonNull(message);
|
||||||
if(message instanceof GroupMessageEvent) {
|
if(message instanceof GroupMessageEvent) {
|
||||||
messageSender = new MiraiMessageSender(((GroupMessageEvent) message).getGroup(), MessageSource.Group);
|
messageSender = new MiraiMessageSender(((GroupMessageEvent) message).getGroup(), MessageSource.GROUP);
|
||||||
} else {
|
} else {
|
||||||
messageSender = new MiraiMessageSender(message.getSender(), MessageSource.Private);
|
messageSender = new MiraiMessageSender(message.getSender(), MessageSource.PRIVATE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -45,9 +45,9 @@ public class MiraiMessageEvent extends net.lamgc.cgj.bot.event.MessageEvent {
|
|||||||
super(groupId, qqId, getMessageBodyWithoutSource(message.toString()));
|
super(groupId, qqId, getMessageBodyWithoutSource(message.toString()));
|
||||||
this.messageObject = Objects.requireNonNull(messageObject, "messageObject is null");
|
this.messageObject = Objects.requireNonNull(messageObject, "messageObject is null");
|
||||||
if(groupId != 0) {
|
if(groupId != 0) {
|
||||||
this.messageSender = new MiraiMessageSender(((GroupMessageEvent) messageObject).getGroup(), MessageSource.Group);
|
this.messageSender = new MiraiMessageSender(((GroupMessageEvent) messageObject).getGroup(), MessageSource.GROUP);
|
||||||
} else {
|
} else {
|
||||||
this.messageSender = new MiraiMessageSender(messageObject.getSender(), MessageSource.Group);
|
this.messageSender = new MiraiMessageSender(messageObject.getSender(), MessageSource.GROUP);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -40,7 +40,7 @@ public class MiraiMessageSender implements MessageSender {
|
|||||||
* @throws NoSuchElementException 当在机器人好友列表或群列表里没有这个好友或群的时候抛出
|
* @throws NoSuchElementException 当在机器人好友列表或群列表里没有这个好友或群的时候抛出
|
||||||
*/
|
*/
|
||||||
public MiraiMessageSender(Bot bot, MessageSource source, long id) {
|
public MiraiMessageSender(Bot bot, MessageSource source, long id) {
|
||||||
this(source == MessageSource.Private ? bot.getFriend(id) : bot.getGroup(id), source);
|
this(source == MessageSource.PRIVATE ? bot.getFriend(id) : bot.getGroup(id), source);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -7,17 +7,17 @@ public enum MessageSource {
|
|||||||
/**
|
/**
|
||||||
* 私聊消息
|
* 私聊消息
|
||||||
*/
|
*/
|
||||||
Private,
|
PRIVATE,
|
||||||
/**
|
/**
|
||||||
* 群组消息
|
* 群组消息
|
||||||
*/
|
*/
|
||||||
Group,
|
GROUP,
|
||||||
/**
|
/**
|
||||||
* 讨论组消息
|
* 讨论组消息
|
||||||
*/
|
*/
|
||||||
Discuss,
|
DISCUSS,
|
||||||
/**
|
/**
|
||||||
* 未知来源
|
* 未知来源
|
||||||
*/
|
*/
|
||||||
Unknown
|
UNKNOWN
|
||||||
}
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package net.lamgc.cgj.bot.sort;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public enum PreLoadDataAttribute {
|
||||||
|
/**
|
||||||
|
* 按点赞数排序
|
||||||
|
*/
|
||||||
|
LIKE("likeCount"),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按页面数排序
|
||||||
|
*/
|
||||||
|
PAGE("pageCount"),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按收藏数排序
|
||||||
|
*/
|
||||||
|
BOOKMARK("bookmarkCount"),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按评论数排序
|
||||||
|
*/
|
||||||
|
COMMENT("commentCount"),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 不明
|
||||||
|
*/
|
||||||
|
RESPONSE("responseCount"),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按查看次数排序
|
||||||
|
*/
|
||||||
|
VIEW("viewCount"),
|
||||||
|
;
|
||||||
|
|
||||||
|
public final String attrName;
|
||||||
|
|
||||||
|
PreLoadDataAttribute(String attrName) {
|
||||||
|
this.attrName = attrName;
|
||||||
|
}
|
||||||
|
}
|
@ -3,6 +3,8 @@ package net.lamgc.cgj.bot.sort;
|
|||||||
import com.google.gson.JsonElement;
|
import com.google.gson.JsonElement;
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
import net.lamgc.cgj.bot.cache.CacheStoreCentral;
|
import net.lamgc.cgj.bot.cache.CacheStoreCentral;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
@ -10,11 +12,13 @@ import java.util.Comparator;
|
|||||||
/**
|
/**
|
||||||
* 收藏数比较器
|
* 收藏数比较器
|
||||||
*/
|
*/
|
||||||
public class PreLoadDataComparator implements Comparator<JsonElement> {
|
public class PreLoadDataAttributeComparator implements Comparator<JsonElement> {
|
||||||
|
|
||||||
private final Attribute attribute;
|
private final static Logger log = LoggerFactory.getLogger(PreLoadDataAttributeComparator.class);
|
||||||
|
|
||||||
public PreLoadDataComparator(Attribute attribute) {
|
private final PreLoadDataAttribute attribute;
|
||||||
|
|
||||||
|
public PreLoadDataAttributeComparator(PreLoadDataAttribute attribute) {
|
||||||
this.attribute = attribute;
|
this.attribute = attribute;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -47,49 +51,9 @@ public class PreLoadDataComparator implements Comparator<JsonElement> {
|
|||||||
illustPreLoadData2.get(attribute.attrName).getAsInt(),
|
illustPreLoadData2.get(attribute.attrName).getAsInt(),
|
||||||
illustPreLoadData1.get(attribute.attrName).getAsInt());
|
illustPreLoadData1.get(attribute.attrName).getAsInt());
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
e.printStackTrace();
|
log.error("获取预加载数据失败", e);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum Attribute {
|
|
||||||
/**
|
|
||||||
* 按点赞数排序
|
|
||||||
*/
|
|
||||||
LIKE("likeCount"),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按页面数排序
|
|
||||||
*/
|
|
||||||
PAGE("pageCount"),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按收藏数排序
|
|
||||||
*/
|
|
||||||
BOOKMARK("bookmarkCount"),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按评论数排序
|
|
||||||
*/
|
|
||||||
COMMENT("commentCount"),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 不明
|
|
||||||
*/
|
|
||||||
RESPONSE("responseCount"),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按查看次数排序
|
|
||||||
*/
|
|
||||||
VIEW("viewCount"),
|
|
||||||
;
|
|
||||||
|
|
||||||
public final String attrName;
|
|
||||||
|
|
||||||
Attribute(String attrName) {
|
|
||||||
this.attrName = attrName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package net.lamgc.cgj.bot.cache.exception;
|
package net.lamgc.cgj.exception;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
@ -6,6 +6,7 @@ import com.google.gson.JsonElement;
|
|||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
import com.google.gson.reflect.TypeToken;
|
import com.google.gson.reflect.TypeToken;
|
||||||
import io.netty.handler.codec.http.HttpHeaderNames;
|
import io.netty.handler.codec.http.HttpHeaderNames;
|
||||||
|
import net.lamgc.cgj.exception.HttpRequestException;
|
||||||
import org.apache.http.Header;
|
import org.apache.http.Header;
|
||||||
import org.apache.http.HttpHost;
|
import org.apache.http.HttpHost;
|
||||||
import org.apache.http.HttpRequest;
|
import org.apache.http.HttpRequest;
|
||||||
@ -326,7 +327,7 @@ public class PixivDownload {
|
|||||||
String responseBody = EntityUtils.toString(response.getEntity());
|
String responseBody = EntityUtils.toString(response.getEntity());
|
||||||
log.trace("ResponseBody: {}", responseBody);
|
log.trace("ResponseBody: {}", responseBody);
|
||||||
if(response.getStatusLine().getStatusCode() != 200) {
|
if(response.getStatusLine().getStatusCode() != 200) {
|
||||||
throw new IOException("Http Response Error: '" + response.getStatusLine() + "', ResponseBody: '" + responseBody + '\'');
|
throw new HttpRequestException(response.getStatusLine(), responseBody);
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonObject resultObject = gson.fromJson(responseBody, JsonObject.class);
|
JsonObject resultObject = gson.fromJson(responseBody, JsonObject.class);
|
||||||
@ -353,7 +354,7 @@ public class PixivDownload {
|
|||||||
HttpResponse response = httpClient.execute(request);
|
HttpResponse response = httpClient.execute(request);
|
||||||
|
|
||||||
if(response.getStatusLine().getStatusCode() != 200) {
|
if(response.getStatusLine().getStatusCode() != 200) {
|
||||||
throw new IOException("Http响应码非200: " + response.getStatusLine());
|
throw new HttpRequestException(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
Document document = Jsoup.parse(EntityUtils.toString(response.getEntity()));
|
Document document = Jsoup.parse(EntityUtils.toString(response.getEntity()));
|
||||||
@ -401,7 +402,7 @@ public class PixivDownload {
|
|||||||
if(resultObject.get("error").getAsBoolean()) {
|
if(resultObject.get("error").getAsBoolean()) {
|
||||||
String message = resultObject.get("message").getAsString();
|
String message = resultObject.get("message").getAsString();
|
||||||
log.warn("作品页面接口请求错误, 错误信息: {}", message);
|
log.warn("作品页面接口请求错误, 错误信息: {}", message);
|
||||||
throw new IOException(message);
|
throw new HttpRequestException(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonArray linkArray = resultObject.getAsJsonArray("body");
|
JsonArray linkArray = resultObject.getAsJsonArray("body");
|
||||||
@ -499,51 +500,12 @@ public class PixivDownload {
|
|||||||
} else {
|
} else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取作品信息
|
* 获取作品信息
|
||||||
* @param illustId 作品ID
|
* @param illustId 作品ID
|
||||||
* @return 成功获取返回JsonObject, 失败返回null, <br/>
|
* @return 成功获取返回JsonObject, 失败返回null.
|
||||||
* Json示例: <br/>
|
|
||||||
* <pre>
|
|
||||||
* {
|
|
||||||
* "illustId": "79584670",
|
|
||||||
* "illustTitle": "このヤンキーはウブすぎる",
|
|
||||||
* "id": "79584670",
|
|
||||||
* "title": "このヤンキーはウブすぎる",
|
|
||||||
* "illustType": 1,
|
|
||||||
* "xRestrict": 0,
|
|
||||||
* "restrict": 0,
|
|
||||||
* "sl": 2,
|
|
||||||
* "url": "https://i.pximg.net/c/360x360_70/img-master/img/2020/02/19/00/38/23/79584670_p0_square1200.jpg",
|
|
||||||
* "description": "",
|
|
||||||
* "tags": [
|
|
||||||
* "漫画",
|
|
||||||
* "オリジナル",
|
|
||||||
* "創作",
|
|
||||||
* "創作男女",
|
|
||||||
* "コロさん、ポリさん此方です!",
|
|
||||||
* "恋の予感",
|
|
||||||
* "あまずっぺー",
|
|
||||||
* "交換日記",
|
|
||||||
* "続編希望!!",
|
|
||||||
* "オリジナル10000users入り"
|
|
||||||
* ],
|
|
||||||
* "userId": "4778293",
|
|
||||||
* "userName": "隈浪さえ",
|
|
||||||
* "width": 3288,
|
|
||||||
* "height": 4564,
|
|
||||||
* "pageCount": 4,
|
|
||||||
* "isBookmarkable": true,
|
|
||||||
* "bookmarkData": null,
|
|
||||||
* "alt": "#オリジナル このヤンキーはウブすぎる - 隈浪さえ的漫画",
|
|
||||||
* "isAdContainer": false,
|
|
||||||
* "profileImageUrl": "https://i.pximg.net/user-profile/img/2019/12/04/18/56/19/16639046_fea29ce38ea89b0cb2313b40b3a72f9a_50.jpg",
|
|
||||||
* "type": "illust"
|
|
||||||
* }
|
|
||||||
* </pre>
|
|
||||||
* @throws IOException 当请求发生异常, 或接口返回错误信息时抛出.
|
* @throws IOException 当请求发生异常, 或接口返回错误信息时抛出.
|
||||||
* @throws NoSuchElementException 当该作品不存在时抛出异常
|
* @throws NoSuchElementException 当该作品不存在时抛出异常
|
||||||
*/
|
*/
|
||||||
@ -555,7 +517,7 @@ public class PixivDownload {
|
|||||||
JsonObject responseObj = new Gson().fromJson(responseStr, JsonObject.class);
|
JsonObject responseObj = new Gson().fromJson(responseStr, JsonObject.class);
|
||||||
|
|
||||||
if(responseObj.get("error").getAsBoolean()) {
|
if(responseObj.get("error").getAsBoolean()) {
|
||||||
throw new IOException(responseObj.get("message").getAsString());
|
throw new HttpRequestException(response.getStatusLine(), responseStr);
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonArray illustsArray = responseObj.getAsJsonObject("body").getAsJsonArray("illusts");
|
JsonArray illustsArray = responseObj.getAsJsonObject("body").getAsJsonArray("illusts");
|
||||||
|
@ -15,8 +15,8 @@ import java.util.Objects;
|
|||||||
* @author LamGC
|
* @author LamGC
|
||||||
* @see PixivURL#PIXIV_SEARCH_CONTENT_URL
|
* @see PixivURL#PIXIV_SEARCH_CONTENT_URL
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("ALL")
|
@SuppressWarnings("unused")
|
||||||
public class PixivSearchBuilder {
|
public class PixivSearchLinkBuilder {
|
||||||
|
|
||||||
private final String content;
|
private final String content;
|
||||||
|
|
||||||
@ -26,8 +26,8 @@ public class PixivSearchBuilder {
|
|||||||
private SearchOrder searchOrder = SearchOrder.DATE_D;
|
private SearchOrder searchOrder = SearchOrder.DATE_D;
|
||||||
private SearchContentOption searchContentOption = SearchContentOption.ALL;
|
private SearchContentOption searchContentOption = SearchContentOption.ALL;
|
||||||
|
|
||||||
private HashSet<String> includeKeywords = new HashSet<>(0);
|
private final HashSet<String> includeKeywords = new HashSet<>(0);
|
||||||
private HashSet<String> excludeKeywords = new HashSet<>(0);
|
private final HashSet<String> excludeKeywords = new HashSet<>(0);
|
||||||
|
|
||||||
private int page = 1;
|
private int page = 1;
|
||||||
|
|
||||||
@ -42,7 +42,7 @@ public class PixivSearchBuilder {
|
|||||||
private Date startDate = null;
|
private Date startDate = null;
|
||||||
private Date endDate = null;
|
private Date endDate = null;
|
||||||
|
|
||||||
public PixivSearchBuilder(String searchContent) {
|
public PixivSearchLinkBuilder(String searchContent) {
|
||||||
this.content = Objects.requireNonNull(searchContent);
|
this.content = Objects.requireNonNull(searchContent);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -99,7 +99,7 @@ public class PixivSearchBuilder {
|
|||||||
public boolean equals(Object o) {
|
public boolean equals(Object o) {
|
||||||
if (this == o) return true;
|
if (this == o) return true;
|
||||||
if (o == null || getClass() != o.getClass()) return false;
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
PixivSearchBuilder that = (PixivSearchBuilder) o;
|
PixivSearchLinkBuilder that = (PixivSearchLinkBuilder) o;
|
||||||
return page == that.page &&
|
return page == that.page &&
|
||||||
wgt == that.wgt &&
|
wgt == that.wgt &&
|
||||||
hgt == that.hgt &&
|
hgt == that.hgt &&
|
||||||
@ -141,7 +141,7 @@ public class PixivSearchBuilder {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "PixivSearchBuilder{" +
|
return "PixivSearchLinkBuilder{" +
|
||||||
"content='" + content + '\'' +
|
"content='" + content + '\'' +
|
||||||
", searchArea=" + searchArea +
|
", searchArea=" + searchArea +
|
||||||
", searchMode=" + searchMode +
|
", searchMode=" + searchMode +
|
||||||
@ -161,19 +161,11 @@ public class PixivSearchBuilder {
|
|||||||
'}';
|
'}';
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder setSearchArea(SearchArea searchArea) {
|
public PixivSearchLinkBuilder setSearchArea(SearchArea searchArea) {
|
||||||
this.searchArea = Objects.requireNonNull(searchArea);
|
this.searchArea = Objects.requireNonNull(searchArea);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取搜索区域
|
|
||||||
* @return 返回搜索区域对象
|
|
||||||
*/
|
|
||||||
public SearchArea getSearchArea() {
|
|
||||||
return searchArea;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取搜索条件.
|
* 获取搜索条件.
|
||||||
* @return 搜索条件内容
|
* @return 搜索条件内容
|
||||||
@ -202,50 +194,50 @@ public class PixivSearchBuilder {
|
|||||||
return searchContent.toString();
|
return searchContent.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder setSearchMode(SearchMode searchMode) {
|
public PixivSearchLinkBuilder setSearchMode(SearchMode searchMode) {
|
||||||
this.searchMode = Objects.requireNonNull(searchMode);
|
this.searchMode = Objects.requireNonNull(searchMode);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder setSearchType(SearchType searchType) {
|
public PixivSearchLinkBuilder setSearchType(SearchType searchType) {
|
||||||
this.searchType = Objects.requireNonNull(searchType);
|
this.searchType = Objects.requireNonNull(searchType);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder setSearchOrder(SearchOrder searchOrder) {
|
public PixivSearchLinkBuilder setSearchOrder(SearchOrder searchOrder) {
|
||||||
this.searchOrder = Objects.requireNonNull(searchOrder);
|
this.searchOrder = Objects.requireNonNull(searchOrder);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder setSearchContentOption(SearchContentOption searchContentOption) {
|
public PixivSearchLinkBuilder setSearchContentOption(SearchContentOption searchContentOption) {
|
||||||
this.searchContentOption = Objects.requireNonNull(searchContentOption);
|
this.searchContentOption = Objects.requireNonNull(searchContentOption);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder setRatioOption(RatioOption ratioOption) {
|
public PixivSearchLinkBuilder setRatioOption(RatioOption ratioOption) {
|
||||||
this.ratioOption = Objects.requireNonNull(ratioOption);
|
this.ratioOption = Objects.requireNonNull(ratioOption);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder setDateRange(Date startDate, Date endDate) {
|
public PixivSearchLinkBuilder setDateRange(Date startDate, Date endDate) {
|
||||||
this.startDate = startDate;
|
this.startDate = startDate;
|
||||||
this.endDate = endDate;
|
this.endDate = endDate;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder setMaxSize(int width, int height) {
|
public PixivSearchLinkBuilder setMaxSize(int width, int height) {
|
||||||
this.wgt = width;
|
this.wgt = width;
|
||||||
this.hgt = height;
|
this.hgt = height;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder setMinSize(int width, int height) {
|
public PixivSearchLinkBuilder setMinSize(int width, int height) {
|
||||||
this.wlt = width;
|
this.wlt = width;
|
||||||
this.hlt = height;
|
this.hlt = height;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder setPage(int pageIndex) {
|
public PixivSearchLinkBuilder setPage(int pageIndex) {
|
||||||
if (pageIndex <= 0) {
|
if (pageIndex <= 0) {
|
||||||
throw new IllegalArgumentException("Invalid pageIndex: " + pageIndex);
|
throw new IllegalArgumentException("Invalid pageIndex: " + pageIndex);
|
||||||
}
|
}
|
||||||
@ -253,22 +245,22 @@ public class PixivSearchBuilder {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder addExcludeKeyword(String keyword) {
|
public PixivSearchLinkBuilder addExcludeKeyword(String keyword) {
|
||||||
excludeKeywords.add(keyword);
|
excludeKeywords.add(keyword);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder removeExcludeKeyword(String keyword) {
|
public PixivSearchLinkBuilder removeExcludeKeyword(String keyword) {
|
||||||
excludeKeywords.remove(keyword);
|
excludeKeywords.remove(keyword);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder addIncludeKeyword(String keyword) {
|
public PixivSearchLinkBuilder addIncludeKeyword(String keyword) {
|
||||||
includeKeywords.add(keyword);
|
includeKeywords.add(keyword);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PixivSearchBuilder removeIncludeKeyword(String keyword) {
|
public PixivSearchLinkBuilder removeIncludeKeyword(String keyword) {
|
||||||
includeKeywords.remove(keyword);
|
includeKeywords.remove(keyword);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
@ -10,55 +10,56 @@ import java.util.GregorianCalendar;
|
|||||||
* 目前已整理的一些Pixiv接口列表
|
* 目前已整理的一些Pixiv接口列表
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
public class PixivURL {
|
public final class PixivURL {
|
||||||
|
|
||||||
|
private PixivURL() {}
|
||||||
|
|
||||||
public static final String PIXIV_INDEX_URL = "https://www.pixiv.net";
|
public final static String PIXIV_INDEX_URL = "https://www.pixiv.net";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站预登陆url
|
* P站预登陆url
|
||||||
*/
|
*/
|
||||||
public static final String PIXIV_LOGIN_PAGE_URL = "https://accounts.pixiv.net/login?lang=zh&source=pc&view_type=page&ref=wwwtop_accounts_index";
|
public final static String PIXIV_LOGIN_PAGE_URL = "https://accounts.pixiv.net/login?lang=zh&source=pc&view_type=page&ref=wwwtop_accounts_index";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站登录请求url
|
* P站登录请求url
|
||||||
*/
|
*/
|
||||||
public static final String PIXIV_LOGIN_URL = "https://accounts.pixiv.net/api/login?lang=zh";
|
public final static String PIXIV_LOGIN_URL = "https://accounts.pixiv.net/api/login?lang=zh";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站搜索请求url
|
* P站搜索请求url
|
||||||
* @deprecated 该接口已被替换, 请使用{@link PixivSearchBuilder}构造搜索Url
|
* @deprecated 该接口已被替换, 请使用{@link PixivSearchLinkBuilder}构造搜索Url
|
||||||
* @see PixivSearchBuilder
|
* @see PixivSearchLinkBuilder
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
@Deprecated
|
||||||
private static final String PIXIV_SEARCH_URL = "https://www.pixiv.net/search.php";
|
private final static String PIXIV_SEARCH_URL = "https://www.pixiv.net/search.php";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站搜索用户url
|
* P站搜索用户url
|
||||||
* 需要替换的参数:
|
* 需要替换的参数:
|
||||||
* {nick} - 用户昵称、部分名称
|
* {nick} - 用户昵称、部分名称
|
||||||
* @deprecated 该接口已被替换, 请使用{@link PixivSearchBuilder}构造搜索Url
|
* @deprecated 该接口已被替换, 请使用{@link PixivSearchLinkBuilder}构造搜索Url
|
||||||
* @see PixivSearchBuilder
|
* @see PixivSearchLinkBuilder
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
@Deprecated
|
||||||
public static final String PIXIV_SEARCH_USER_URL = PIXIV_SEARCH_URL + "?s_mode=s_usr&nick={nick}";
|
public final static String PIXIV_SEARCH_USER_URL = PIXIV_SEARCH_URL + "?s_mode=s_usr&nick={nick}";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站搜索插画url
|
* P站搜索插画url
|
||||||
* 需要替换的参数:
|
* 需要替换的参数:
|
||||||
* {word} - 插画相关文本
|
* {word} - 插画相关文本
|
||||||
* @deprecated 该接口已被替换, 请使用{@link PixivSearchBuilder}构造搜索Url
|
* @deprecated 该接口已被替换, 请使用{@link PixivSearchLinkBuilder}构造搜索Url
|
||||||
* @see PixivSearchBuilder
|
* @see PixivSearchLinkBuilder
|
||||||
*/
|
*/
|
||||||
@Deprecated
|
@Deprecated
|
||||||
public static final String PIXIV_SEARCH_TAG_URL = PIXIV_SEARCH_URL + "?s_mode=s_tag&word={word}";
|
public final static String PIXIV_SEARCH_TAG_URL = PIXIV_SEARCH_URL + "?s_mode=s_tag&word={word}";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站插图下载链接获取url
|
* P站插图下载链接获取url
|
||||||
* 需要替换的文本:
|
* 需要替换的文本:
|
||||||
* {illustId} - 插画ID
|
* {illustId} - 插画ID
|
||||||
*/
|
*/
|
||||||
public static final String PIXIV_ILLUST_API_URL = "https://www.pixiv.net/ajax/illust/{illustId}/pages";
|
public final static String PIXIV_ILLUST_API_URL = "https://www.pixiv.net/ajax/illust/{illustId}/pages";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站用户插图列表获取API
|
* P站用户插图列表获取API
|
||||||
@ -67,42 +68,42 @@ public class PixivURL {
|
|||||||
* {userId} - 用户ID
|
* {userId} - 用户ID
|
||||||
*/
|
*/
|
||||||
//{"error":false,"message":"","body":{"illusts":{"74369837":null,"70990542":null,"70608653":null,"69755191":null,"69729450":null,"69729416":null,"69503608":null,"69288766":null,"69083882":null,"69051458":null,"68484200":null,"68216927":null,"68216866":null,"68192333":null,"67915106":null,"67914932":null,"67854803":null,"67854745":null,"67854670":null,"67787211":null,"67772199":null,"67770637":null,"67754861":null,"67754804":null,"67754726":null,"67740486":null,"67740480":null,"67740450":null,"67740434":null,"67726337":null,"67499196":null,"67499163":null,"67499145":null,"67499111":null,"67499085":null,"67499038":null,"67498987":null,"67473178":null,"66271465":null,"63682753":null,"63682697":null,"59385148":null,"59383265":null,"59383240":null,"59383227":null,"59383173":null},"manga":[],"novels":[],"mangaSeries":[],"novelSeries":[],"pickup":[],"bookmarkCount":{"public":{"illust":1,"novel":0},"private":{"illust":0,"novel":0}}}}
|
//{"error":false,"message":"","body":{"illusts":{"74369837":null,"70990542":null,"70608653":null,"69755191":null,"69729450":null,"69729416":null,"69503608":null,"69288766":null,"69083882":null,"69051458":null,"68484200":null,"68216927":null,"68216866":null,"68192333":null,"67915106":null,"67914932":null,"67854803":null,"67854745":null,"67854670":null,"67787211":null,"67772199":null,"67770637":null,"67754861":null,"67754804":null,"67754726":null,"67740486":null,"67740480":null,"67740450":null,"67740434":null,"67726337":null,"67499196":null,"67499163":null,"67499145":null,"67499111":null,"67499085":null,"67499038":null,"67498987":null,"67473178":null,"66271465":null,"63682753":null,"63682697":null,"59385148":null,"59383265":null,"59383240":null,"59383227":null,"59383173":null},"manga":[],"novels":[],"mangaSeries":[],"novelSeries":[],"pickup":[],"bookmarkCount":{"public":{"illust":1,"novel":0},"private":{"illust":0,"novel":0}}}}
|
||||||
public static final String PIXIV_USER_ILLUST_LIST_URL = "https://www.pixiv.net/ajax/user/{userId}/profile/all";
|
public final static String PIXIV_USER_ILLUST_LIST_URL = "https://www.pixiv.net/ajax/user/{userId}/profile/all";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 能够同时获取插图信息的用户插图列表获取API
|
* 能够同时获取插图信息的用户插图列表获取API
|
||||||
* 需要替换的文本:
|
* 需要替换的文本:
|
||||||
* {userId} - 用户ID
|
* {userId} - 用户ID
|
||||||
*/
|
*/
|
||||||
public static final String PIXIV_USER_TOP_ILLUST_LIST_URL = "https://www.pixiv.net/ajax/user/{userId}/profile/top";
|
public final static String PIXIV_USER_TOP_ILLUST_LIST_URL = "https://www.pixiv.net/ajax/user/{userId}/profile/top";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站单图详情页url
|
* P站单图详情页url
|
||||||
* 需要替换的文本:
|
* 需要替换的文本:
|
||||||
* {illustId} - 插画ID
|
* {illustId} - 插画ID
|
||||||
*/
|
*/
|
||||||
public static final String PIXIV_ILLUST_MEDIUM_URL = "https://www.pixiv.net/member_illust.php?mode=medium&illust_id={illustId}";
|
public final static String PIXIV_ILLUST_MEDIUM_URL = "https://www.pixiv.net/member_illust.php?mode=medium&illust_id={illustId}";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站多图详情页url
|
* P站多图详情页url
|
||||||
* 需要替换的文本:
|
* 需要替换的文本:
|
||||||
* {illustId} - 插画ID
|
* {illustId} - 插画ID
|
||||||
*/
|
*/
|
||||||
public static final String PIXIV_ILLUST_MANGA_URL = "https://www.pixiv.net/member_illust.php?mode=manga&illust_id={illustId}";
|
public final static String PIXIV_ILLUST_MANGA_URL = "https://www.pixiv.net/member_illust.php?mode=manga&illust_id={illustId}";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站用户页面url
|
* P站用户页面url
|
||||||
* 需要替换的文本:
|
* 需要替换的文本:
|
||||||
* {userId} - 用户ID
|
* {userId} - 用户ID
|
||||||
*/
|
*/
|
||||||
public static final String PIXIV_USER_URL = "https://www.pixiv.net/member.php?id={userId}";
|
public final static String PIXIV_USER_URL = "https://www.pixiv.net/member.php?id={userId}";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站插图信息获取API
|
* P站插图信息获取API
|
||||||
* 这个API能获取插图基本信息,但不能获取大小
|
* 这个API能获取插图基本信息,但不能获取大小
|
||||||
* 请使用{@link #getPixivIllustInfoAPI(int[])}获取URL
|
* 请使用{@link #getPixivIllustInfoAPI(int[])}获取URL
|
||||||
*/
|
*/
|
||||||
private static final String PIXIV_GET_ILLUST_INFO_URL = "https://www.pixiv.net/ajax/illust/recommend/illusts?";
|
private final static String PIXIV_GET_ILLUST_INFO_URL = "https://www.pixiv.net/ajax/illust/recommend/illusts?";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站获取用户所有插图ID的Api
|
* P站获取用户所有插图ID的Api
|
||||||
@ -110,7 +111,15 @@ public class PixivURL {
|
|||||||
* 需要替换的文本:
|
* 需要替换的文本:
|
||||||
* {userId} - 用户ID
|
* {userId} - 用户ID
|
||||||
*/
|
*/
|
||||||
public static final String PIXIV_GET_USER_ALL_ILLUST_ID_URL = "https://www.pixiv.net/ajax/user/{userId}/profile/all";
|
public final static String PIXIV_GET_USER_ALL_ILLUST_URL = "https://www.pixiv.net/ajax/user/{userId}/profile/all";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* P站获取用户推荐插画及用户基本数据
|
||||||
|
* 这个API能获得作者的部分(推荐)作品, 每个作品有详细数据, 还能获取作者主页信息(比如主页说明, 看板图)
|
||||||
|
* 需要替换的文本:
|
||||||
|
* {userId} - 用户ID
|
||||||
|
*/
|
||||||
|
public final static String PIXIV_GET_USER_TOP_ILLUST_URL = "https://www.pixiv.net/ajax/user/{userId}/profile/top";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* P站标签搜索URL
|
* P站标签搜索URL
|
||||||
@ -118,7 +127,7 @@ public class PixivURL {
|
|||||||
* 需要替换的文本:
|
* 需要替换的文本:
|
||||||
* {content} - 大致tag内容
|
* {content} - 大致tag内容
|
||||||
*/
|
*/
|
||||||
public static final String PIXIV_TAG_SEARCH_URL = "https://www.pixiv.net/ajax/search/tags/{content}";
|
public final static String PIXIV_TAG_SEARCH_URL = "https://www.pixiv.net/ajax/search/tags/{content}";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取动图下载链接和拼接数据.
|
* 获取动图下载链接和拼接数据.
|
||||||
@ -128,11 +137,17 @@ public class PixivURL {
|
|||||||
*/
|
*/
|
||||||
public final static String PIXIV_GET_UGOIRA_META_URL = "https://www.pixiv.net/ajax/illust/{illustId}/ugoira_meta";
|
public final static String PIXIV_GET_UGOIRA_META_URL = "https://www.pixiv.net/ajax/illust/{illustId}/ugoira_meta";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取自己帐号的部分数据(目前仅能获取: 关注数, 粉丝数和看板图)
|
||||||
|
* 需要登录.
|
||||||
|
*/
|
||||||
|
public final static String PIXIV_GET_USER_EXTRA_URL = "https://www.pixiv.net/ajax/user/extra";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 请求时带上需要退出的Cookies
|
* 请求时带上需要退出的Cookies
|
||||||
* 无论成功与否都会返回302重定向到{@linkplain #PIXIV_LOGIN_PAGE_URL 登录页面}
|
* 无论成功与否都会返回302重定向到{@linkplain #PIXIV_LOGIN_PAGE_URL 登录页面}
|
||||||
*/
|
*/
|
||||||
public static final String PIXIV_LOGOUT_URL = "https://www.pixiv.net/logout.php";
|
public final static String PIXIV_LOGOUT_URL = "https://www.pixiv.net/logout.php";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构造P站获取插图信息的Api Url
|
* 构造P站获取插图信息的Api Url
|
||||||
@ -279,7 +294,7 @@ public class PixivURL {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Pixiv搜索接口.<br/>
|
* Pixiv搜索接口.<br/>
|
||||||
* 要使用该链接请使用{@link PixivSearchBuilder}构造链接.<br/>
|
* 要使用该链接请使用{@link PixivSearchLinkBuilder}构造链接.<br/>
|
||||||
* 需要替换的参数: <br/>
|
* 需要替换的参数: <br/>
|
||||||
* content - 搜索内容
|
* content - 搜索内容
|
||||||
*/
|
*/
|
||||||
|
@ -7,6 +7,7 @@ import com.squareup.gifencoder.GifEncoder;
|
|||||||
import com.squareup.gifencoder.Image;
|
import com.squareup.gifencoder.Image;
|
||||||
import com.squareup.gifencoder.ImageOptions;
|
import com.squareup.gifencoder.ImageOptions;
|
||||||
import io.netty.handler.codec.http.HttpHeaderNames;
|
import io.netty.handler.codec.http.HttpHeaderNames;
|
||||||
|
import net.lamgc.cgj.exception.HttpRequestException;
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
import org.apache.http.client.HttpClient;
|
import org.apache.http.client.HttpClient;
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
@ -51,7 +52,7 @@ public final class PixivUgoiraBuilder {
|
|||||||
if(resultObject.get("error").getAsBoolean()) {
|
if(resultObject.get("error").getAsBoolean()) {
|
||||||
String message = resultObject.get("message").getAsString();
|
String message = resultObject.get("message").getAsString();
|
||||||
log.error("获取动图元数据失败!(接口报错: {})", message);
|
log.error("获取动图元数据失败!(接口报错: {})", message);
|
||||||
throw new IOException(message);
|
throw new HttpRequestException(response.getStatusLine(), bodyStr);
|
||||||
} else if(!resultObject.has("body")) {
|
} else if(!resultObject.has("body")) {
|
||||||
String message = "接口返回数据不存在body属性, 可能接口发生改变!";
|
String message = "接口返回数据不存在body属性, 可能接口发生改变!";
|
||||||
log.error(message);
|
log.error(message);
|
||||||
@ -181,7 +182,7 @@ public final class PixivUgoiraBuilder {
|
|||||||
if(resultObject.get("error").getAsBoolean()) {
|
if(resultObject.get("error").getAsBoolean()) {
|
||||||
String message = resultObject.get("message").getAsString();
|
String message = resultObject.get("message").getAsString();
|
||||||
log.error("接口返回错误: {}", message);
|
log.error("接口返回错误: {}", message);
|
||||||
throw new IOException(message);
|
throw new HttpRequestException(response.getStatusLine(), responseBody);
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonArray illustsArray = resultObject.getAsJsonObject("body").getAsJsonArray("illusts");
|
JsonArray illustsArray = resultObject.getAsJsonObject("body").getAsJsonArray("illusts");
|
||||||
|
@ -1,149 +0,0 @@
|
|||||||
package net.lamgc.cgj.proxy;
|
|
||||||
|
|
||||||
import com.github.monkeywie.proxyee.intercept.HttpProxyIntercept;
|
|
||||||
import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptInitializer;
|
|
||||||
import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptPipeline;
|
|
||||||
import com.github.monkeywie.proxyee.intercept.common.CertDownIntercept;
|
|
||||||
import com.github.monkeywie.proxyee.proxy.ProxyConfig;
|
|
||||||
import com.github.monkeywie.proxyee.server.HttpProxyServer;
|
|
||||||
import com.github.monkeywie.proxyee.server.HttpProxyServerConfig;
|
|
||||||
import io.netty.channel.Channel;
|
|
||||||
import io.netty.handler.codec.http.HttpHeaderNames;
|
|
||||||
import io.netty.handler.codec.http.HttpHeaders;
|
|
||||||
import io.netty.handler.codec.http.HttpRequest;
|
|
||||||
import io.netty.handler.codec.http.HttpResponse;
|
|
||||||
import org.apache.http.client.CookieStore;
|
|
||||||
import org.apache.http.impl.cookie.BasicClientCookie;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import java.net.HttpCookie;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 登录成功后提供CookieStore, 然后由程序自动登录Pixiv
|
|
||||||
* @author LamGC
|
|
||||||
*/
|
|
||||||
public class PixivAccessProxyServer {
|
|
||||||
|
|
||||||
private final Logger log = LoggerFactory.getLogger(PixivAccessProxyServer.class);
|
|
||||||
|
|
||||||
private final HttpProxyServer proxyServer;
|
|
||||||
|
|
||||||
private final CookieStore cookieStore;
|
|
||||||
|
|
||||||
public PixivAccessProxyServer(CookieStore cookieStore){
|
|
||||||
this(cookieStore, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public PixivAccessProxyServer(CookieStore cookieStore, ProxyConfig proxyConfig){
|
|
||||||
HttpProxyServerConfig config = new HttpProxyServerConfig();
|
|
||||||
this.cookieStore = cookieStore;
|
|
||||||
config.setHandleSsl(true);
|
|
||||||
this.proxyServer = new HttpProxyServer();
|
|
||||||
this.proxyServer
|
|
||||||
.serverConfig(config)
|
|
||||||
.proxyConfig(proxyConfig)
|
|
||||||
.proxyInterceptInitializer(new HttpProxyInterceptInitializer(){
|
|
||||||
@Override
|
|
||||||
public void init(HttpProxyInterceptPipeline pipeline) {
|
|
||||||
pipeline.addLast(new CertDownIntercept());
|
|
||||||
pipeline.addLast(new HttpProxyIntercept(){
|
|
||||||
|
|
||||||
private boolean match(HttpRequest request){
|
|
||||||
String host = request.headers().get(HttpHeaderNames.HOST);
|
|
||||||
return host.equalsIgnoreCase("pixiv.net") || host.contains(".pixiv.net");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void beforeRequest(Channel clientChannel, HttpRequest httpRequest, HttpProxyInterceptPipeline pipeline) throws Exception {
|
|
||||||
log.info("URL: " + httpRequest.headers().get(HttpHeaderNames.HOST) + httpRequest.uri());
|
|
||||||
if(!match(httpRequest)){
|
|
||||||
super.beforeRequest(clientChannel, httpRequest, pipeline);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
log.info("正在注入Cookies...");
|
|
||||||
HttpHeaders requestHeaders = httpRequest.headers();
|
|
||||||
if(requestHeaders.contains(HttpHeaderNames.COOKIE)){
|
|
||||||
log.info("原请求存在自带Cookies, 正在清除Cookies...");
|
|
||||||
log.debug("原Cookies: {}", requestHeaders.getAsString(HttpHeaderNames.COOKIE));
|
|
||||||
requestHeaders.remove(HttpHeaderNames.COOKIE);
|
|
||||||
}
|
|
||||||
StringBuilder cookieBuilder = new StringBuilder();
|
|
||||||
cookieStore.getCookies().forEach(cookie -> {
|
|
||||||
if(cookie.isExpired(new Date())){
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
cookieBuilder.append(cookie.getName()).append("=").append(cookie.getValue()).append("; ");
|
|
||||||
});
|
|
||||||
log.info("Cookies构造完成, 结果: " + cookieBuilder.toString());
|
|
||||||
requestHeaders.add(HttpHeaderNames.COOKIE, cookieBuilder.toString());
|
|
||||||
log.info("Cookies注入完成.");
|
|
||||||
|
|
||||||
super.beforeRequest(clientChannel, httpRequest, pipeline);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) throws Exception {
|
|
||||||
if(!match(pipeline.getHttpRequest())){
|
|
||||||
super.afterResponse(clientChannel, proxyChannel, httpResponse, pipeline);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
log.info("正在更新Response Cookie...(Header Name: " + HttpHeaderNames.SET_COOKIE + ")");
|
|
||||||
List<String> responseCookies = httpResponse.headers().getAll(HttpHeaderNames.SET_COOKIE);
|
|
||||||
responseCookies.forEach(value -> {
|
|
||||||
/*if(check(value)){
|
|
||||||
log.info("黑名单Cookie, 已忽略: " + value);
|
|
||||||
return;
|
|
||||||
}*/
|
|
||||||
log.info("Response Cookie: " + value);
|
|
||||||
BasicClientCookie cookie = parseRawCookie(value);
|
|
||||||
cookieStore.addCookie(cookie);
|
|
||||||
});
|
|
||||||
httpResponse.headers().remove(HttpHeaderNames.SET_COOKIE);
|
|
||||||
super.afterResponse(clientChannel, proxyChannel, httpResponse, pipeline);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected BasicClientCookie parseRawCookie(String rawCookie) {
|
|
||||||
List<HttpCookie> cookies = HttpCookie.parse(rawCookie);
|
|
||||||
if (cookies.size() < 1)
|
|
||||||
return null;
|
|
||||||
HttpCookie httpCookie = cookies.get(0);
|
|
||||||
BasicClientCookie cookie = new BasicClientCookie(httpCookie.getName(), httpCookie.getValue());
|
|
||||||
if (httpCookie.getMaxAge() >= 0) {
|
|
||||||
Date expiryDate = new Date(System.currentTimeMillis() + httpCookie.getMaxAge() * 1000);
|
|
||||||
cookie.setExpiryDate(expiryDate);
|
|
||||||
}
|
|
||||||
if (httpCookie.getDomain() != null)
|
|
||||||
cookie.setDomain(httpCookie.getDomain());
|
|
||||||
if (httpCookie.getPath() != null)
|
|
||||||
cookie.setPath(httpCookie.getPath());
|
|
||||||
if (httpCookie.getComment() != null)
|
|
||||||
cookie.setComment(httpCookie.getComment());
|
|
||||||
cookie.setSecure(httpCookie.getSecure());
|
|
||||||
return cookie;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public void start(int port){
|
|
||||||
this.proxyServer.start(port);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void close(){
|
|
||||||
this.proxyServer.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 导出CookieStore.
|
|
||||||
* 注意!该方法导出的CookieStore不适用于ApacheHttpClient, 如需使用则需要进行转换.
|
|
||||||
* @return CookieStore对象
|
|
||||||
*/
|
|
||||||
public CookieStore getCookieStore(){
|
|
||||||
return this.cookieStore;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
65
src/main/java/net/lamgc/cgj/util/Locker.java
Normal file
65
src/main/java/net/lamgc/cgj/util/Locker.java
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
package net.lamgc.cgj.util;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
public final class Locker<K> {
|
||||||
|
|
||||||
|
private final LockerMap<K> fromMap;
|
||||||
|
|
||||||
|
private final K key;
|
||||||
|
|
||||||
|
private final boolean autoDestroy;
|
||||||
|
|
||||||
|
private final AtomicInteger lockCount = new AtomicInteger(0);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造一个锁对象
|
||||||
|
* @param map 所属LockerMap
|
||||||
|
* @param key 所属Key
|
||||||
|
*/
|
||||||
|
Locker(LockerMap<K> map, K key, boolean autoDestroy) {
|
||||||
|
this.fromMap = map;
|
||||||
|
this.key = key;
|
||||||
|
this.autoDestroy = autoDestroy;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上锁
|
||||||
|
*/
|
||||||
|
public void lock() {
|
||||||
|
lockCount.incrementAndGet();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解锁
|
||||||
|
*/
|
||||||
|
public void unlock() {
|
||||||
|
int newValue = lockCount.decrementAndGet();
|
||||||
|
if(newValue <= 0 && autoDestroy) {
|
||||||
|
destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取锁对象所属Key
|
||||||
|
*/
|
||||||
|
public K getKey() {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 销毁锁对象
|
||||||
|
*/
|
||||||
|
public void destroy() {
|
||||||
|
fromMap.destroyLocker(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Locker@" + this.hashCode() + "{" +
|
||||||
|
"fromMap=" + fromMap +
|
||||||
|
", key=" + key +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
31
src/main/java/net/lamgc/cgj/util/LockerMap.java
Normal file
31
src/main/java/net/lamgc/cgj/util/LockerMap.java
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
package net.lamgc.cgj.util;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
public class LockerMap<K> {
|
||||||
|
|
||||||
|
private final HashMap<K, Locker<K>> lockerHashMap = new HashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建锁
|
||||||
|
* @param key Key
|
||||||
|
* @return 如果Key所属锁存在, 则返回对应锁, 否则返回新锁
|
||||||
|
*/
|
||||||
|
public Locker<K> createLocker(K key, boolean autoDestroy) {
|
||||||
|
if(lockerHashMap.containsKey(key)) {
|
||||||
|
return lockerHashMap.get(key);
|
||||||
|
}
|
||||||
|
Locker<K> newLocker = new Locker<>(this, key, autoDestroy);
|
||||||
|
lockerHashMap.put(key, newLocker);
|
||||||
|
return newLocker;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 销毁锁
|
||||||
|
* @param locker 锁对象
|
||||||
|
*/
|
||||||
|
public void destroyLocker(Locker<K> locker) {
|
||||||
|
lockerHashMap.remove(locker.getKey());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -2,6 +2,7 @@ package net.lamgc.cgj.util;
|
|||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -22,29 +23,53 @@ public class TimeLimitThreadPoolExecutor extends ThreadPoolExecutor {
|
|||||||
*/
|
*/
|
||||||
private final AtomicLong timeoutCheckInterval = new AtomicLong(100);
|
private final AtomicLong timeoutCheckInterval = new AtomicLong(100);
|
||||||
|
|
||||||
private final Map<Thread, AtomicLong> workerThreadMap = new Hashtable<>();
|
private final Map<Thread, MonitorInfo> workerThreadMap = new Hashtable<>();
|
||||||
|
|
||||||
private final Thread timeoutCheckThread = createTimeoutCheckThread();
|
private final Thread timeoutCheckThread = createTimeoutCheckThread();
|
||||||
|
|
||||||
public TimeLimitThreadPoolExecutor(long executeLimitTime, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
|
public TimeLimitThreadPoolExecutor(long executeLimitTime,
|
||||||
|
int corePoolSize,
|
||||||
|
int maximumPoolSize,
|
||||||
|
long keepAliveTime,
|
||||||
|
TimeUnit unit,
|
||||||
|
BlockingQueue<Runnable> workQueue) {
|
||||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
|
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
|
||||||
setInitialTime(executeLimitTime);
|
setInitialTime(executeLimitTime);
|
||||||
timeoutCheckThread.start();
|
timeoutCheckThread.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
public TimeLimitThreadPoolExecutor(long executeLimitTime, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
|
public TimeLimitThreadPoolExecutor(long executeLimitTime,
|
||||||
|
int corePoolSize,
|
||||||
|
int maximumPoolSize,
|
||||||
|
long keepAliveTime,
|
||||||
|
TimeUnit unit,
|
||||||
|
BlockingQueue<Runnable> workQueue,
|
||||||
|
ThreadFactory threadFactory) {
|
||||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
|
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
|
||||||
setInitialTime(executeLimitTime);
|
setInitialTime(executeLimitTime);
|
||||||
timeoutCheckThread.start();
|
timeoutCheckThread.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
public TimeLimitThreadPoolExecutor(long executeLimitTime, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
|
public TimeLimitThreadPoolExecutor(long executeLimitTime,
|
||||||
|
int corePoolSize,
|
||||||
|
int maximumPoolSize,
|
||||||
|
long keepAliveTime,
|
||||||
|
TimeUnit unit,
|
||||||
|
BlockingQueue<Runnable> workQueue,
|
||||||
|
RejectedExecutionHandler handler) {
|
||||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
|
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
|
||||||
setInitialTime(executeLimitTime);
|
setInitialTime(executeLimitTime);
|
||||||
timeoutCheckThread.start();
|
timeoutCheckThread.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
public TimeLimitThreadPoolExecutor(long executeLimitTime, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
|
public TimeLimitThreadPoolExecutor(long executeLimitTime,
|
||||||
|
int corePoolSize,
|
||||||
|
int maximumPoolSize,
|
||||||
|
long keepAliveTime,
|
||||||
|
TimeUnit unit,
|
||||||
|
BlockingQueue<Runnable> workQueue,
|
||||||
|
ThreadFactory threadFactory,
|
||||||
|
RejectedExecutionHandler handler) {
|
||||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
|
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
|
||||||
setInitialTime(executeLimitTime);
|
setInitialTime(executeLimitTime);
|
||||||
timeoutCheckThread.start();
|
timeoutCheckThread.start();
|
||||||
@ -107,14 +132,17 @@ public class TimeLimitThreadPoolExecutor extends ThreadPoolExecutor {
|
|||||||
while (true) {
|
while (true) {
|
||||||
try {
|
try {
|
||||||
long interval = this.timeoutCheckInterval.get();
|
long interval = this.timeoutCheckInterval.get();
|
||||||
|
//noinspection BusyWait 用于等待超时
|
||||||
Thread.sleep(interval);
|
Thread.sleep(interval);
|
||||||
|
|
||||||
// 检查是否存在超时的任务
|
// 检查是否存在超时的任务
|
||||||
workerThreadMap.forEach((thread, time) -> {
|
final long executeTimeLimit = this.executeTimeLimit.get();
|
||||||
long currentTime = time.getAndAdd(interval);
|
workerThreadMap.forEach((thread, info) -> {
|
||||||
if(currentTime > executeTimeLimit.get()) {
|
long currentTime = info.getTimeRemaining().getAndAdd(interval);
|
||||||
if(!thread.isInterrupted()) {
|
if(currentTime > executeTimeLimit) {
|
||||||
|
if(!info.getNotifyInterrupted().get() && !thread.isInterrupted()) {
|
||||||
thread.interrupt();
|
thread.interrupt();
|
||||||
|
info.getNotifyInterrupted().set(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -130,7 +158,7 @@ public class TimeLimitThreadPoolExecutor extends ThreadPoolExecutor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void beforeExecute(Thread t, Runnable r) {
|
protected void beforeExecute(Thread t, Runnable r) {
|
||||||
workerThreadMap.put(t, new AtomicLong());
|
workerThreadMap.put(t, new MonitorInfo());
|
||||||
super.beforeExecute(t, r);
|
super.beforeExecute(t, r);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -145,4 +173,20 @@ public class TimeLimitThreadPoolExecutor extends ThreadPoolExecutor {
|
|||||||
this.timeoutCheckThread.interrupt();
|
this.timeoutCheckThread.interrupt();
|
||||||
super.terminated();
|
super.terminated();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static class MonitorInfo {
|
||||||
|
|
||||||
|
private final AtomicLong timeRemaining = new AtomicLong();
|
||||||
|
|
||||||
|
private final AtomicBoolean notifyInterrupted = new AtomicBoolean(false);
|
||||||
|
|
||||||
|
public AtomicBoolean getNotifyInterrupted() {
|
||||||
|
return notifyInterrupted;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AtomicLong getTimeRemaining() {
|
||||||
|
return timeRemaining;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -49,7 +49,8 @@
|
|||||||
</Appenders>
|
</Appenders>
|
||||||
|
|
||||||
<Loggers>
|
<Loggers>
|
||||||
<Root level="TRACE">
|
<Logger level="INFO" name="org.apache.http"/>
|
||||||
|
<Root level="DEBUG">
|
||||||
<AppenderRef ref="STANDARD_STDOUT"/>
|
<AppenderRef ref="STANDARD_STDOUT"/>
|
||||||
<AppenderRef ref="STANDARD_STDERR"/>
|
<AppenderRef ref="STANDARD_STDERR"/>
|
||||||
<AppenderRef ref="rollingFile"/>
|
<AppenderRef ref="rollingFile"/>
|
||||||
|
@ -3,23 +3,23 @@ package net.lamgc.cgj.pixiv;
|
|||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class PixivSearchBuilderTest {
|
public class PixivSearchLinkBuilderTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void buildTest() {
|
public void buildTest() {
|
||||||
PixivSearchBuilder builder = new PixivSearchBuilder("hololive");
|
PixivSearchLinkBuilder builder = new PixivSearchLinkBuilder("hololive");
|
||||||
builder.addIncludeKeyword("35").addIncludeKeyword("okayu").addIncludeKeyword("百鬼あやめ");
|
builder.addIncludeKeyword("35").addIncludeKeyword("okayu").addIncludeKeyword("百鬼あやめ");
|
||||||
System.out.println(builder.buildURL());
|
System.out.println(builder.buildURL());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void equalsTest() {
|
public void equalsTest() {
|
||||||
Assert.assertEquals(new PixivSearchBuilder("风景"), new PixivSearchBuilder("风景"));
|
Assert.assertEquals(new PixivSearchLinkBuilder("风景"), new PixivSearchLinkBuilder("风景"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void hashCodeTest() {
|
public void hashCodeTest() {
|
||||||
Assert.assertEquals(new PixivSearchBuilder("风景").hashCode(), new PixivSearchBuilder("风景").hashCode());
|
Assert.assertEquals(new PixivSearchLinkBuilder("风景").hashCode(), new PixivSearchLinkBuilder("风景").hashCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
18
src/test/java/net/lamgc/cgj/util/LockerMapTest.java
Normal file
18
src/test/java/net/lamgc/cgj/util/LockerMapTest.java
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
package net.lamgc.cgj.util;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class LockerMapTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void createAndFinalizeTest() {
|
||||||
|
LockerMap<String> map = new LockerMap<>();
|
||||||
|
Locker<String> locker = map.createLocker("Test", true);
|
||||||
|
Assert.assertEquals(locker, map.createLocker("Test", true));
|
||||||
|
locker.lock();
|
||||||
|
locker.unlock();
|
||||||
|
System.gc();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -2,26 +2,37 @@ package net.lamgc.cgj.util;
|
|||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.util.concurrent.ArrayBlockingQueue;
|
import java.util.concurrent.ArrayBlockingQueue;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class TimeLimitThreadPoolExecutorTest {
|
public class TimeLimitThreadPoolExecutorTest {
|
||||||
|
|
||||||
|
private final static Logger log = LoggerFactory.getLogger(TimeLimitThreadPoolExecutorTest.class);
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void timeoutTest() throws InterruptedException {
|
public void timeoutTest() throws InterruptedException {
|
||||||
TimeLimitThreadPoolExecutor executor = new TimeLimitThreadPoolExecutor(1000, 1, 1, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(50));
|
TimeLimitThreadPoolExecutor executor = new TimeLimitThreadPoolExecutor(1000, 1, 1, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(50));
|
||||||
System.out.println(executor.isTerminated());
|
log.info("ThreadPoolExecutor.isTerminated: {}", executor.isTerminated());
|
||||||
System.out.println(executor.isShutdown());
|
log.info("ThreadPoolExecutor.isShutdown: {}", executor.isShutdown());
|
||||||
|
|
||||||
executor.setTimeoutCheckInterval(150);
|
executor.setTimeoutCheckInterval(150);
|
||||||
System.out.println("当前设定: ETL: " + executor.getExecuteTimeLimit() + "ms, TCI: " + executor.getTimeoutCheckInterval() + "ms");
|
log.info("当前设定: ExecuteTimeLimit: {}ms, CheckInterval: {}ms", executor.getExecuteTimeLimit(),
|
||||||
|
executor.getTimeoutCheckInterval());
|
||||||
executor.execute(() -> {
|
executor.execute(() -> {
|
||||||
try {
|
try {
|
||||||
Thread.sleep(5 * 1000);
|
Thread.sleep(5000);
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
System.out.println("线程 " + Thread.currentThread().getName() + " 被中断");
|
System.out.println("线程 " + Thread.currentThread().getName() + " 被中断");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Assert.fail("Multiple interrupts occurred");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
executor.shutdown();
|
executor.shutdown();
|
||||||
Assert.assertTrue(executor.awaitTermination(5 * 1000, TimeUnit.MILLISECONDS));
|
Assert.assertTrue(executor.awaitTermination(5 * 1000, TimeUnit.MILLISECONDS));
|
||||||
|
Reference in New Issue
Block a user