Compare commits

..

2 Commits

Author SHA1 Message Date
d274b7c402 Merge pull request #31 from LamGC/dependabot/maven/junit-junit-4.13.1
Bump junit from 4.12 to 4.13.1
2020-10-14 16:57:56 +08:00
0a4c26aded Bump junit from 4.12 to 4.13.1
Bumps [junit](https://github.com/junit-team/junit4) from 4.12 to 4.13.1.
- [Release notes](https://github.com/junit-team/junit4/releases)
- [Changelog](https://github.com/junit-team/junit4/blob/main/doc/ReleaseNotes4.12.md)
- [Commits](https://github.com/junit-team/junit4/compare/r4.12...r4.13.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-13 21:46:16 +00:00
17 changed files with 268 additions and 386 deletions

View File

@ -100,7 +100,7 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.12</version> <version>4.13.1</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -10,7 +10,9 @@ import net.lamgc.cgj.bot.boot.BotGlobal;
import net.lamgc.cgj.bot.framework.cli.ConsoleMain; import net.lamgc.cgj.bot.framework.cli.ConsoleMain;
import net.lamgc.cgj.bot.framework.coolq.SpringCQApplication; import net.lamgc.cgj.bot.framework.coolq.SpringCQApplication;
import net.lamgc.cgj.bot.framework.mirai.MiraiMain; import net.lamgc.cgj.bot.framework.mirai.MiraiMain;
import net.lamgc.cgj.pixiv.*; import net.lamgc.cgj.pixiv.PixivDownload;
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
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.ArgumentsRunner; import net.lamgc.utils.base.runner.ArgumentsRunner;
import net.lamgc.utils.base.runner.Command; import net.lamgc.utils.base.runner.Command;
@ -180,18 +182,18 @@ public class Main {
date = format.format(queryDate); date = format.format(queryDate);
log.info("查询时间: {}", date); log.info("查询时间: {}", date);
RankingMode rankingMode = RankingMode.MODE_DAILY; PixivURL.RankingMode rankingMode = PixivURL.RankingMode.MODE_DAILY;
RankingContentType contentType = null; PixivURL.RankingContentType contentType = null;
if(mode != null) { if(mode != null) {
try { try {
rankingMode = RankingMode.valueOf(mode); rankingMode = PixivURL.RankingMode.valueOf(mode);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
log.warn("不支持的RankingMode: {}", mode); log.warn("不支持的RankingMode: {}", mode);
} }
} }
if(content != null) { if(content != null) {
try { try {
contentType = RankingContentType.valueOf(content); contentType = PixivURL.RankingContentType.valueOf(content);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
log.warn("不支持的RankingContentType: {}", content); log.warn("不支持的RankingContentType: {}", content);
} }
@ -213,8 +215,7 @@ public class Main {
log.info("正在调用方法..."); log.info("正在调用方法...");
try { try {
pixivDownload.getRankingAsInputStream(contentType, rankingMode, queryDate, range, pixivDownload.getRankingAsInputStream(contentType, rankingMode, queryDate, range, PixivDownload.PageQuality.ORIGINAL, (rank, link, rankInfo, inputStream) -> {
PixivDownload.PageQuality.ORIGINAL, (rank, link, rankInfo, inputStream) -> {
try { try {
ZipEntry entry = new ZipEntry("Rank" + rank + "-" + link.substring(link.lastIndexOf("/") + 1)); ZipEntry entry = new ZipEntry("Rank" + rank + "-" + link.substring(link.lastIndexOf("/") + 1));
entry.setComment(rankInfo.toString()); entry.setComment(rankInfo.toString());
@ -300,39 +301,35 @@ public class Main {
JsonObject resultBody = jsonObject.getAsJsonObject("body"); JsonObject resultBody = jsonObject.getAsJsonObject("body");
for(PixivSearchAttribute attribute : PixivSearchAttribute.values()) { for(PixivSearchLinkBuilder.SearchArea searchArea : PixivSearchLinkBuilder.SearchArea.values()) {
for(String attrName : attribute.attributeNames) { if(!resultBody.has(searchArea.jsonKey) || resultBody.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data").size() == 0) {
if(!resultBody.has(attrName) || //log.info("返回数据不包含 {}", searchArea.jsonKey);
resultBody.getAsJsonObject(attrName).getAsJsonArray("data").size() == 0) { continue;
//log.info("返回数据不包含 {}", attrName); }
JsonArray illustsArray = resultBody
.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data");
log.info("已找到与 {} 相关插图信息({})", content, searchArea.name().toLowerCase());
int count = 1;
for (JsonElement jsonElement : illustsArray) {
JsonObject illustObj = jsonElement.getAsJsonObject();
if(!illustObj.has("illustId")) {
continue; continue;
} }
JsonArray illustsArray = resultBody int illustId = illustObj.get("illustId").getAsInt();
.getAsJsonObject(attrName).getAsJsonArray("data"); StringBuilder builder = new StringBuilder("[");
log.info("已找到与 {} 相关插图信息({})", content, attribute.name().toLowerCase()); illustObj.get("tags").getAsJsonArray().forEach(el -> builder.append(el.getAsString()).append(", "));
int count = 1; builder.replace(builder.length() - 2, builder.length(), "]");
for (JsonElement jsonElement : illustsArray) { log.info("{} ({} / {})\n\t作品id: {}, \n\t作者名(作者id): {} ({}), \n\t作品标题: {}, \n\t作品Tags: {}, \n\t作品链接: {}",
JsonObject illustObj = jsonElement.getAsJsonObject(); searchArea.name(),
if(!illustObj.has("illustId")) { count++,
continue; illustsArray.size(),
} illustId,
int illustId = illustObj.get("illustId").getAsInt(); illustObj.get("userName").getAsString(),
StringBuilder builder = new StringBuilder("["); illustObj.get("userId").getAsInt(),
illustObj.get("tags").getAsJsonArray().forEach(el -> builder.append(el.getAsString()).append(", ")); illustObj.get("illustTitle").getAsString(),
builder.replace(builder.length() - 2, builder.length(), "]"); builder,
log.info("{} ({} / {})\n\t作品id: {}, \n\t作者名(作者id): {} ({}), " + PixivURL.getPixivRefererLink(illustId)
"\n\t作品标题: {}, \n\t作品Tags: {}, \n\t作品链接: {}", );
attribute.name(),
count++,
illustsArray.size(),
illustId,
illustObj.get("userName").getAsString(),
illustObj.get("userId").getAsInt(),
illustObj.get("illustTitle").getAsString(),
builder,
PixivURL.getPixivRefererLink(illustId)
);
}
} }
} }
} }

View File

@ -9,8 +9,7 @@ import net.lamgc.cgj.bot.boot.BotGlobal;
import net.lamgc.cgj.bot.message.MessageSenderBuilder; import net.lamgc.cgj.bot.message.MessageSenderBuilder;
import net.lamgc.cgj.bot.message.MessageSource; import net.lamgc.cgj.bot.message.MessageSource;
import net.lamgc.cgj.pixiv.PixivDownload; import net.lamgc.cgj.pixiv.PixivDownload;
import net.lamgc.cgj.pixiv.RankingContentType; import net.lamgc.cgj.pixiv.PixivURL;
import net.lamgc.cgj.pixiv.RankingMode;
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;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -119,16 +118,16 @@ public class BotAdminCommandProcess {
return "排行榜范围选取错误!"; return "排行榜范围选取错误!";
} }
RankingContentType type; PixivURL.RankingContentType type;
RankingMode mode; PixivURL.RankingMode mode;
try { try {
type = RankingContentType.valueOf("TYPE_" + rankingContentType.toUpperCase()); type = PixivURL.RankingContentType.valueOf("TYPE_" + rankingContentType.toUpperCase());
} catch(IllegalArgumentException e) { } catch(IllegalArgumentException e) {
return "无效的排行榜类型参数!"; return "无效的排行榜类型参数!";
} }
try { try {
mode = RankingMode.valueOf("MODE_" + rankingMode.toUpperCase()); mode = PixivURL.RankingMode.valueOf("MODE_" + rankingMode.toUpperCase());
} catch(IllegalArgumentException e) { } catch(IllegalArgumentException e) {
return "无效的排行榜模式参数!"; return "无效的排行榜模式参数!";
} }
@ -226,13 +225,10 @@ public class BotAdminCommandProcess {
} catch(NoSuchElementException ignored) { } catch(NoSuchElementException ignored) {
} }
int rankingStart = setting.has(RANKING_SETTING_RANKING_START) ? int rankingStart = setting.has(RANKING_SETTING_RANKING_START) ? setting.get(RANKING_SETTING_RANKING_START).getAsInt() : 1;
setting.get(RANKING_SETTING_RANKING_START).getAsInt() : 1; int rankingEnd = setting.has(RANKING_SETTING_RANKING_END) ? setting.get(RANKING_SETTING_RANKING_END).getAsInt() : 150;
int rankingEnd = setting.has(RANKING_SETTING_RANKING_END) ? PixivURL.RankingMode rankingMode = PixivURL.RankingMode.MODE_DAILY;
setting.get(RANKING_SETTING_RANKING_END).getAsInt() : 150; PixivURL.RankingContentType rankingContentType = PixivURL.RankingContentType.TYPE_ILLUST;
RankingMode rankingMode = RankingMode.MODE_DAILY;
RankingContentType rankingContentType = RankingContentType.TYPE_ILLUST;
PixivDownload.PageQuality pageQuality = PixivDownload.PageQuality.REGULAR; PixivDownload.PageQuality pageQuality = PixivDownload.PageQuality.REGULAR;
if(rankingStart <= 0 || rankingStart > 500) { if(rankingStart <= 0 || rankingStart > 500) {
@ -250,7 +246,7 @@ public class BotAdminCommandProcess {
if(setting.has(RANKING_SETTING_RANKING_MODE)) { if(setting.has(RANKING_SETTING_RANKING_MODE)) {
String value = setting.get(RANKING_SETTING_RANKING_MODE).getAsString().trim().toUpperCase(); String value = setting.get(RANKING_SETTING_RANKING_MODE).getAsString().trim().toUpperCase();
try { try {
rankingMode = RankingMode.valueOf(value.startsWith("MODE_") ? value : "MODE_" + value); rankingMode = PixivURL.RankingMode.valueOf(value.startsWith("MODE_") ? value : "MODE_" + value);
} catch(IllegalArgumentException e) { } catch(IllegalArgumentException e) {
log.warn("群组ID [{}] - 无效的RankingMode设定值, 将重置为默认值: {}", id, value); log.warn("群组ID [{}] - 无效的RankingMode设定值, 将重置为默认值: {}", id, value);
} }
@ -258,7 +254,7 @@ public class BotAdminCommandProcess {
if(setting.has(RANKING_SETTING_RANKING_CONTENT_TYPE)) { if(setting.has(RANKING_SETTING_RANKING_CONTENT_TYPE)) {
String value = setting.get(RANKING_SETTING_RANKING_CONTENT_TYPE).getAsString().trim().toUpperCase(); String value = setting.get(RANKING_SETTING_RANKING_CONTENT_TYPE).getAsString().trim().toUpperCase();
try { try {
rankingContentType = RankingContentType.valueOf(value.startsWith("TYPE_") ? value : "TYPE_" + value); rankingContentType = PixivURL.RankingContentType.valueOf(value.startsWith("TYPE_") ? value : "TYPE_" + value);
} catch(IllegalArgumentException e) { } catch(IllegalArgumentException e) {
log.warn("群组ID [{}] - 无效的RankingContentType设定值: {}", id, value); log.warn("群组ID [{}] - 无效的RankingContentType设定值: {}", id, value);
} }
@ -297,10 +293,7 @@ public class BotAdminCommandProcess {
* @throws NoSuchElementException 当这个群号没有定时器的时候抛出异常 * @throws NoSuchElementException 当这个群号没有定时器的时候抛出异常
*/ */
@Command @Command
public static String removePushGroup( public static String removePushGroup(@Argument(name = "$fromGroup") long fromGroup, @Argument(name = "group", force = false) long id) {
@Argument(name = "$fromGroup") long fromGroup,
@Argument(name = "group", force = false) long id
) {
long group = id <= 0 ? fromGroup : id; long group = id <= 0 ? fromGroup : id;
RandomIntervalSendTimer.getTimerById(group).destroy(); RandomIntervalSendTimer.getTimerById(group).destroy();
pushInfoMap.remove(group); pushInfoMap.remove(group);
@ -331,8 +324,7 @@ public class BotAdminCommandProcess {
log.debug("{} - Report: {}", illustIdStr, report); log.debug("{} - Report: {}", illustIdStr, report);
String reason = report.get("reason").isJsonNull() ? "" : report.get("reason").getAsString(); String reason = report.get("reason").isJsonNull() ? "" : report.get("reason").getAsString();
msgBuilder.append(count).append(". 作品Id: ").append(illustIdStr) msgBuilder.append(count).append(". 作品Id: ").append(illustIdStr)
.append("(").append( .append("(").append(dateFormat.format(new Date(report.get("reportTime").getAsLong()))).append(")\n")
dateFormat.format(new Date(report.get("reportTime").getAsLong()))).append(")\n")
.append("报告者QQ").append(report.get("fromQQ").getAsLong()).append("\n") .append("报告者QQ").append(report.get("fromQQ").getAsLong()).append("\n")
.append("报告所在群:").append(report.get("fromGroup").getAsLong()).append("\n") .append("报告所在群:").append(report.get("fromGroup").getAsLong()).append("\n")
.append("报告原因:\n").append(reason).append("\n"); .append("报告原因:\n").append(reason).append("\n");

View File

@ -11,8 +11,11 @@ import net.lamgc.cgj.bot.cache.JsonRedisCacheStore;
import net.lamgc.cgj.bot.event.BufferedMessageSender; import net.lamgc.cgj.bot.event.BufferedMessageSender;
import net.lamgc.cgj.bot.sort.PreLoadDataAttribute; import net.lamgc.cgj.bot.sort.PreLoadDataAttribute;
import net.lamgc.cgj.bot.sort.PreLoadDataAttributeComparator; import net.lamgc.cgj.bot.sort.PreLoadDataAttributeComparator;
import net.lamgc.cgj.pixiv.*; 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.PixivSearchAttribute;
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
import net.lamgc.cgj.pixiv.PixivURL;
import net.lamgc.cgj.util.PixivUtils; import net.lamgc.cgj.util.PixivUtils;
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;
@ -143,8 +146,8 @@ public class BotCommandProcess {
@Argument(name = "$fromGroup") long fromGroup, @Argument(name = "$fromGroup") long fromGroup,
@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") RankingMode contentMode, @Argument(force = false, name = "mode", defaultValue = "DAILY") String contentMode,
@Argument(force = false, name = "type", defaultValue = "ALL") RankingContentType contentType, @Argument(force = false, name = "type", defaultValue = "ALL") String contentType,
@Argument(force = false, name = "p", defaultValue = "1") int pageIndex @Argument(force = false, name = "p", defaultValue = "1") int pageIndex
) throws InterruptedException { ) throws InterruptedException {
if(pageIndex <= 0) { if(pageIndex <= 0) {
@ -170,13 +173,33 @@ public class BotCommandProcess {
} }
} }
if(!contentType.isSupportedMode(contentMode)) { PixivURL.RankingMode mode;
try {
String rankingModeValue = contentMode.toUpperCase();
mode = PixivURL.RankingMode.valueOf(rankingModeValue.startsWith("MODE_") ?
rankingModeValue : "MODE_" + rankingModeValue);
} catch (IllegalArgumentException e) {
log.warn("无效的RankingMode值: {}", contentMode);
return "参数无效, 请查看帮助信息";
}
PixivURL.RankingContentType type;
try {
String contentTypeValue = contentType.toUpperCase();
type = PixivURL.RankingContentType.valueOf(
contentTypeValue.startsWith("TYPE_") ? contentTypeValue : "TYPE_" + contentTypeValue);
} catch (IllegalArgumentException e) {
log.warn("无效的RankingContentType值: {}", contentType);
return "参数无效, 请查看帮助信息";
}
if(!type.isSupportedMode(mode)) {
log.warn("RankingContentType不支持指定的RankingMode.(ContentType: {}, RankingMode: {})", log.warn("RankingContentType不支持指定的RankingMode.(ContentType: {}, RankingMode: {})",
contentType.name(), contentMode.name()); type.name(), mode.name());
return "不支持的内容类型或模式!"; return "不支持的内容类型或模式!";
} }
StringBuilder resultBuilder = new StringBuilder(contentMode.name() + " - 以下是 ") StringBuilder resultBuilder = new StringBuilder(mode.name() + " - 以下是 ")
.append(new SimpleDateFormat("yyyy-MM-dd").format(queryDate)).append(" 的Pixiv插画排名榜前十名\n"); .append(new SimpleDateFormat("yyyy-MM-dd").format(queryDate)).append(" 的Pixiv插画排名榜前十名\n");
try { try {
int index = 0; int index = 0;
@ -200,7 +223,7 @@ public class BotCommandProcess {
int startsIndex = itemLimit * pageIndex - (itemLimit - 1); int startsIndex = itemLimit * pageIndex - (itemLimit - 1);
List<JsonObject> rankingInfoList = CacheStoreCentral.getCentral() List<JsonObject> rankingInfoList = CacheStoreCentral.getCentral()
.getRankingInfoByCache(contentType, contentMode, queryDate, .getRankingInfoByCache(type, mode, queryDate,
Math.max(1, startsIndex), Math.max(0, itemLimit), false); Math.max(1, startsIndex), Math.max(0, itemLimit), false);
if(rankingInfoList.isEmpty()) { if(rankingInfoList.isEmpty()) {
return "无法查询排行榜,可能排行榜尚未更新。"; return "无法查询排行榜,可能排行榜尚未更新。";
@ -220,7 +243,7 @@ public class BotCommandProcess {
if (index <= imageLimit) { if (index <= imageLimit) {
resultBuilder resultBuilder
.append(CacheStoreCentral.getCentral() .append(CacheStoreCentral.getCentral()
.getImageById(fromGroup, illustId, PageQuality.REGULAR, 1)) .getImageById(fromGroup, illustId, PixivDownload.PageQuality.REGULAR, 1))
.append("\n"); .append("\n");
} }
} }
@ -250,20 +273,20 @@ public class BotCommandProcess {
@Argument(name = "$fromGroup") long fromGroup, @Argument(name = "$fromGroup") long fromGroup,
@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 = "ILLUST") String contentType) {
RankingMode mode; PixivURL.RankingMode mode;
try { try {
String rankingModeValue = contentMode.toUpperCase(); String rankingModeValue = contentMode.toUpperCase();
mode = RankingMode.valueOf(rankingModeValue.startsWith("MODE_") ? mode = PixivURL.RankingMode.valueOf(rankingModeValue.startsWith("MODE_") ?
rankingModeValue : "MODE_" + rankingModeValue); rankingModeValue : "MODE_" + rankingModeValue);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
log.warn("无效的RankingMode值: {}", contentMode); log.warn("无效的RankingMode值: {}", contentMode);
return "参数无效, 请查看帮助信息"; return "参数无效, 请查看帮助信息";
} }
RankingContentType type; PixivURL.RankingContentType type;
try { try {
String contentTypeValue = contentType.toUpperCase(); String contentTypeValue = contentType.toUpperCase();
type = RankingContentType.valueOf( type = PixivURL.RankingContentType.valueOf(
contentTypeValue.startsWith("TYPE_") ? contentTypeValue : "TYPE_" + contentTypeValue); contentTypeValue.startsWith("TYPE_") ? contentTypeValue : "TYPE_" + contentTypeValue);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
log.warn("无效的RankingContentType值: {}", contentType); log.warn("无效的RankingContentType值: {}", contentType);

View File

@ -4,8 +4,7 @@ import com.google.gson.JsonObject;
import net.lamgc.cgj.bot.cache.CacheStoreCentral; import net.lamgc.cgj.bot.cache.CacheStoreCentral;
import net.lamgc.cgj.bot.message.MessageSender; import net.lamgc.cgj.bot.message.MessageSender;
import net.lamgc.cgj.pixiv.PixivDownload; import net.lamgc.cgj.pixiv.PixivDownload;
import net.lamgc.cgj.pixiv.RankingContentType; import net.lamgc.cgj.pixiv.PixivURL;
import net.lamgc.cgj.pixiv.RankingMode;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -23,8 +22,8 @@ public class RandomRankingArtworksSender extends AutoSender {
private final long groupId; private final long groupId;
private final int rankingStart; private final int rankingStart;
private final int rankingStop; private final int rankingStop;
private final RankingMode mode; private final PixivURL.RankingMode mode;
private final RankingContentType contentType; private final PixivURL.RankingContentType contentType;
private final PixivDownload.PageQuality quality; private final PixivDownload.PageQuality quality;
/** /**
@ -41,8 +40,8 @@ public class RandomRankingArtworksSender extends AutoSender {
MessageSender messageSender, MessageSender messageSender,
int rankingStart, int rankingStart,
int rankingStop, int rankingStop,
RankingMode mode, PixivURL.RankingMode mode,
RankingContentType contentType, PixivURL.RankingContentType contentType,
PixivDownload.PageQuality quality) { PixivDownload.PageQuality quality) {
this(messageSender, 0, rankingStart, rankingStop, mode, contentType, quality); this(messageSender, 0, rankingStart, rankingStop, mode, contentType, quality);
} }
@ -63,8 +62,8 @@ public class RandomRankingArtworksSender extends AutoSender {
long groupId, long groupId,
int rankingStart, int rankingStart,
int rankingStop, int rankingStop,
RankingMode mode, PixivURL.RankingMode mode,
RankingContentType contentType, PixivURL.RankingContentType contentType,
PixivDownload.PageQuality quality) { PixivDownload.PageQuality quality) {
super(messageSender); super(messageSender);
this.groupId = groupId; this.groupId = groupId;
@ -74,8 +73,7 @@ public class RandomRankingArtworksSender extends AutoSender {
this.rankingStart = rankingStart > 0 ? rankingStart : 1; this.rankingStart = rankingStart > 0 ? rankingStart : 1;
this.rankingStop = rankingStop > 0 ? rankingStop : 150; this.rankingStop = rankingStop > 0 ? rankingStop : 150;
if(this.rankingStart > this.rankingStop) { if(this.rankingStart > this.rankingStop) {
throw new IndexOutOfBoundsException( throw new IndexOutOfBoundsException("rankingStart=" + this.rankingStart + ", rankingStop=" + this.rankingStop);
"rankingStart=" + this.rankingStart + ", rankingStop=" + this.rankingStop);
} }
this.quality = quality == null ? PixivDownload.PageQuality.REGULAR : quality; this.quality = quality == null ? PixivDownload.PageQuality.REGULAR : quality;
} }

View File

@ -2,8 +2,7 @@ package net.lamgc.cgj.bot;
import net.lamgc.cgj.bot.event.BotEventHandler; import net.lamgc.cgj.bot.event.BotEventHandler;
import net.lamgc.cgj.bot.event.VirtualLoadMessageEvent; import net.lamgc.cgj.bot.event.VirtualLoadMessageEvent;
import net.lamgc.cgj.pixiv.RankingContentType; import net.lamgc.cgj.pixiv.PixivURL;
import net.lamgc.cgj.pixiv.RankingMode;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -65,15 +64,14 @@ public class RankingUpdateTimer {
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()); String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
log.info("正在获取 {} 期排行榜数据...", calendar.getTime()); log.info("正在获取 {} 期排行榜数据...", calendar.getTime());
for (RankingMode rankingMode : RankingMode.values()) { for (PixivURL.RankingMode rankingMode : PixivURL.RankingMode.values()) {
for (RankingContentType contentType : RankingContentType.values()) { for (PixivURL.RankingContentType contentType : PixivURL.RankingContentType.values()) {
if(!contentType.isSupportedMode(rankingMode)) { if(!contentType.isSupportedMode(rankingMode)) {
log.debug("不支持的类型, 填空值跳过...(类型: {}.{})", rankingMode.name(), contentType.name()); log.debug("不支持的类型, 填空值跳过...(类型: {}.{})", rankingMode.name(), contentType.name());
} }
log.info("当前排行榜类型: {}.{}, 正在更新...", rankingMode.name(), contentType.name()); log.info("当前排行榜类型: {}.{}, 正在更新...", rankingMode.name(), contentType.name());
BotEventHandler.executeMessageEvent(new VirtualLoadMessageEvent(0,0, BotEventHandler.executeMessageEvent(new VirtualLoadMessageEvent(0,0,
".cgj ranking -type=" + contentType.name() + ".cgj ranking -type=" + contentType.name() + " -mode=" + rankingMode.name() + " -force -date " + dateStr));
" -mode=" + rankingMode.name() + " -force -date " + dateStr));
log.info("排行榜 {}.{} 负载指令已投递.", rankingMode.name(), contentType.name()); log.info("排行榜 {}.{} 负载指令已投递.", rankingMode.name(), contentType.name());
} }
} }

View File

@ -11,8 +11,7 @@ import net.lamgc.cgj.bot.boot.BotGlobal;
import net.lamgc.cgj.exception.HttpRequestException; import net.lamgc.cgj.exception.HttpRequestException;
import net.lamgc.cgj.pixiv.PixivDownload; import net.lamgc.cgj.pixiv.PixivDownload;
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder; import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
import net.lamgc.cgj.pixiv.RankingContentType; import net.lamgc.cgj.pixiv.PixivURL;
import net.lamgc.cgj.pixiv.RankingMode;
import net.lamgc.cgj.util.Locker; import net.lamgc.cgj.util.Locker;
import net.lamgc.cgj.util.LockerMap; import net.lamgc.cgj.util.LockerMap;
import net.lamgc.cgj.util.URLs; import net.lamgc.cgj.util.URLs;
@ -125,8 +124,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 {
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);
@ -356,9 +354,9 @@ public final class CacheStoreCentral {
* @return 成功返回有值List, 失败且无异常返回空 * @return 成功返回有值List, 失败且无异常返回空
* @throws IOException 获取异常时抛出 * @throws IOException 获取异常时抛出
*/ */
public List<JsonObject> getRankingInfoByCache(RankingContentType contentType, public List<JsonObject> getRankingInfoByCache(PixivURL.RankingContentType contentType,
RankingMode mode, PixivURL.RankingMode mode,
Date queryDate, int start, int range, boolean flushCache) Date queryDate, int start, int range, boolean flushCache)
throws IOException { throws IOException {
if(!contentType.isSupportedMode(mode)) { if(!contentType.isSupportedMode(mode)) {
log.warn("试图获取不支持的排行榜类型已拒绝.(ContentType: {}, RankingMode: {})", contentType.name(), mode.name()); log.warn("试图获取不支持的排行榜类型已拒绝.(ContentType: {}, RankingMode: {})", contentType.name(), mode.name());
@ -416,10 +414,9 @@ public final class CacheStoreCentral {
public JsonObject getSearchBody(PixivSearchLinkBuilder searchBuilder) throws IOException { public JsonObject getSearchBody(PixivSearchLinkBuilder searchBuilder) throws IOException {
log.debug("正在搜索作品, 条件: {}", searchBuilder.getSearchCondition()); log.debug("正在搜索作品, 条件: {}", searchBuilder.getSearchCondition());
String requestUrl = searchBuilder.buildURL(); String requestUrl = searchBuilder.buildURL();
String searchIdentify = String searchIdentify = requestUrl.substring(requestUrl.lastIndexOf("/", requestUrl.lastIndexOf("/") - 1) + 1);
requestUrl.substring(requestUrl.lastIndexOf("/", requestUrl.lastIndexOf("/") - 1) + 1); Locker<String> locker
Locker<String> locker = = buildSyncKey(searchIdentify);
buildSyncKey(searchIdentify);
log.debug("RequestUrl: {}", requestUrl); log.debug("RequestUrl: {}", requestUrl);
JsonObject resultBody = null; JsonObject resultBody = null;
if(!searchBodyCache.exists(searchIdentify)) { if(!searchBodyCache.exists(searchIdentify)) {

View File

@ -7,18 +7,17 @@ import net.lamgc.cgj.bot.BotAdminCommandProcess;
import net.lamgc.cgj.bot.BotCommandProcess; import net.lamgc.cgj.bot.BotCommandProcess;
import net.lamgc.cgj.bot.MessageEventExecutionDebugger; import net.lamgc.cgj.bot.MessageEventExecutionDebugger;
import net.lamgc.cgj.bot.SettingProperties; import net.lamgc.cgj.bot.SettingProperties;
import net.lamgc.cgj.bot.util.parser.DateParser; import net.lamgc.cgj.util.DateParser;
import net.lamgc.cgj.bot.util.parser.PagesQualityParser; import net.lamgc.cgj.util.PagesQualityParser;
import net.lamgc.cgj.bot.util.parser.RankingContentTypeParser;
import net.lamgc.cgj.bot.util.parser.RankingModeParser;
import net.lamgc.cgj.util.TimeLimitThreadPoolExecutor; import net.lamgc.cgj.util.TimeLimitThreadPoolExecutor;
import net.lamgc.utils.base.runner.ArgumentsRunner; import net.lamgc.utils.base.runner.ArgumentsRunner;
import net.lamgc.utils.base.runner.ArgumentsRunnerConfig; import net.lamgc.utils.base.runner.ArgumentsRunnerConfig;
import net.lamgc.utils.base.runner.exception.DeveloperRunnerException; import net.lamgc.utils.base.runner.exception.DeveloperRunnerException;
import net.lamgc.utils.base.runner.exception.NoSuchCommandException; import net.lamgc.utils.base.runner.exception.NoSuchCommandException;
import net.lamgc.utils.base.runner.exception.ParameterNoFoundException; import net.lamgc.utils.base.runner.exception.ParameterNoFoundException;
import net.lamgc.utils.event.EventObject;
import net.lamgc.utils.event.*; import net.lamgc.utils.event.*;
import net.lamgc.utils.event.EventObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -71,13 +70,7 @@ public class BotEventHandler implements EventHandler {
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( public void exceptionHandler(Thread executeThread, EventHandler handler, Method handlerMethod, EventObject event, Throwable cause) {
Thread executeThread,
EventHandler handler,
Method handlerMethod,
EventObject event,
Throwable cause
) {
log.error("EventExecutor@{} 发生未捕获异常:\n\t" + log.error("EventExecutor@{} 发生未捕获异常:\n\t" +
"Thread:{}\n\tEventHandler: {}\n\tHandlerMethod: {}\n\tEventObject: {}\n" + "Thread:{}\n\tEventHandler: {}\n\tHandlerMethod: {}\n\tEventObject: {}\n" +
"------------------ Stack Trace ------------------\n{}", "------------------ Stack Trace ------------------\n{}",
@ -110,11 +103,8 @@ public class BotEventHandler implements EventHandler {
ArgumentsRunnerConfig runnerConfig = new ArgumentsRunnerConfig(); ArgumentsRunnerConfig runnerConfig = new ArgumentsRunnerConfig();
runnerConfig.setUseDefaultValueInsteadOfException(true); runnerConfig.setUseDefaultValueInsteadOfException(true);
runnerConfig.setCommandIgnoreCase(true); runnerConfig.setCommandIgnoreCase(true);
runnerConfig.addStringParameterParser(new DateParser(new SimpleDateFormat("yyyy-MM-dd"))); runnerConfig.addStringParameterParser(new DateParser(new SimpleDateFormat("yyyy-MM-dd")));
runnerConfig.addStringParameterParser(new PagesQualityParser()); runnerConfig.addStringParameterParser(new PagesQualityParser());
runnerConfig.addStringParameterParser(new RankingModeParser());
runnerConfig.addStringParameterParser(new RankingContentTypeParser());
processRunner = new ArgumentsRunner(BotCommandProcess.class, runnerConfig); processRunner = new ArgumentsRunner(BotCommandProcess.class, runnerConfig);
adminRunner = new ArgumentsRunner(BotAdminCommandProcess.class, runnerConfig); adminRunner = new ArgumentsRunner(BotAdminCommandProcess.class, runnerConfig);
@ -147,8 +137,7 @@ public class BotEventHandler implements EventHandler {
if(!event.getMessage().startsWith(ADMIN_COMMAND_PREFIX) && if(!event.getMessage().startsWith(ADMIN_COMMAND_PREFIX) &&
!Strings.isNullOrEmpty(debuggerName)) { !Strings.isNullOrEmpty(debuggerName)) {
try { try {
MessageEventExecutionDebugger debugger = MessageEventExecutionDebugger debugger = MessageEventExecutionDebugger.valueOf(debuggerName.toUpperCase());
MessageEventExecutionDebugger.valueOf(debuggerName.toUpperCase());
debugger.debugger.accept(executor, event, SettingProperties.getProperties(SettingProperties.GLOBAL), debugger.debugger.accept(executor, event, SettingProperties.getProperties(SettingProperties.GLOBAL),
MessageEventExecutionDebugger.getDebuggerLogger(debugger)); MessageEventExecutionDebugger.getDebuggerLogger(debugger));
} catch(IllegalArgumentException e) { } catch(IllegalArgumentException e) {
@ -165,9 +154,6 @@ public class BotEventHandler implements EventHandler {
} }
} }
private final static Pattern MESSAGE_PATTERN =
Pattern.compile("/\\s*(\".+?\"|[^:\\s])+((\\s*:\\s*(\".+?\"|[^\\s])+)|)|(\".+?\"|[^\"\\s])+");
/** /**
* 以事件形式处理消息事件 * 以事件形式处理消息事件
* @param event 消息事件对象 * @param event 消息事件对象
@ -180,7 +166,8 @@ public class BotEventHandler implements EventHandler {
return; return;
} }
Matcher matcher = MESSAGE_PATTERN.matcher(Strings.nullToEmpty(msg)); Pattern pattern = Pattern.compile("/\\s*(\".+?\"|[^:\\s])+((\\s*:\\s*(\".+?\"|[^\\s])+)|)|(\".+?\"|[^\"\\s])+");
Matcher matcher = pattern.matcher(Strings.nullToEmpty(msg));
List<String> argsList = new ArrayList<>(); List<String> argsList = new ArrayList<>();
while (matcher.find()) { while (matcher.find()) {
String arg = matcher.group(); String arg = matcher.group();
@ -210,7 +197,6 @@ public class BotEventHandler implements EventHandler {
args = Arrays.copyOf(args, args.length + 4); args = Arrays.copyOf(args, args.length + 4);
argsList.toArray(args); argsList.toArray(args);
String[] runnerArguments = args.length <= 1 ? new String[0] : Arrays.copyOfRange(args, 1, args.length);
log.info("正在处理命令..."); log.info("正在处理命令...");
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
Object result; Object result;
@ -220,10 +206,10 @@ public class BotEventHandler implements EventHandler {
.equals(SettingProperties.getProperty(0, "admin.adminId"))) { .equals(SettingProperties.getProperty(0, "admin.adminId"))) {
result = "你没有执行该命令的权限!"; result = "你没有执行该命令的权限!";
} else { } else {
result = adminRunner.run(runnerArguments); result = adminRunner.run(args.length <= 1 ? new String[0] : Arrays.copyOfRange(args, 1, args.length));
} }
} else { } else {
result = processRunner.run(runnerArguments); result = processRunner.run(args.length <= 1 ? new String[0] : Arrays.copyOfRange(args, 1, args.length));
} }
} catch(NoSuchCommandException e) { } catch(NoSuchCommandException e) {
result = "没有这个命令!请使用“.cgj”查看帮助说明"; result = "没有这个命令!请使用“.cgj”查看帮助说明";
@ -260,8 +246,7 @@ public class BotEventHandler implements EventHandler {
long totalTime = System.currentTimeMillis() - time; long totalTime = System.currentTimeMillis() - time;
log.info("命令反馈完成.(事件耗时: {}ms, P: {}%({}ms), R: {}%({}ms))", totalTime, log.info("命令反馈完成.(事件耗时: {}ms, P: {}%({}ms), R: {}%({}ms))", totalTime,
String.format("%.3f", ((double) processTime / (double)totalTime) * 100F), processTime, String.format("%.3f", ((double) processTime / (double)totalTime) * 100F), processTime,
String.format("%.3f", ((double) (totalTime - processTime) / (double)totalTime) * 100F), String.format("%.3f", ((double) (totalTime - processTime) / (double)totalTime) * 100F), totalTime - processTime);
totalTime - processTime);
} }
/** /**

View File

@ -1,29 +0,0 @@
package net.lamgc.cgj.bot.util.parser;
import net.lamgc.cgj.pixiv.RankingContentType;
import net.lamgc.utils.base.runner.StringParameterParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RankingContentTypeParser implements StringParameterParser<RankingContentType> {
private final static Logger log = LoggerFactory.getLogger(RankingContentTypeParser.class);
@Override
public RankingContentType parse(String strValue) {
try {
if(strValue.toUpperCase().startsWith("TYPE_")) {
return RankingContentType.valueOf(strValue.toUpperCase());
}
return RankingContentType.valueOf("TYPE_" + strValue.toUpperCase());
} catch(IllegalArgumentException e) {
log.warn("无效的RankingContentType值: {}", strValue);
throw e;
}
}
@Override
public RankingContentType defaultValue() {
return RankingContentType.TYPE_ALL;
}
}

View File

@ -1,29 +0,0 @@
package net.lamgc.cgj.bot.util.parser;
import net.lamgc.cgj.pixiv.RankingMode;
import net.lamgc.utils.base.runner.StringParameterParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RankingModeParser implements StringParameterParser<RankingMode> {
private final static Logger log = LoggerFactory.getLogger(RankingModeParser.class);
@Override
public RankingMode parse(String strValue) {
try {
if(strValue.toUpperCase().startsWith("MODE_")) {
return RankingMode.valueOf(strValue.toUpperCase());
}
return RankingMode.valueOf("MODE_" + strValue.toUpperCase());
} catch(IllegalArgumentException e) {
log.warn("无效的RankingMode值: {}", strValue);
throw e;
}
}
@Override
public RankingMode defaultValue() {
return RankingMode.MODE_DAILY;
}
}

View File

@ -56,10 +56,10 @@ public class PixivDownload {
this.cookieStore = cookieStore; this.cookieStore = cookieStore;
HttpClientBuilder builder = HttpClientBuilder.create(); HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultCookieStore(cookieStore); builder.setDefaultCookieStore(cookieStore);
// UA: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36
ArrayList<Header> defaultHeaders = new ArrayList<>(2); ArrayList<Header> defaultHeaders = new ArrayList<>(2);
defaultHeaders.add(new BasicHeader("User-Agent", defaultHeaders.add(new BasicHeader("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"));
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"));
builder.setDefaultHeaders(defaultHeaders); builder.setDefaultHeaders(defaultHeaders);
builder.setProxy(proxy); builder.setProxy(proxy);
httpClient = builder.build(); httpClient = builder.build();
@ -84,8 +84,7 @@ public class PixivDownload {
Document document; Document document;
ArrayList<String> linkList = new ArrayList<>(); ArrayList<String> linkList = new ArrayList<>();
do { do {
request = new HttpGet(PixivURL.PIXIV_USER_COLLECTION_PAGE request = new HttpGet(PixivURL.PIXIV_USER_COLLECTION_PAGE.replace("{pageIndex}", Integer.toString(++pageIndex)));
.replace("{pageIndex}", Integer.toString(++pageIndex)));
setCookieInRequest(request, cookieStore); setCookieInRequest(request, cookieStore);
log.debug("Request Link: " + request.getURI().toString()); log.debug("Request Link: " + request.getURI().toString());
HttpResponse response = httpClient.execute(request); HttpResponse response = httpClient.execute(request);
@ -100,13 +99,10 @@ public class PixivDownload {
Gson gson = new Gson(); Gson gson = new Gson();
for (String href : hrefList) { for (String href : hrefList) {
HttpGet linkApiRequest = createHttpGetRequest(PixivURL.PIXIV_ILLUST_API_URL HttpGet linkApiRequest = createHttpGetRequest(PixivURL.PIXIV_ILLUST_API_URL.replace("{illustId}", href.substring(href.lastIndexOf("/") + 1)));
.replace("{illustId}", href.substring(href.lastIndexOf("/") + 1)));
log.debug(linkApiRequest.getURI().toString()); log.debug(linkApiRequest.getURI().toString());
HttpResponse httpResponse = httpClient.execute(linkApiRequest); HttpResponse httpResponse = httpClient.execute(linkApiRequest);
JsonObject linkResult = JsonObject linkResult = gson.fromJson(EntityUtils.toString(httpResponse.getEntity()), JsonObject.class);
gson.fromJson(EntityUtils.toString(httpResponse.getEntity()), JsonObject.class);
if(linkResult.get("error").getAsBoolean()) { if(linkResult.get("error").getAsBoolean()) {
log.error("接口返回错误信息: {}", linkResult.get("message").getAsString()); log.error("接口返回错误信息: {}", linkResult.get("message").getAsString());
continue; continue;
@ -115,10 +111,7 @@ public class PixivDownload {
JsonArray linkArray = linkResult.get("body").getAsJsonArray(); JsonArray linkArray = linkResult.get("body").getAsJsonArray();
for (int i = 0; i < linkArray.size(); i++) { for (int i = 0; i < linkArray.size(); i++) {
JsonObject linkObject = linkArray.get(i).getAsJsonObject().get("urls").getAsJsonObject(); JsonObject linkObject = linkArray.get(i).getAsJsonObject().get("urls").getAsJsonObject();
linkList.add( linkList.add(linkObject.get((quality == null ? PageQuality.ORIGINAL : quality).toString().toLowerCase()).getAsString());
linkObject.get((quality == null ? PageQuality.ORIGINAL : quality).toString().toLowerCase())
.getAsString()
);
} }
} }
} while(!document.select(".pager-container>.next").isEmpty()); } while(!document.select(".pager-container>.next").isEmpty());
@ -160,8 +153,7 @@ public class PixivDownload {
Document document = Jsoup.parse(EntityUtils.toString(response.getEntity())); Document document = Jsoup.parse(EntityUtils.toString(response.getEntity()));
HttpClient imageClient = HttpClientBuilder.create().build(); HttpClient imageClient = HttpClientBuilder.create().build();
Elements elements = document Elements elements = document.select(".gtm-illust-recommend-zone>.image-item>.gtm-illust-recommend-thumbnail-link");
.select(".gtm-illust-recommend-zone>.image-item>.gtm-illust-recommend-thumbnail-link");
for(int illustIndex = 0; illustIndex < elements.size(); illustIndex++){ for(int illustIndex = 0; illustIndex < elements.size(); illustIndex++){
String href = elements.get(illustIndex).attr("href"); String href = elements.get(illustIndex).attr("href");
int illustId = Integer.parseInt(href.substring(href.lastIndexOf("/") + 1)); int illustId = Integer.parseInt(href.substring(href.lastIndexOf("/") + 1));
@ -203,14 +195,8 @@ public class PixivDownload {
* @param fn 回调函数 * @param fn 回调函数
* @throws IOException 当请求发生异常时抛出 * @throws IOException 当请求发生异常时抛出
*/ */
public void getRankingAsInputStream( public void getRankingAsInputStream(PixivURL.RankingContentType contentType, PixivURL.RankingMode mode,
RankingContentType contentType, Date time, int range, PageQuality quality, RankingDownloadFunction fn) throws IOException {
RankingMode mode,
Date time,
int range,
PageQuality quality,
RankingDownloadFunction fn
) throws IOException {
getRankingAsInputStream(contentType, mode, time, 1, range, quality, fn); getRankingAsInputStream(contentType, mode, time, 1, range, quality, fn);
} }
@ -225,23 +211,15 @@ public class PixivDownload {
* @param fn 回调函数 * @param fn 回调函数
* @throws IOException 当请求发生异常时抛出 * @throws IOException 当请求发生异常时抛出
*/ */
public void getRankingAsInputStream( public void getRankingAsInputStream(PixivURL.RankingContentType contentType, PixivURL.RankingMode mode,
RankingContentType contentType, Date time, int rankStart, int range, PageQuality quality, RankingDownloadFunction fn) throws IOException {
RankingMode mode,
Date time,
int rankStart,
int range,
PageQuality quality,
RankingDownloadFunction fn
) throws IOException {
getRanking(contentType, mode, time, rankStart, range).forEach(rankInfo -> { getRanking(contentType, mode, time, rankStart, range).forEach(rankInfo -> {
int rank = rankInfo.get("rank").getAsInt(); int rank = rankInfo.get("rank").getAsInt();
int illustId = rankInfo.get("illust_id").getAsInt(); int illustId = rankInfo.get("illust_id").getAsInt();
int authorId = rankInfo.get("user_id").getAsInt(); int authorId = rankInfo.get("user_id").getAsInt();
String authorName = rankInfo.get("user_name").getAsString(); String authorName = rankInfo.get("user_name").getAsString();
String title = rankInfo.get("title").getAsString(); String title = rankInfo.get("title").getAsString();
log.trace("当前到第 {}/{} 名(总共 {} 名), IllustID: {}, Author: ({}) {}, Title: {}", log.trace("当前到第 {}/{} 名(总共 {} 名), IllustID: {}, Author: ({}) {}, Title: {}", rank, rankStart + range - 1, range, illustId, authorId, authorName, title);
rank, rankStart + range - 1, range, illustId, authorId, authorName, title);
log.trace("正在获取PagesLink..."); log.trace("正在获取PagesLink...");
List<String> linkList; List<String> linkList;
try { try {
@ -258,11 +236,7 @@ public class PixivDownload {
for (int pageIndex = 0; pageIndex < linkList.size(); pageIndex++) { for (int pageIndex = 0; pageIndex < linkList.size(); pageIndex++) {
String downloadLink = linkList.get(pageIndex); String downloadLink = linkList.get(pageIndex);
log.trace("当前Page: {}/{}", pageIndex + 1, linkList.size()); log.trace("当前Page: {}/{}", pageIndex + 1, linkList.size());
try(InputStream imageInputStream = try(InputStream imageInputStream = new BufferedInputStream(getImageAsInputStream(HttpClientBuilder.create().build(), downloadLink), 256 * 1024)) {
new BufferedInputStream(
getImageAsInputStream(HttpClientBuilder.create().build(), downloadLink),
256 * 1024)
) {
fn.download(rank, downloadLink, rankInfo.deepCopy(), imageInputStream); fn.download(rank, downloadLink, rankInfo.deepCopy(), imageInputStream);
} catch(IOException e) { } catch(IOException e) {
log.error("下载插画时发生异常", e); log.error("下载插画时发生异常", e);
@ -282,24 +256,22 @@ public class PixivDownload {
* @param rankStart 开始排名, 从1开始 * @param rankStart 开始排名, 从1开始
* @param range 取范围 * @param range 取范围
* @return 成功返回有值List, 失败且无异常返回空 * @return 成功返回有值List, 失败且无异常返回空
* @throws IllegalArgumentException 当{@linkplain net.lamgc.cgj.pixiv.RankingContentType RankingContentType} * @throws IllegalArgumentException 当{@linkplain net.lamgc.cgj.pixiv.PixivURL.RankingContentType RankingContentType}
* 与{@linkplain net.lamgc.cgj.pixiv.RankingMode RankingMode}互不兼容时抛出 * 与{@linkplain net.lamgc.cgj.pixiv.PixivURL.RankingMode RankingMode}互不兼容时抛出
* @throws IndexOutOfBoundsException 当排行榜选取范围超出排行榜范围时抛出(排行榜范围为 1 ~ 500 名) * @throws IndexOutOfBoundsException 当排行榜选取范围超出排行榜范围时抛出(排行榜范围为 1 ~ 500 名)
* @throws IOException 当Http请求发生异常时抛出, 或Http请求响应码非200时抛出 * @throws IOException 当Http请求发生异常时抛出, 或Http请求响应码非200时抛出
*/ */
public List<JsonObject> getRanking(RankingContentType contentType, RankingMode mode, public List<JsonObject> getRanking(PixivURL.RankingContentType contentType, PixivURL.RankingMode mode,
Date time, int rankStart, int range) throws IOException { Date time, int rankStart, int range) throws IOException {
Objects.requireNonNull(time); Objects.requireNonNull(time);
if(!Objects.requireNonNull(contentType).isSupportedMode(Objects.requireNonNull(mode))) { if(!Objects.requireNonNull(contentType).isSupportedMode(Objects.requireNonNull(mode))) {
throw new IllegalArgumentException("ContentType不支持指定的RankingMode: ContentType: " throw new IllegalArgumentException("ContentType不支持指定的RankingMode: ContentType: " + contentType.name() + ", Mode: " + mode.name());
+ contentType.name() + ", Mode: " + mode.name());
} else if(rankStart <= 0) { } else if(rankStart <= 0) {
throw new IndexOutOfBoundsException("rankStart cannot be less than or equal to zero: " + rankStart); throw new IndexOutOfBoundsException("rankStart cannot be less than or equal to zero: " + rankStart);
} else if(range <= 0) { } else if(range <= 0) {
throw new IndexOutOfBoundsException("range cannot be less than or equal to zero:" + range); throw new IndexOutOfBoundsException("range cannot be less than or equal to zero:" + range);
} else if(rankStart + range - 1 > 500) { } else if(rankStart + range - 1 > 500) {
throw new IndexOutOfBoundsException("排名选取范围超出了排行榜范围: rankStart=" throw new IndexOutOfBoundsException("排名选取范围超出了排行榜范围: rankStart=" + rankStart + ", range=" + range + ", length:" + (rankStart + range - 1));
+ rankStart + ", range=" + range + ", length:" + (rankStart + range - 1));
} }
int startPages = (int) Math.max(1, Math.floor(rankStart / 50F)); int startPages = (int) Math.max(1, Math.floor(rankStart / 50F));
@ -322,8 +294,7 @@ public class PixivDownload {
JsonObject resultObject = gson.fromJson(responseBody, JsonObject.class); JsonObject resultObject = gson.fromJson(responseBody, JsonObject.class);
canNext = resultObject.get("next").getAsJsonPrimitive().isNumber(); canNext = resultObject.get("next").getAsJsonPrimitive().isNumber();
JsonArray resultArray = resultObject.getAsJsonArray("contents"); JsonArray resultArray = resultObject.getAsJsonArray("contents");
for (int resultIndex = startIndex; for (int resultIndex = startIndex; resultIndex < resultArray.size() && count < range; resultIndex++, count++) {
resultIndex < resultArray.size() && count < range; resultIndex++, count++) {
results.add(resultArray.get(resultIndex).getAsJsonObject()); results.add(resultArray.get(resultIndex).getAsJsonObject());
} }
@ -383,14 +354,8 @@ public class PixivDownload {
* @return 返回该illust所有Page的下载链接 * @return 返回该illust所有Page的下载链接
* @throws IOException 当HttpClient在请求时发生异常, 或接口报错时抛出, 注意{@link IOException#getMessage()} * @throws IOException 当HttpClient在请求时发生异常, 或接口报错时抛出, 注意{@link IOException#getMessage()}
*/ */
public static List<String> getIllustAllPageDownload( public static List<String> getIllustAllPageDownload(HttpClient httpClient, CookieStore cookieStore, int illustId, PageQuality quality) throws IOException {
HttpClient httpClient, HttpGet linkApiRequest = new HttpGet(PixivURL.PIXIV_ILLUST_API_URL.replace("{illustId}", Integer.toString(illustId)));
CookieStore cookieStore,
int illustId,
PageQuality quality
) throws IOException {
HttpGet linkApiRequest = new HttpGet(PixivURL.PIXIV_ILLUST_API_URL
.replace("{illustId}", Integer.toString(illustId)));
setCookieInRequest(linkApiRequest, cookieStore); setCookieInRequest(linkApiRequest, cookieStore);
HttpResponse response = httpClient.execute(linkApiRequest); HttpResponse response = httpClient.execute(linkApiRequest);
JsonObject resultObject = new Gson().fromJson(EntityUtils.toString(response.getEntity()), JsonObject.class); JsonObject resultObject = new Gson().fromJson(EntityUtils.toString(response.getEntity()), JsonObject.class);
@ -447,8 +412,7 @@ public class PixivDownload {
@Deprecated @Deprecated
public Set<Map.Entry<String, InputStream>> getCollectionAsInputStream(PageQuality quality) throws IOException { public Set<Map.Entry<String, InputStream>> getCollectionAsInputStream(PageQuality quality) throws IOException {
HashSet<Map.Entry<String, InputStream>> illustInputStreamSet = new HashSet<>(); HashSet<Map.Entry<String, InputStream>> illustInputStreamSet = new HashSet<>();
getCollectionAsInputStream(quality, (link, inputStream) -> getCollectionAsInputStream(quality, (link, inputStream) -> illustInputStreamSet.add(new AbstractMap.SimpleEntry<>(link, inputStream)));
illustInputStreamSet.add(new AbstractMap.SimpleEntry<>(link, inputStream)));
return illustInputStreamSet; return illustInputStreamSet;
} }
@ -529,8 +493,7 @@ public class PixivDownload {
public static void setCookieInRequest(HttpRequest request, CookieStore cookieStore) { public static void setCookieInRequest(HttpRequest request, CookieStore cookieStore) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
cookieStore.getCookies().forEach(cookie -> cookieStore.getCookies().forEach(cookie -> builder.append(cookie.getName()).append("=").append(cookie.getValue()).append("; "));
builder.append(cookie.getName()).append("=").append(cookie.getValue()).append("; "));
request.setHeader(HttpHeaderNames.COOKIE.toString(), builder.toString()); request.setHeader(HttpHeaderNames.COOKIE.toString(), builder.toString());
} }

View File

@ -1,6 +1,7 @@
package net.lamgc.cgj.pixiv; package net.lamgc.cgj.pixiv;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
@ -208,13 +209,7 @@ public final class PixivURL {
* @param pageIndex 页数一页50位总共10页 * @param pageIndex 页数一页50位总共10页
* @return 返回构建好的链接 * @return 返回构建好的链接
*/ */
public static String getRankingLink( public static String getRankingLink(RankingContentType contentType, RankingMode mode, Date time, int pageIndex, boolean json){
RankingContentType contentType,
RankingMode mode,
Date time,
int pageIndex,
boolean json
){
StringBuilder linkBuilder = new StringBuilder(PIXIV_RANKING_LINK); StringBuilder linkBuilder = new StringBuilder(PIXIV_RANKING_LINK);
linkBuilder.append("mode=").append(mode == null ? RankingMode.MODE_DAILY.modeParam : mode.modeParam); linkBuilder.append("mode=").append(mode == null ? RankingMode.MODE_DAILY.modeParam : mode.modeParam);
if(contentType != null && !contentType.equals(RankingContentType.TYPE_ALL)){ if(contentType != null && !contentType.equals(RankingContentType.TYPE_ALL)){
@ -240,6 +235,63 @@ public final class PixivURL {
return linkBuilder.toString(); return linkBuilder.toString();
} }
/**
* 排名榜模式
*/
public enum RankingMode{
/**
* 每天
*/
MODE_DAILY("daily"),
/**
* 每周
*/
MODE_WEEKLY("weekly"),
/**
* 每月
*/
MODE_MONTHLY("monthly"),
/**
* 新人
*/
MODE_ROOKIE("rookie"),
/**
* 原创
*/
MODE_ORIGINAL("original"),
/**
* 受男性喜欢
*/
MODE_MALE("male"),
/**
* 受女性喜欢
*/
MODE_FEMALE("female"),
/**
* 每天 - R18
*/
MODE_DAILY_R18("daily_r18"),
/**
* 每周 - R18
*/
MODE_WEEKLY_R18("weekly_r18"),
/**
* 受男性喜欢 - R18
*/
MODE_MALE_R18("male_r18"),
/**
* 受女性喜欢 - R18
*/
MODE_FEMALE_R18("female_r18"),
;
public String modeParam;
RankingMode(String modeParamName){
this.modeParam = modeParamName;
}
}
/** /**
* Pixiv搜索接口.<br/> * Pixiv搜索接口.<br/>
* 要使用该链接请使用{@link PixivSearchLinkBuilder}构造链接.<br/> * 要使用该链接请使用{@link PixivSearchLinkBuilder}构造链接.<br/>
@ -248,4 +300,72 @@ public final class PixivURL {
*/ */
final static String PIXIV_SEARCH_CONTENT_URL = "https://www.pixiv.net/ajax/search/{area}/{content}?word={content}"; final static String PIXIV_SEARCH_CONTENT_URL = "https://www.pixiv.net/ajax/search/{area}/{content}?word={content}";
/**
* 排名榜类型
*/
public enum RankingContentType{
TYPE_ALL("", RankingMode.values()),
/**
* 插画
* 支持的时间类型: 每天, 每周, 每月, 新人
*/
TYPE_ILLUST("illust",
new RankingMode[]{
RankingMode.MODE_DAILY,
RankingMode.MODE_MONTHLY,
RankingMode.MODE_WEEKLY,
RankingMode.MODE_ROOKIE,
RankingMode.MODE_DAILY_R18,
RankingMode.MODE_WEEKLY_R18,
}
),
/**
* 动图
* 支持的时间类型:每天, 每周
*/
TYPE_UGOIRA("ugoira",
new RankingMode[]{
RankingMode.MODE_DAILY,
RankingMode.MODE_WEEKLY,
RankingMode.MODE_DAILY_R18,
RankingMode.MODE_WEEKLY_R18
}
),
/**
* 漫画
* 支持的时间类型: 每天, 每周, 每月, 新人
*/
TYPE_MANGA("manga",
new RankingMode[]{
RankingMode.MODE_DAILY,
RankingMode.MODE_MONTHLY,
RankingMode.MODE_WEEKLY,
RankingMode.MODE_ROOKIE,
RankingMode.MODE_DAILY_R18,
RankingMode.MODE_WEEKLY_R18,
}
)
;
String typeName;
private final RankingMode[] supportedMode;
RankingContentType(String typeName, RankingMode[] supportedMode){
this.typeName = typeName;
this.supportedMode = supportedMode;
}
/**
* 检查指定RankingMode是否支持
* @param mode 要检查的RankingMode项
* @return 如果支持返回true
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isSupportedMode(RankingMode mode) {
return Arrays.binarySearch(supportedMode, mode) >= 0;
}
}
} }

View File

@ -1,75 +0,0 @@
package net.lamgc.cgj.pixiv;
import java.util.Arrays;
/**
* 排名榜类型
*/
public enum RankingContentType{
/**
* 所有类型.
* 支持所有Mode.
*/
TYPE_ALL("", RankingMode.values()),
/**
* 插画
* 支持的时间类型: 每天, 每周, 每月, 新人
*/
TYPE_ILLUST("illust",
new RankingMode[]{
RankingMode.MODE_DAILY,
RankingMode.MODE_MONTHLY,
RankingMode.MODE_WEEKLY,
RankingMode.MODE_ROOKIE,
RankingMode.MODE_DAILY_R18,
RankingMode.MODE_WEEKLY_R18,
}
),
/**
* 动图
* 支持的时间类型:每天, 每周
*/
TYPE_UGOIRA("ugoira",
new RankingMode[]{
RankingMode.MODE_DAILY,
RankingMode.MODE_WEEKLY,
RankingMode.MODE_DAILY_R18,
RankingMode.MODE_WEEKLY_R18
}
),
/**
* 漫画
* 支持的时间类型: 每天, 每周, 每月, 新人
*/
TYPE_MANGA("manga",
new RankingMode[]{
RankingMode.MODE_DAILY,
RankingMode.MODE_MONTHLY,
RankingMode.MODE_WEEKLY,
RankingMode.MODE_ROOKIE,
RankingMode.MODE_DAILY_R18,
RankingMode.MODE_WEEKLY_R18,
}
)
;
String typeName;
private final RankingMode[] supportedMode;
RankingContentType(String typeName, RankingMode[] supportedMode){
this.typeName = typeName;
this.supportedMode = supportedMode;
}
/**
* 检查指定RankingMode是否支持
* @param mode 要检查的RankingMode项
* @return 如果支持返回true
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isSupportedMode(RankingMode mode) {
return Arrays.binarySearch(supportedMode, mode) >= 0;
}
}

View File

@ -1,58 +0,0 @@
package net.lamgc.cgj.pixiv;
/**
* 排名榜模式
*/
public enum RankingMode{
/**
* 每天
*/
MODE_DAILY("daily"),
/**
* 每周
*/
MODE_WEEKLY("weekly"),
/**
* 每月
*/
MODE_MONTHLY("monthly"),
/**
* 新人
*/
MODE_ROOKIE("rookie"),
/**
* 原创
*/
MODE_ORIGINAL("original"),
/**
* 受男性喜欢
*/
MODE_MALE("male"),
/**
* 受女性喜欢
*/
MODE_FEMALE("female"),
/**
* 每天 - R18
*/
MODE_DAILY_R18("daily_r18"),
/**
* 每周 - R18
*/
MODE_WEEKLY_R18("weekly_r18"),
/**
* 受男性喜欢 - R18
*/
MODE_MALE_R18("male_r18"),
/**
* 受女性喜欢 - R18
*/
MODE_FEMALE_R18("female_r18"),
;
public String modeParam;
RankingMode(String modeParamName){
this.modeParam = modeParamName;
}
}

View File

@ -1,4 +1,4 @@
package net.lamgc.cgj.bot.util.parser; package net.lamgc.cgj.util;
import net.lamgc.utils.base.runner.StringParameterParser; import net.lamgc.utils.base.runner.StringParameterParser;

View File

@ -1,4 +1,4 @@
package net.lamgc.cgj.bot.util.parser; package net.lamgc.cgj.util;
import net.lamgc.cgj.pixiv.PixivDownload; import net.lamgc.cgj.pixiv.PixivDownload;
import net.lamgc.utils.base.runner.StringParameterParser; import net.lamgc.utils.base.runner.StringParameterParser;

View File

@ -133,7 +133,7 @@ public class PixivDownloadTest {
zos.setLevel(9); zos.setLevel(9);
log.info("正在调用方法..."); log.info("正在调用方法...");
try { try {
pixivDownload.getRankingAsInputStream(null, RankingMode.MODE_DAILY_R18, queryDate, 500, PixivDownload.PageQuality.ORIGINAL, (rank, link, rankInfo, inputStream) -> { pixivDownload.getRankingAsInputStream(null, PixivURL.RankingMode.MODE_DAILY_R18, queryDate, 500, PixivDownload.PageQuality.ORIGINAL, (rank, link, rankInfo, inputStream) -> {
try { try {
ZipEntry entry = new ZipEntry("Rank" + rank + "-" + link.substring(link.lastIndexOf("/") + 1)); ZipEntry entry = new ZipEntry("Rank" + rank + "-" + link.substring(link.lastIndexOf("/") + 1));
entry.setComment(rankInfo.toString()); entry.setComment(rankInfo.toString());