Compare commits

..

1 Commits

Author SHA1 Message Date
f976017a89 [Update] 使用搜索推荐接口优化搜索功能对搜索内容的相关性;
[Add] PixivURL 增加搜索推荐接口Url;
[Add] PixivSearchLinkBuilder 增加`getContent`方法以允许外部获取搜索原始内容;
[Add] CacheStoreCentral 增加`getSearchBody(PixivSearchLinkBuilder)`方法以允许直接提供builder进行请求;
[Change] CacheStoreCentral, PixivUtils 移除`getSearchBody(String, ...)`方法对PixivSearchLinkBuilder的构建, 将该部分转移至`PixivUtils.buildSearchLinkBuilder`方法;
[Update] BotCommandProcess 增加`addRecommendKeywords(PixivSearchLinkBuilder, int)`方法以针对PixivSearchLinkBuilder的搜索原始内容增加指定数量的搜索推荐关键词;
2020-07-15 09:00:00 +08:00
24 changed files with 557 additions and 688 deletions

View File

@ -5,7 +5,7 @@ ENV jarFileName=ContentGrabbingJi-exec.jar
ENV CGJ_REDIS_URI="127.0.0.1:6379"
ENV CGJ_PROXY=""
RUN mkdir /data/
ENTRYPOINT ["/usr/java/openjdk-14/bin/java", "-Duser.timezone=GMT+8"]
ENTRYPOINT ["/usr/java/openjdk-14/bin/java", "-Duser.timezone=Aisa/Shanghai"]
CMD ["-Dcgj.logsPath=/data/logs", "-jar", "/CGJ.jar", "botMode", "-botDataDir=/data"]
COPY ${jarFileName} /CGJ.jar

View File

@ -1,19 +1,20 @@
# ContentGrabbingJi - 色图姬 #
一个以高性能、高效率为目标,多平台/框架支持、持续维护的 Pixiv 聊天机器人
一个以高性能、高效率为目标,多平台/框架支持、持续维护的Pixiv聊天机器人
色图姬存在的目的最初是作为**爬虫 + 机器人**的形式开发,在开发过程中逐渐以多聊天平台,高效率为目标进行。
## 安装 ##
### 通过Jar文件部署 ###
1. 从项目的[版本页面](https://github.com/LamGC/ContentGrabbingJi/releases)下载最新版色图姬主程序 jar 文件
2. 准备一个目录用于存放运行数据这里以 `./runData` 为例子)。
3. 将通过 PixivLoginProxyServer 获得的 Pixiv 登录会话文件放置在目录中`./runData/cookies.store`)。
4. 使用命令 `java -jar <CGJ.jar> buildPassword -password "QQ机器人账号的密码"` 构造一个登录用的密码
5. 在数据目录创建一个配置文件 `bot.properties`并添加如下内容
1. 从项目的[版本页面](https://github.com/LamGC/ContentGrabbingJi/releases)下载最新版色图姬主程序jar文件
2. 准备一个目录, 用于存放运行数据(这里以`./runData`为例子).
3. 将通过PixivLoginProxyServer获得的Pixiv登录会话文件放置在目录中(`./runData/cookies.store`).
4. 使用命令`java -jar <CGJ.jar> buildPassword -password "QQ机器人账号的密码"`构造一个登录用的密码.
5. 在数据目录创建一个配置文件`bot.properties`, 并添加如下内容:
```properties
bot.qq=<机器人QQ账号>
bot.password=<通过buildPassword获得的密码>
```
6. 在数据目录创建新文件夹 `setting`并创建一个全局配置文件 `global.properties`然后设置如下内容
6. 在数据目录创建新文件夹`setting`, 并创建一个全局配置文件`global.properties`, 然后设置如下内容:
```properties
# 该配置为全局配置文件, 当群组没有特定配置时, 将使用全局配置.
# 管理员QQ (必填)
@ -29,10 +30,8 @@
# 搜索结果长度. 该选项请适当调整, 设置过长可能导致超出聊天平台的最长消息长度, 导致发送失败!
search.itemCountLimit=8
```
(管理员 QQ 的作用/用法将在下面详细说明。)
7. 配置完成后,准备一台 Redis 服务端,用于缓存数据。
8. Redis 服务器准备好后,使用命令启动色图姬:
`java -jar <CGJ.jar> botMode -botDataDir <数据目录> -redisAddress <Redis服务器地址> [-proxy 代理服务器地址]`
7. 配置完成后, 准备一台Redis服务端, 用于缓存数据.
8. Redis服务器准备好后, 使用命令启动色图姬:`java -jar <CGJ.jar> botMode -botDataDir <数据目录> -redisAddress <Redis服务器地址> [-proxy 代理服务器地址]`
9. 完成!好好享受!
### 通过Docker部署 ###
@ -55,14 +54,11 @@
你应该注意到了在部署过程中你需要设置一个管理员QQ的配置色图姬支持通过命令来管理色图姬的运行。
目前支持的管理员命令:
```bash
# 清除缓存(慎用)
# 该操作将会清除Redis服务器内的所有数据, 以及色图姬下载到本地的所有图片缓存.
# 清除缓存
.cgjadmin cleanCache
# 设置配置项
# 如果不使用group参数, 则设置全局配置
# 注意: 配置项设置后需要使用`.cgjadmin saveProperties`才会保存到文件中,
# 如不保存, 则仅能在本次运行中生效(或使用`.cgjadmin loadProperties`重新加载后失效).
.cgjadmin setProperty <-key 配置项名> <-value 配置项新值> [-group 指定群组]
# 查询配置项
@ -83,8 +79,7 @@
# 增加群组作品推送
# 如果增加了original参数, 则图片为原图发送
# 如果不指定group参数, 则群组为命令发送所在群组
# 最长发送时间 = 最短发送时间 + 随机时间范围
.cgjadmin addPushGroup [-group 指定群组号] [-minTime 最短发送时间] [-floatTime 随机时间范围] [-rankingStart 排行榜起始排名]
.cgjadmin addPushGroup [-group 指定群组号] [-minTime 最小] [-floatTime 随机时间范围] [-rankingStart 排行榜起始排名]
[-rankingStop 排行榜结束排名] [-mode 排行榜模式] [-type 排行榜类型] [-original]
# 删除群组推送功能
@ -107,9 +102,9 @@
```
## 贡献 ##
**向色图姬贡献不一定需要编程知识,向色图姬项目提出意见,反馈问题同样会为色图姬项目提供很大的帮助!**
向色图姬贡献不一定需要编程知识,向色图姬项目提出意见,反馈问题同样会为色图姬项目提供很大的帮助!
如果你在使用色图姬的过程中遇到了Bug可以通过色图姬项目的**Issues**使用[Bug反馈模板](https://github.com/LamGC/ContentGrabbingJi/issues/new?assignees=&labels=bug&template=Bug_Report.md&title=)向色图姬提供Bug信息。
如果是为色图姬提供一些新功能想法,或者对色图姬有什么意见,则可以使用[功能/意见提议模板](https://github.com/LamGC/ContentGrabbingJi/issues/new?assignees=&labels=function%2C+question&template=Feature_Report.md&title=)反馈你的想法!
如果是为色图姬提供一些新功能想法,或者对色图姬有什么意见,则可以直接通过Issues发起讨论。
如果你会Java开发又想为色图姬提供一些新功能可以通过Fork仓库的方法实现后发起PR合并到色图姬项目中
向色图姬贡献代码需要遵循一些贡献事项如果你的代码不符合这些事项PR有可能会被关闭

View File

@ -51,6 +51,7 @@ weekly_r18|`√`|`√`|`√`|`√`
male_r18 |`√`|×|×|×
female_r18|`√`|×|×|×
### 返回数据 ###
#### 数据示例 ####
```json

View File

@ -16,17 +16,14 @@ GET https://www.pixiv.net/ajax/search/{Type}/{Content}?{Param...}
### 参数 ###
#### Url参数 ####
- `Type`: 内容类型
- `artworks` - 所有类型
- `top` - 推荐
- `illustrations` - 插画
- `manga` - 漫画
- `novels` - 小说
- `tags` - 查询标签信息
- illustrations(插画)
- top(推荐)
- manga(漫画)
- novels(小说)
- `Content`: 搜索内容
#### GET参数 ####
##### 必填 #####
> 注意:除 `tags` 类型外,其他内容类型都需要以下参数。
- `word`: 与搜索内容一致 (经测试似乎可以省略)
- `s_mode`: 匹配模式
- `s_tag`: 标签,部分一致
@ -85,8 +82,7 @@ GET https://www.pixiv.net/ajax/search/{Type}/{Content}?{Param...}
"風景",
"空",
"草",
"雲"
],
"雲"],
"userId":"31507675",
"userName":"昏omeme",
"width":1600,
@ -159,8 +155,7 @@ GET https://www.pixiv.net/ajax/search/{Type}/{Content}?{Param...}
"女の子",
"カラス",
"风景",
"線路"
],
"線路"],
"userId":"1069005",
"userName":"へちま",
"width":2000,
@ -315,10 +310,24 @@ GET https://www.pixiv.net/ajax/search/{Type}/{Content}?{Param...}
}
}
```
> 注意:根据 Url 参数中 `Type` 的不同,返回数据的属性也会出现差异,
详见字段说明下的【请求 Url 中的 Type 与返回数据中属性的关系】表格
#### 字段说明 ####
- `novel`: (`Object`) 小说搜索结果
- `data`: (`Object`) 搜索结果(仅当前页数)
- (待补充)
- `total`: (`number`) 搜索结果总量
- `popular`: (`Object`) 受欢迎的搜索结果
- `relatedTags`: (`string[]`) 与搜索结果相关的标签
- `tagTranslation`: (`Object`) 相关标签的翻译信息
- `{Attr: 标签名}`: 标签名为属性名
- `语言名(例如 中文是 zh)`: (`string`) 标签翻译名
- `zoneConfig`: (`Object`) 猜测是广告相关信息?
- `extraData`: (`Object`) 扩展信息
- `meta`: (`Object`) 网页元数据
- `title`: (`string`) 网页标题
- `description`: 搜索结果说明内容
- `descriptionHeader`: (`string`) 说明内容的Html代码
- `alternateLanguages`: (`Object`) 不明链接?
- `{语言名}`: 对应语言的链接
- `illustManga`: (`Object`) 漫画和插画的搜索结果
- `total`: (`number`) 搜索结果总量
- `data`: (`Object[]`) 搜索结果(仅当前页数)
@ -353,45 +362,4 @@ GET https://www.pixiv.net/ajax/search/{Type}/{Content}?{Param...}
- `createDate`: (`string`) 作品创建时间(或者是完成时间?)
- `updateDate`: (`string`) 作品上传时间
- `profileImageUrl`: (`string`) 作者用户头像图片链接
- `bookmarkRanges`: (`Object[]`) 收藏数范围(推测是用于按收藏数搜索而使用)
- `min`: (`number`) 最小收藏数, 值为 `null` 则无限制
- `max`: (`number`) 最大收藏数, 值为 `null` 则无限制
- `illust`: (`Object`) 插画作品搜索结果
- **与`illustManga`结构相同**
- `manga`: (`Object`) 漫画作品搜索结果
- **与`illustManga`结构相同**
- `novel`: (`Object`) 小说搜索结果
- **与`illustManga`结构相同**
- `popular`: (`Object`) 受欢迎的搜索结果
- `recent`: (`Object[]`) 近期推荐
- **与`illustManga.data.{element}`结构相同**
- `permanent`: (`Object[]`) 旧作品推荐
- **与`illustManga.data.{element}`结构相同**
- `relatedTags`: (`string[]`) 与搜索结果相关的原始标签名
- `tagTranslation`: (`Object`) 相关标签的翻译信息
- `{Attr: 标签名}`: 标签名为属性名, 对应 `relatedTags` 中的原始标签名
- `语言名(例如 中文是 zh)`: (`string`) 标签翻译名
- `zoneConfig`: (`Object`) 猜测是广告相关信息?
- `extraData`: (`Object`) 扩展信息
- `meta`: (`Object`) 网页元数据
- `title`: (`string`) 网页标题
- `description`: 搜索结果说明内容
- `descriptionHeader`: (`string`) 说明内容的Html代码
- `alternateLanguages`: (`Object`) 不明链接?
- `{语言名}`: 对应语言的链接
##### 请求 Url 中的 Type 与返回数据中属性的关系 #####
> 表中数据可能有错误,如发现问题,可在发起 Issue 并附上不在该表中情况(例如)的请求信息和返回数据,经确认后将会更新文档。
类型|illustManga|illust|manga|novel
:--|:-:|:-:|:-:|:-:
`artworks` |√|×|×|×
`top` |√|×|×|?
`illustrations`|×|√|×|×
`manga` |×|×|√|×
`novels` |×|×|×|√
符号解释:
- `√`: 该属性一定存在
- `?`: 该属性可能存在
- `×`: 该属性不存在

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

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

View File

@ -11,11 +11,17 @@ import net.lamgc.cgj.bot.cache.JsonRedisCacheStore;
import net.lamgc.cgj.bot.event.BufferedMessageSender;
import net.lamgc.cgj.bot.sort.PreLoadDataAttribute;
import net.lamgc.cgj.bot.sort.PreLoadDataAttributeComparator;
import net.lamgc.cgj.pixiv.*;
import net.lamgc.cgj.bot.util.PixivUtils;
import net.lamgc.cgj.pixiv.PixivDownload;
import net.lamgc.cgj.pixiv.PixivDownload.PageQuality;
import net.lamgc.cgj.util.PixivUtils;
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.Command;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -39,8 +45,6 @@ public class BotCommandProcess {
private final static RankingUpdateTimer updateTimer = new RankingUpdateTimer();
private final static int SEARCH_PAGE_MAX_ITEM = 60;
public static void initialize() {
log.info("正在初始化...");
@ -143,14 +147,9 @@ public class BotCommandProcess {
@Argument(name = "$fromGroup") long fromGroup,
@Argument(force = false, name = "date") Date queryTime,
@Argument(force = false, name = "force") boolean force,
@Argument(force = false, name = "mode", defaultValue = "DAILY") RankingMode contentMode,
@Argument(force = false, name = "type", defaultValue = "ALL") RankingContentType contentType,
@Argument(force = false, name = "p", defaultValue = "1") int pageIndex
@Argument(force = false, name = "mode", defaultValue = "DAILY") String contentMode,
@Argument(force = false, name = "type", defaultValue = "ALL") String contentType
) throws InterruptedException {
if(pageIndex <= 0) {
return "色图姬找不到指定页数的排行榜!";
}
Date queryDate = queryTime;
if (queryDate == null) {
queryDate = new Date();
@ -170,13 +169,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: {})",
contentType.name(), contentMode.name());
type.name(), mode.name());
return "不支持的内容类型或模式!";
}
StringBuilder resultBuilder = new StringBuilder(contentMode.name() + " - 以下是 ")
StringBuilder resultBuilder = new StringBuilder(mode.name() + " - 以下是 ")
.append(new SimpleDateFormat("yyyy-MM-dd").format(queryDate)).append(" 的Pixiv插画排名榜前十名\n");
try {
int index = 0;
@ -198,10 +217,8 @@ public class BotCommandProcess {
log.warn("配置项 {} 的参数值格式有误!", imageLimitPropertyKey);
}
int startsIndex = itemLimit * pageIndex - (itemLimit - 1);
List<JsonObject> rankingInfoList = CacheStoreCentral.getCentral()
.getRankingInfoByCache(contentType, contentMode, queryDate,
Math.max(1, startsIndex), Math.max(0, itemLimit), false);
.getRankingInfoByCache(type, mode, queryDate, 1, Math.max(0, itemLimit), false);
if(rankingInfoList.isEmpty()) {
return "无法查询排行榜,可能排行榜尚未更新。";
}
@ -220,7 +237,7 @@ public class BotCommandProcess {
if (index <= imageLimit) {
resultBuilder
.append(CacheStoreCentral.getCentral()
.getImageById(fromGroup, illustId, PageQuality.REGULAR, 1))
.getImageById(fromGroup, illustId, PixivDownload.PageQuality.REGULAR, 1))
.append("\n");
}
}
@ -250,20 +267,20 @@ public class BotCommandProcess {
@Argument(name = "$fromGroup") long fromGroup,
@Argument(force = false, name = "mode", defaultValue = "DAILY") String contentMode,
@Argument(force = false, name = "type", defaultValue = "ILLUST") String contentType) {
RankingMode mode;
PixivURL.RankingMode mode;
try {
String rankingModeValue = contentMode.toUpperCase();
mode = RankingMode.valueOf(rankingModeValue.startsWith("MODE_") ?
mode = PixivURL.RankingMode.valueOf(rankingModeValue.startsWith("MODE_") ?
rankingModeValue : "MODE_" + rankingModeValue);
} catch (IllegalArgumentException e) {
log.warn("无效的RankingMode值: {}", contentMode);
return "参数无效, 请查看帮助信息";
}
RankingContentType type;
PixivURL.RankingContentType type;
try {
String contentTypeValue = contentType.toUpperCase();
type = RankingContentType.valueOf(
type = PixivURL.RankingContentType.valueOf(
contentTypeValue.startsWith("TYPE_") ? contentTypeValue : "TYPE_" + contentTypeValue);
} catch (IllegalArgumentException e) {
log.warn("无效的RankingContentType值: {}", contentType);
@ -302,9 +319,22 @@ public class BotCommandProcess {
@Argument(name = "option", force = false) String contentOption,
@Argument(name = "p", force = false, defaultValue = "1") int pagesIndex
) throws IOException, InterruptedException {
PixivSearchLinkBuilder searchLinkBuilder = PixivUtils.buildSearchLinkBuilderFromString(content, type, area,
includeKeywords, excludeKeywords, contentOption, pagesIndex);
log.debug("正在执行搜索...");
PixivSearchLinkBuilder linkBuilder = PixivUtils.buildSearchLinkBuilder(content, type, area, includeKeywords,
excludeKeywords, contentOption, pagesIndex);
int recommendKeywordCount = 0;
try {
recommendKeywordCount = Integer.parseInt(SettingProperties.getProperties(fromGroup)
.getProperty("search.recommendKeywordCount", "0"));
} catch(NumberFormatException e) {
log.warn("配置项 search.recommendKeywordCount 的值无效");
}
addRecommendKeywords(linkBuilder, recommendKeywordCount);
JsonObject resultBody = CacheStoreCentral.getCentral()
.getSearchBody(content, type, area, includeKeywords, excludeKeywords, contentOption, pagesIndex);
StringBuilder result = new StringBuilder("内容 " + content + " 的搜索结果:\n");
log.debug("正在处理信息...");
int limit = 8;
try {
limit = Integer.parseInt(SettingProperties.
@ -312,112 +342,95 @@ public class BotCommandProcess {
} catch (Exception e) {
log.warn("参数转换异常!将使用默认值(" + limit + ")", e);
}
int totalCount = 0;
StringBuilder result = new StringBuilder("内容 " + content + " 的搜索结果:\n");
List<JsonObject> artworkList = getSearchResult(searchLinkBuilder, fromGroup, limit, pagesIndex);
artworkList.sort(new PreLoadDataAttributeComparator(PreLoadDataAttribute.LIKE));
int startIndex = limit * pagesIndex - limit + 1;
int pageStartIndex = startIndex % SEARCH_PAGE_MAX_ITEM;
for(int index = pageStartIndex; totalCount < limit && index < artworkList.size(); index++) {
int illustId = artworkList.get(index - 1).get("illustId").getAsInt();
// 预加载数据有更多信息可以提供
JsonObject artworkPreLoadData = CacheStoreCentral.getCentral()
.getIllustPreLoadData(illustId, false);
for (PixivSearchLinkBuilder.SearchArea searchArea : PixivSearchLinkBuilder.SearchArea.values()) {
if (!resultBody.has(searchArea.jsonKey) ||
resultBody.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data").size() == 0) {
log.debug("返回数据不包含 {}", searchArea.jsonKey);
continue;
}
JsonArray illustsArray = resultBody
.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data");
ArrayList<JsonElement> illustsList = new ArrayList<>();
illustsArray.forEach(illustsList::add);
illustsList.sort(new PreLoadDataAttributeComparator(PreLoadDataAttribute.BOOKMARK));
// 构造消息内容
result.append(startIndex++).append(". ").append(artworkPreLoadData.get("illustId").getAsInt()).append(" ")
.append(artworkPreLoadData.get("illustTitle").getAsString());
result.append("\n\t").append("作者:").append(artworkPreLoadData.get("userName").getAsString());
result.append("\n\t").append("作品页数:").append(artworkPreLoadData.get("pageCount").getAsInt()).append("");
result.append("\n\t").append("点赞数:")
.append(artworkPreLoadData.get(PreLoadDataAttribute.LIKE.attrName).getAsInt()).append("");
result.append("\n\t").append("收藏数:")
.append(artworkPreLoadData.get(PreLoadDataAttribute.BOOKMARK.attrName).getAsInt()).append("");
result.append("\n\t").append("围观数:")
.append(artworkPreLoadData.get(PreLoadDataAttribute.VIEW.attrName).getAsInt()).append("");
result.append("\n\t").append("评论数:")
.append(artworkPreLoadData.get(PreLoadDataAttribute.COMMENT.attrName).getAsInt()).append(" ");
result.append(CacheStoreCentral.getCentral()
.getImageById(fromGroup, illustId, PageQuality.REGULAR, 1)).append("\n");
totalCount++;
log.debug("已找到与 {} 相关插图信息({})", content, searchArea.name().toLowerCase());
int count = 1;
for (JsonElement jsonElement : illustsList) {
if (count > limit) {
break;
}
JsonObject illustObj = jsonElement.getAsJsonObject();
if (!illustObj.has("illustId")) {
continue;
}
int illustId = illustObj.get("illustId").getAsInt();
StringBuilder builder = new StringBuilder("[");
illustObj.get("tags").getAsJsonArray().forEach(el -> builder.append(el.getAsString()).append(", "));
builder.replace(builder.length() - 2, builder.length(), "]");
log.debug("{} ({} / {})\n\t作品id: {}, \n\t作者名(作者id): {} ({}), \n\t" +
"作品标题: {}, \n\t作品Tags: {}, \n\t页数: {}页, \n\t作品链接: {}",
searchArea.name(),
count,
illustsList.size(),
illustId,
illustObj.get("userName").getAsString(),
illustObj.get("userId").getAsInt(),
illustObj.get("illustTitle").getAsString(),
builder,
illustObj.get("pageCount").getAsInt(),
PixivURL.getPixivRefererLink(illustId)
);
String imageMsg;
try {
imageMsg = CacheStoreCentral.getCentral()
.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)) {
log.warn("作品Id {} 为R-18作品, 跳过.", illustId);
continue;
} else if(isReported(illustId)) {
log.warn("作品Id {} 被报告, 正在等待审核, 跳过该作品.", illustId);
continue;
}
JsonObject illustPreLoadData = CacheStoreCentral.getCentral()
.getIllustPreLoadData(illustId, false);
result.append(searchArea.name()).append(" (").append(count).append(" / ")
.append(limit).append(")\n\t作品id: ").append(illustId)
.append(", \n\t作者名: ").append(illustObj.get("userName").getAsString())
.append("\n\t作品标题: ").append(illustObj.get("illustTitle").getAsString())
.append("\n\t作品页数: ").append(illustObj.get("pageCount").getAsInt()).append("")
.append("\n\t点赞数")
.append(illustPreLoadData.get(PreLoadDataAttribute.LIKE.attrName).getAsInt())
.append("\n\t收藏数")
.append(illustPreLoadData.get(PreLoadDataAttribute.BOOKMARK.attrName).getAsInt())
.append("\n\t围观数")
.append(illustPreLoadData.get(PreLoadDataAttribute.VIEW.attrName).getAsInt())
.append("\n\t评论数")
.append(illustPreLoadData.get(PreLoadDataAttribute.COMMENT.attrName).getAsInt())
.append("\n").append(imageMsg).append("\n");
count++;
totalCount++;
}
if (count > limit) {
break;
}
}
return totalCount <= 0 ?
"搜索完成,未找到相关作品。" :
Strings.nullToEmpty(result.toString()) + "预览图片并非原图,使用“.cgj image -id 作品id”获取原图\n" +
"如有不当作品,可使用\".cgj report -id 作品id\"向色图姬反馈。";
}
/**
* 获取 length 涉及的多个页的搜索结果.
* 例如:
* pageMaxItem = 60;
* length = 150;
* page = 3;
* 那么:
* endItemIndex = length * page = 450;
* startItemIndex = endItemIndex - length + 1 = 301;
* startPageIndex = ceil(startItemIndex / pageMaxItem) = 6;
* pageRange = ceil((endItemIndex - length + 1) / pageMaxItem) = 3;
* endPageIndex = startPageIndex - pageRange - 1 = 8;
* 该方法将会取搜索结果的 6 ~ 8 页结果并返回;
* @param searchLinkBuilder 已构造好除 Page 参数外其他参数的 {@link PixivSearchLinkBuilder}
* @param length 所需结果的范围
* @param page 所需结果的页数
* @return 返回包含范围的涉及页面所有搜索结果.
* @throws IOException 如获取发生异常则抛出.
*/
private static List<JsonObject> getSearchResult(PixivSearchLinkBuilder searchLinkBuilder, long groupId, int length, int page) throws IOException {
List<JsonObject> artworkList = new ArrayList<>(length);
int endsItemIndex = length * page;
int startsItemIndex = endsItemIndex - length + 1;
int startPageIndex = (int) Math.ceil(startsItemIndex / (double) SEARCH_PAGE_MAX_ITEM);
int pageRange = (int) Math.ceil((endsItemIndex - startsItemIndex) / (double) SEARCH_PAGE_MAX_ITEM);
PixivSearchAttribute areaAttribute = PixivSearchAttribute.valueOf(searchLinkBuilder.getSearchArea().toString());
Properties properties = SettingProperties.getProperties(groupId);
int expectedQuantity = pageRange * SEARCH_PAGE_MAX_ITEM;
for(int pageIndex = startPageIndex;
pageIndex <= startPageIndex + pageRange - 1 || artworkList.size() < length || artworkList.size() < expectedQuantity;
pageIndex++) {
searchLinkBuilder.setPage(pageIndex);
JsonObject searchBody = CacheStoreCentral.getCentral().getSearchBody(searchLinkBuilder);
for(String areaAttributeName : areaAttribute.attributeNames) {
JsonObject areaResult = searchBody.getAsJsonObject(areaAttributeName);
if(areaResult == null || !areaResult.has("data")) {
log.debug("作品类型属性 {} 无搜索结果, 跳过...", areaAttributeName);
continue;
}
JsonArray areaArray = areaResult.getAsJsonArray("data");
for(JsonElement element : areaArray) {
JsonObject artworkInfo = element.getAsJsonObject();
if(!artworkInfo.has("illustId")) {
log.warn("发现未含有illustId的JsonObject: '{}'", artworkInfo.toString());
continue;
}
final int illustId = artworkInfo.get("illustId").getAsInt();
if(isNoSafe(illustId, properties, false)) {
log.warn("作品 {} 为R18作品, 跳过.", illustId);
continue;
} else if(isReported(illustId)) {
log.warn("作品 {} 被报告, 跳过.", illustId);
continue;
}
artworkList.add(artworkInfo);
}
}
}
// 去重
Set<JsonObject> hashSet = new HashSet<>(artworkList.size());
hashSet.addAll(artworkList);
artworkList.clear();
artworkList.addAll(hashSet);
return artworkList;
}
/**
* 获取作品页面的下载链接
* @param illustId 作品Id
@ -527,6 +540,43 @@ public class BotCommandProcess {
return "色图姬收到了你的报告,将屏蔽该作品并对作品违规情况进行核实,感谢你的反馈!";
}
/**
* 根据Pixiv搜索推荐列表补充关键词.
* <p>该操作可能会优化搜索效果.</p>
* @param searchLinkBuilder PixivSearchLinkBuilder对象
* @param includeKeywordsCount 需要添加的关键词数量
* @throws IOException 当获取推荐列表发生异常时抛出.
*/
private static void addRecommendKeywords(PixivSearchLinkBuilder searchLinkBuilder, int includeKeywordsCount)
throws IOException {
if(includeKeywordsCount <= 0) {
return;
}
HttpGet request = BotGlobal.getGlobal().getPixivDownload()
.createHttpGetRequest(PixivURL.PIXIV_SEARCH_RECOMMENDS
.replace("{content}", searchLinkBuilder.getContent()));
request.addHeader(HttpHeaders.REFERER, "https://www.pixiv.net/");
HttpResponse response = BotGlobal.getGlobal().getPixivDownload().getHttpClient().execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
if(response.getStatusLine().getStatusCode() != 200) {
throw new IOException("Interface request failure: " + response.getStatusLine() +
", response body: '" + responseBody + "'");
}
JsonObject resultObject = BotGlobal.getGlobal().getGson()
.fromJson(responseBody, JsonObject.class);
if(!resultObject.has("candidates")) {
return;
}
JsonArray recommendsArr = resultObject.getAsJsonArray("candidates");
for (int count = 0; count < includeKeywordsCount && count < recommendsArr.size(); count++) {
searchLinkBuilder.addIncludeKeyword(
recommendsArr.get(count).getAsJsonObject().get("tag_name").getAsString());
}
}
/**
* 检查某一作品是否被报告
* @param illustId 作品Id

View File

@ -4,8 +4,7 @@ import com.google.gson.JsonObject;
import net.lamgc.cgj.bot.cache.CacheStoreCentral;
import net.lamgc.cgj.bot.message.MessageSender;
import net.lamgc.cgj.pixiv.PixivDownload;
import net.lamgc.cgj.pixiv.RankingContentType;
import net.lamgc.cgj.pixiv.RankingMode;
import net.lamgc.cgj.pixiv.PixivURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -23,8 +22,8 @@ public class RandomRankingArtworksSender extends AutoSender {
private final long groupId;
private final int rankingStart;
private final int rankingStop;
private final RankingMode mode;
private final RankingContentType contentType;
private final PixivURL.RankingMode mode;
private final PixivURL.RankingContentType contentType;
private final PixivDownload.PageQuality quality;
/**
@ -41,8 +40,8 @@ public class RandomRankingArtworksSender extends AutoSender {
MessageSender messageSender,
int rankingStart,
int rankingStop,
RankingMode mode,
RankingContentType contentType,
PixivURL.RankingMode mode,
PixivURL.RankingContentType contentType,
PixivDownload.PageQuality quality) {
this(messageSender, 0, rankingStart, rankingStop, mode, contentType, quality);
}
@ -63,8 +62,8 @@ public class RandomRankingArtworksSender extends AutoSender {
long groupId,
int rankingStart,
int rankingStop,
RankingMode mode,
RankingContentType contentType,
PixivURL.RankingMode mode,
PixivURL.RankingContentType contentType,
PixivDownload.PageQuality quality) {
super(messageSender);
this.groupId = groupId;
@ -74,8 +73,7 @@ public class RandomRankingArtworksSender extends AutoSender {
this.rankingStart = rankingStart > 0 ? rankingStart : 1;
this.rankingStop = rankingStop > 0 ? rankingStop : 150;
if(this.rankingStart > this.rankingStop) {
throw new IndexOutOfBoundsException(
"rankingStart=" + this.rankingStart + ", rankingStop=" + this.rankingStop);
throw new IndexOutOfBoundsException("rankingStart=" + this.rankingStart + ", rankingStop=" + this.rankingStop);
}
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.VirtualLoadMessageEvent;
import net.lamgc.cgj.pixiv.RankingContentType;
import net.lamgc.cgj.pixiv.RankingMode;
import net.lamgc.cgj.pixiv.PixivURL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -65,15 +64,14 @@ public class RankingUpdateTimer {
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
log.info("正在获取 {} 期排行榜数据...", calendar.getTime());
for (RankingMode rankingMode : RankingMode.values()) {
for (RankingContentType contentType : RankingContentType.values()) {
for (PixivURL.RankingMode rankingMode : PixivURL.RankingMode.values()) {
for (PixivURL.RankingContentType contentType : PixivURL.RankingContentType.values()) {
if(!contentType.isSupportedMode(rankingMode)) {
log.debug("不支持的类型, 填空值跳过...(类型: {}.{})", rankingMode.name(), contentType.name());
}
log.info("当前排行榜类型: {}.{}, 正在更新...", rankingMode.name(), contentType.name());
BotEventHandler.executeMessageEvent(new VirtualLoadMessageEvent(0,0,
".cgj ranking -type=" + contentType.name() +
" -mode=" + rankingMode.name() + " -force -date " + dateStr));
".cgj ranking -type=" + contentType.name() + " -mode=" + rankingMode.name() + " -force -date " + dateStr));
log.info("排行榜 {}.{} 负载指令已投递.", rankingMode.name(), contentType.name());
}
}

View File

@ -8,11 +8,11 @@ import net.lamgc.cgj.bot.BotCode;
import net.lamgc.cgj.bot.BotCommandProcess;
import net.lamgc.cgj.bot.SettingProperties;
import net.lamgc.cgj.bot.boot.BotGlobal;
import net.lamgc.cgj.bot.util.PixivUtils;
import net.lamgc.cgj.exception.HttpRequestException;
import net.lamgc.cgj.pixiv.PixivDownload;
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
import net.lamgc.cgj.pixiv.RankingContentType;
import net.lamgc.cgj.pixiv.RankingMode;
import net.lamgc.cgj.pixiv.PixivURL;
import net.lamgc.cgj.util.Locker;
import net.lamgc.cgj.util.LockerMap;
import net.lamgc.cgj.util.URLs;
@ -125,8 +125,7 @@ public final class CacheStoreCentral {
* @param pageIndex 指定页面索引, 从1开始
* @return 如果成功, 返回BotCode, 否则返回错误信息.
*/
public String getImageById(long fromGroup, int illustId, PixivDownload.PageQuality quality, int pageIndex)
throws InterruptedException {
public String getImageById(long fromGroup, int illustId, PixivDownload.PageQuality quality, int pageIndex) throws InterruptedException {
log.debug("IllustId: {}, Quality: {}, PageIndex: {}", illustId, quality.name(), pageIndex);
if(pageIndex <= 0) {
log.warn("指定的页数不能小于或等于0: {}", pageIndex);
@ -356,8 +355,8 @@ public final class CacheStoreCentral {
* @return 成功返回有值List, 失败且无异常返回空
* @throws IOException 获取异常时抛出
*/
public List<JsonObject> getRankingInfoByCache(RankingContentType contentType,
RankingMode mode,
public List<JsonObject> getRankingInfoByCache(PixivURL.RankingContentType contentType,
PixivURL.RankingMode mode,
Date queryDate, int start, int range, boolean flushCache)
throws IOException {
if(!contentType.isSupportedMode(mode)) {
@ -404,29 +403,22 @@ public final class CacheStoreCentral {
result = rankingCache.getCache(requestSign, start - 1, range);
log.trace("RequestSign [{}] 缓存命中.", requestSign);
}
return result;
return PixivDownload.getRanking(result, start - 1, range);
}
/**
* 获取搜索结果
* @param searchBuilder 需要执行搜索的搜索链接构造器
* @return 返回完整搜索结果
* @throws IOException 当请求发生异常, 或接口返回异常信息时抛出.
*/
public JsonObject getSearchBody(PixivSearchLinkBuilder searchBuilder) throws IOException {
log.debug("正在搜索作品, 条件: {}", searchBuilder.getSearchCondition());
String requestUrl = searchBuilder.buildURL();
String searchIdentify =
requestUrl.substring(requestUrl.lastIndexOf("/", requestUrl.lastIndexOf("/") - 1) + 1);
Locker<String> locker =
buildSyncKey(searchIdentify);
public JsonObject getSearchBody(PixivSearchLinkBuilder searchLinkBuilder) throws IOException {
log.debug("正在搜索作品, 条件: {}", searchLinkBuilder.getSearchCondition());
Locker<String> locker
= buildSyncKey(searchLinkBuilder.buildURL());
String requestUrl = locker.getKey();
log.debug("RequestUrl: {}", requestUrl);
JsonObject resultBody = null;
if(!searchBodyCache.exists(searchIdentify)) {
if(!searchBodyCache.exists(requestUrl)) {
try {
locker.lock();
synchronized (locker) {
if (!searchBodyCache.exists(searchIdentify)) {
if (!searchBodyCache.exists(requestUrl)) {
log.trace("searchBody缓存失效, 正在更新...");
JsonObject jsonObject;
HttpGet httpGetRequest = BotGlobal.getGlobal().getPixivDownload().
@ -451,8 +443,8 @@ public final class CacheStoreCentral {
} catch (Exception e) {
log.warn("全局配置项 \"{}\" 值非法, 已使用默认值: {}", propValue, expire);
}
resultBody = jsonObject;
searchBodyCache.update(searchIdentify, jsonObject, expire);
resultBody = jsonObject.getAsJsonObject().getAsJsonObject("body");
searchBodyCache.update(requestUrl, jsonObject, expire);
log.trace("searchBody缓存已更新(有效时间: {})", expire);
} else {
log.trace("搜索缓存命中.");
@ -466,9 +458,34 @@ public final class CacheStoreCentral {
}
if(Objects.isNull(resultBody)) {
resultBody = searchBodyCache.getCache(searchIdentify).getAsJsonObject();
resultBody = searchBodyCache.getCache(requestUrl).getAsJsonObject().getAsJsonObject("body");
}
return resultBody.getAsJsonObject("body");
return resultBody;
}
/**
* 获取搜索结果
* @param content 搜索内容
* @param type 类型
* @param area 范围
* @param includeKeywords 包含关键词
* @param excludeKeywords 排除关键词
* @param contentOption 内容类型
* @return 返回完整搜索结果
* @throws IOException 当请求发生异常, 或接口返回异常信息时抛出.
*/
public JsonObject getSearchBody(
String content,
String type,
String area,
String includeKeywords,
String excludeKeywords,
String contentOption,
int pageIndex
) throws IOException {
return getSearchBody(PixivUtils.buildSearchLinkBuilder(content, type, area, includeKeywords,
excludeKeywords, contentOption, pageIndex));
}
protected ImageChecksum getImageChecksum(int illustId, int pageIndex) {

View File

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

View File

@ -92,14 +92,11 @@ public class MiraiMain implements Closeable {
private void executeMessageEvent(MessageEvent message) {
log.debug("Mirai Message: {}", message);
if(message instanceof GroupMessageEvent) {
GroupMessageEvent groupMessageEvent = (GroupMessageEvent) message;
Boolean muteState = muteManager.isMute(groupMessageEvent.getGroup().getId(), true);
GroupMessageEvent GroupMessageEvent = (GroupMessageEvent) message;
Boolean muteState = muteManager.isMute(GroupMessageEvent.getGroup().getId(), true);
if(muteState == null) {
boolean mute = groupMessageEvent.getGroup().getBotMuteRemaining() != 0;
muteManager.setMuteState(groupMessageEvent.getGroup().getId(), mute);
if(mute) {
return;
}
muteManager.setMuteState(GroupMessageEvent.getGroup().getId(),
((GroupMessageEvent) message).getGroup().getBotMuteRemaining() != 0);
} else if(muteState) {
return;
}

View File

@ -1,4 +1,4 @@
package net.lamgc.cgj.util;
package net.lamgc.cgj.bot.util;
import com.google.common.base.Strings;
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
@ -26,7 +26,7 @@ public final class PixivUtils {
* @return 返回PixivSearchLinkBuilder对象
* @see PixivSearchLinkBuilder
*/
public static PixivSearchLinkBuilder buildSearchLinkBuilderFromString(
public static PixivSearchLinkBuilder buildSearchLinkBuilder(
String content,
String type,
String area,
@ -38,14 +38,14 @@ public final class PixivUtils {
PixivSearchLinkBuilder searchBuilder = new PixivSearchLinkBuilder(Strings.isNullOrEmpty(content) ? "" : content);
if (type != null) {
try {
searchBuilder.setSearchType(PixivSearchLinkBuilder.SearchType.valueOf(type.trim().toUpperCase()));
searchBuilder.setSearchType(PixivSearchLinkBuilder.SearchType.valueOf(type.toUpperCase()));
} catch (IllegalArgumentException e) {
log.warn("不支持的SearchType: {}", type);
}
}
if (area != null) {
try {
searchBuilder.setSearchArea(PixivSearchLinkBuilder.SearchArea.valueOf(area.trim().toUpperCase()));
searchBuilder.setSearchArea(PixivSearchLinkBuilder.SearchArea.valueOf(area));
} catch (IllegalArgumentException e) {
log.warn("不支持的SearchArea: {}", area);
}
@ -81,4 +81,6 @@ public final class PixivUtils {
return searchBuilder;
}
}

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

@ -4,6 +4,7 @@ import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import io.netty.handler.codec.http.HttpHeaderNames;
import net.lamgc.cgj.exception.HttpRequestException;
import org.apache.http.Header;
@ -31,6 +32,7 @@ import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
@SuppressWarnings("ALL")
public class PixivDownload {
private final static Logger log = LoggerFactory.getLogger(PixivDownload.class);
@ -56,10 +58,10 @@ public class PixivDownload {
this.cookieStore = cookieStore;
HttpClientBuilder builder = HttpClientBuilder.create();
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);
defaultHeaders.add(new BasicHeader("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"));
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"));
builder.setDefaultHeaders(defaultHeaders);
builder.setProxy(proxy);
httpClient = builder.build();
@ -84,8 +86,7 @@ public class PixivDownload {
Document document;
ArrayList<String> linkList = new ArrayList<>();
do {
request = new HttpGet(PixivURL.PIXIV_USER_COLLECTION_PAGE
.replace("{pageIndex}", Integer.toString(++pageIndex)));
request = new HttpGet(PixivURL.PIXIV_USER_COLLECTION_PAGE.replace("{pageIndex}", Integer.toString(++pageIndex)));
setCookieInRequest(request, cookieStore);
log.debug("Request Link: " + request.getURI().toString());
HttpResponse response = httpClient.execute(request);
@ -100,13 +101,10 @@ public class PixivDownload {
Gson gson = new Gson();
for (String href : hrefList) {
HttpGet linkApiRequest = createHttpGetRequest(PixivURL.PIXIV_ILLUST_API_URL
.replace("{illustId}", href.substring(href.lastIndexOf("/") + 1)));
HttpGet linkApiRequest = createHttpGetRequest(PixivURL.PIXIV_ILLUST_API_URL.replace("{illustId}", href.substring(href.lastIndexOf("/") + 1)));
log.debug(linkApiRequest.getURI().toString());
HttpResponse httpResponse = httpClient.execute(linkApiRequest);
JsonObject linkResult =
gson.fromJson(EntityUtils.toString(httpResponse.getEntity()), JsonObject.class);
JsonObject linkResult = gson.fromJson(EntityUtils.toString(httpResponse.getEntity()), JsonObject.class);
if(linkResult.get("error").getAsBoolean()) {
log.error("接口返回错误信息: {}", linkResult.get("message").getAsString());
continue;
@ -115,10 +113,7 @@ public class PixivDownload {
JsonArray linkArray = linkResult.get("body").getAsJsonArray();
for (int i = 0; i < linkArray.size(); i++) {
JsonObject linkObject = linkArray.get(i).getAsJsonObject().get("urls").getAsJsonObject();
linkList.add(
linkObject.get((quality == null ? PageQuality.ORIGINAL : quality).toString().toLowerCase())
.getAsString()
);
linkList.add(linkObject.get((quality == null ? PageQuality.ORIGINAL : quality).toString().toLowerCase()).getAsString());
}
}
} while(!document.select(".pager-container>.next").isEmpty());
@ -160,8 +155,7 @@ public class PixivDownload {
Document document = Jsoup.parse(EntityUtils.toString(response.getEntity()));
HttpClient imageClient = HttpClientBuilder.create().build();
Elements elements = document
.select(".gtm-illust-recommend-zone>.image-item>.gtm-illust-recommend-thumbnail-link");
Elements elements = document.select(".gtm-illust-recommend-zone>.image-item>.gtm-illust-recommend-thumbnail-link");
for(int illustIndex = 0; illustIndex < elements.size(); illustIndex++){
String href = elements.get(illustIndex).attr("href");
int illustId = Integer.parseInt(href.substring(href.lastIndexOf("/") + 1));
@ -203,14 +197,8 @@ public class PixivDownload {
* @param fn 回调函数
* @throws IOException 当请求发生异常时抛出
*/
public void getRankingAsInputStream(
RankingContentType contentType,
RankingMode mode,
Date time,
int range,
PageQuality quality,
RankingDownloadFunction fn
) throws IOException {
public void getRankingAsInputStream(PixivURL.RankingContentType contentType, PixivURL.RankingMode mode,
Date time, int range, PageQuality quality, RankingDownloadFunction fn) throws IOException {
getRankingAsInputStream(contentType, mode, time, 1, range, quality, fn);
}
@ -225,23 +213,15 @@ public class PixivDownload {
* @param fn 回调函数
* @throws IOException 当请求发生异常时抛出
*/
public void getRankingAsInputStream(
RankingContentType contentType,
RankingMode mode,
Date time,
int rankStart,
int range,
PageQuality quality,
RankingDownloadFunction fn
) throws IOException {
public void getRankingAsInputStream(PixivURL.RankingContentType contentType, PixivURL.RankingMode mode,
Date time, int rankStart, int range, PageQuality quality, RankingDownloadFunction fn) throws IOException {
getRanking(contentType, mode, time, rankStart, range).forEach(rankInfo -> {
int rank = rankInfo.get("rank").getAsInt();
int illustId = rankInfo.get("illust_id").getAsInt();
int authorId = rankInfo.get("user_id").getAsInt();
String authorName = rankInfo.get("user_name").getAsString();
String title = rankInfo.get("title").getAsString();
log.trace("当前到第 {}/{} 名(总共 {} 名), IllustID: {}, Author: ({}) {}, Title: {}",
rank, rankStart + range - 1, range, illustId, authorId, authorName, title);
log.trace("当前到第 {}/{} 名(总共 {} 名), IllustID: {}, Author: ({}) {}, Title: {}", rank, rankStart + range - 1, range, illustId, authorId, authorName, title);
log.trace("正在获取PagesLink...");
List<String> linkList;
try {
@ -258,11 +238,7 @@ public class PixivDownload {
for (int pageIndex = 0; pageIndex < linkList.size(); pageIndex++) {
String downloadLink = linkList.get(pageIndex);
log.trace("当前Page: {}/{}", pageIndex + 1, linkList.size());
try(InputStream imageInputStream =
new BufferedInputStream(
getImageAsInputStream(HttpClientBuilder.create().build(), downloadLink),
256 * 1024)
) {
try(InputStream imageInputStream = new BufferedInputStream(getImageAsInputStream(HttpClientBuilder.create().build(), downloadLink), 256 * 1024)) {
fn.download(rank, downloadLink, rankInfo.deepCopy(), imageInputStream);
} catch(IOException e) {
log.error("下载插画时发生异常", e);
@ -273,6 +249,43 @@ public class PixivDownload {
});
}
/**
* 从JsonArray获取数据
* @param rankingList JsonArray对象
* @param rankStart 开始索引, 从0开始
* @param range 范围
* @return 返回List对象
*/
public static List<JsonObject> getRanking(List<JsonObject> rankingList, int rankStart, int range) {
log.debug("正在读取JsonArray...(rankStart: {}, range: {})", rankStart, range);
ArrayList<JsonObject> results = new ArrayList<>(rankingList.size());
for (int rankIndex = rankStart; rankIndex < rankStart + range; rankIndex++) {
JsonElement jsonElement = rankingList.get(rankIndex - rankStart);
JsonObject rankInfo = jsonElement.getAsJsonObject();
int rank = rankInfo.get("rank").getAsInt();
int illustId = rankInfo.get("illust_id").getAsInt();
int authorId = rankInfo.get("user_id").getAsInt();
String authorName = rankInfo.get("user_name").getAsString();
String title = rankInfo.get("title").getAsString();
log.trace("Array-当前到第 {}/{} 名(总共 {} 名), IllustID: {}, Author: ({}) {}, Title: {}", rank, rankStart + range, range, illustId, authorId, authorName, title);
results.add(rankInfo);
}
log.debug("JsonArray读取完成.");
return results;
}
/**
* 从JsonArray获取数据
* @param rankingArray JsonArray对象
* @param rankStart 开始索引, 从0开始
* @param range 范围
* @return 返回List对象
*/
public static List<JsonObject> getRanking(JsonArray rankingArray, int rankStart, int range) {
List<JsonObject> list = new Gson().fromJson(rankingArray, new TypeToken<List<JsonObject>>(){}.getType());
return getRanking(list, rankStart, range);
}
/**
* 获取排行榜.
* <p>注意: 如果范围实际上没超出, 但返回排行榜不足, 会导致与实际请求的数量不符, 需要检查</p>
@ -282,24 +295,22 @@ public class PixivDownload {
* @param rankStart 开始排名, 从1开始
* @param range 取范围
* @return 成功返回有值List, 失败且无异常返回空
* @throws IllegalArgumentException 当{@linkplain net.lamgc.cgj.pixiv.RankingContentType RankingContentType}
* 与{@linkplain net.lamgc.cgj.pixiv.RankingMode RankingMode}互不兼容时抛出
* @throws IllegalArgumentException 当{@linkplain net.lamgc.cgj.pixiv.PixivURL.RankingContentType RankingContentType}
* 与{@linkplain net.lamgc.cgj.pixiv.PixivURL.RankingMode RankingMode}互不兼容时抛出
* @throws IndexOutOfBoundsException 当排行榜选取范围超出排行榜范围时抛出(排行榜范围为 1 ~ 500 名)
* @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 {
Objects.requireNonNull(time);
if(!Objects.requireNonNull(contentType).isSupportedMode(Objects.requireNonNull(mode))) {
throw new IllegalArgumentException("ContentType不支持指定的RankingMode: ContentType: "
+ contentType.name() + ", Mode: " + mode.name());
throw new IllegalArgumentException("ContentType不支持指定的RankingMode: ContentType: " + contentType.name() + ", Mode: " + mode.name());
} else if(rankStart <= 0) {
throw new IndexOutOfBoundsException("rankStart cannot be less than or equal to zero: " + rankStart);
} else if(range <= 0) {
throw new IndexOutOfBoundsException("range cannot be less than or equal to zero:" + range);
} else if(rankStart + range - 1 > 500) {
throw new IndexOutOfBoundsException("排名选取范围超出了排行榜范围: rankStart="
+ rankStart + ", range=" + range + ", length:" + (rankStart + range - 1));
throw new IndexOutOfBoundsException("排名选取范围超出了排行榜范围: rankStart=" + rankStart + ", range=" + range + ", length:" + (rankStart + range - 1));
}
int startPages = (int) Math.max(1, Math.floor(rankStart / 50F));
@ -322,8 +333,7 @@ public class PixivDownload {
JsonObject resultObject = gson.fromJson(responseBody, JsonObject.class);
canNext = resultObject.get("next").getAsJsonPrimitive().isNumber();
JsonArray resultArray = resultObject.getAsJsonArray("contents");
for (int resultIndex = startIndex;
resultIndex < resultArray.size() && count < range; resultIndex++, count++) {
for (int resultIndex = startIndex; resultIndex < resultArray.size() && count < range; resultIndex++, count++) {
results.add(resultArray.get(resultIndex).getAsJsonObject());
}
@ -383,14 +393,8 @@ public class PixivDownload {
* @return 返回该illust所有Page的下载链接
* @throws IOException 当HttpClient在请求时发生异常, 或接口报错时抛出, 注意{@link IOException#getMessage()}
*/
public static List<String> getIllustAllPageDownload(
HttpClient httpClient,
CookieStore cookieStore,
int illustId,
PageQuality quality
) throws IOException {
HttpGet linkApiRequest = new HttpGet(PixivURL.PIXIV_ILLUST_API_URL
.replace("{illustId}", Integer.toString(illustId)));
public static List<String> getIllustAllPageDownload(HttpClient httpClient, 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);
HttpResponse response = httpClient.execute(linkApiRequest);
JsonObject resultObject = new Gson().fromJson(EntityUtils.toString(response.getEntity()), JsonObject.class);
@ -417,7 +421,6 @@ public class PixivDownload {
/**
* 插图质量
*/
@SuppressWarnings("unused")
public enum PageQuality{
/**
* 原图画质
@ -447,8 +450,7 @@ public class PixivDownload {
@Deprecated
public Set<Map.Entry<String, InputStream>> getCollectionAsInputStream(PageQuality quality) throws IOException {
HashSet<Map.Entry<String, InputStream>> illustInputStreamSet = new HashSet<>();
getCollectionAsInputStream(quality, (link, inputStream) ->
illustInputStreamSet.add(new AbstractMap.SimpleEntry<>(link, inputStream)));
getCollectionAsInputStream(quality, (link, inputStream) -> illustInputStreamSet.add(new AbstractMap.SimpleEntry<>(link, inputStream)));
return illustInputStreamSet;
}
@ -529,8 +531,7 @@ public class PixivDownload {
public static void setCookieInRequest(HttpRequest request, CookieStore cookieStore) {
StringBuilder builder = new StringBuilder();
cookieStore.getCookies().forEach(cookie ->
builder.append(cookie.getName()).append("=").append(cookie.getValue()).append("; "));
cookieStore.getCookies().forEach(cookie -> builder.append(cookie.getName()).append("=").append(cookie.getValue()).append("; "));
request.setHeader(HttpHeaderNames.COOKIE.toString(), builder.toString());
}

View File

@ -1,22 +0,0 @@
package net.lamgc.cgj.pixiv;
/**
* 搜索结果的属性枚举类.
* <p>按照请求的{@link PixivSearchLinkBuilder.SearchArea}获取所支持的属性数组</p>
*/
public enum PixivSearchAttribute {
ARTWORKS("illustManga"),
TOP("illustManga", "novel"),
ILLUSTRATIONS("illust"),
MANGA("manga"),
NOVELS("novel")
;
public final String[] attributeNames;
PixivSearchAttribute(String... attributeNames) {
this.attributeNames = attributeNames;
}
}

View File

@ -8,7 +8,6 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
/**
* Pixiv搜索URL构造器
@ -16,7 +15,7 @@ import java.util.Set;
* @author LamGC
* @see PixivURL#PIXIV_SEARCH_CONTENT_URL
*/
@SuppressWarnings({"unused", "UnusedReturnValue"})
@SuppressWarnings("unused")
public class PixivSearchLinkBuilder {
private final String content;
@ -27,8 +26,8 @@ public class PixivSearchLinkBuilder {
private SearchOrder searchOrder = SearchOrder.DATE_D;
private SearchContentOption searchContentOption = SearchContentOption.ALL;
private final Set<String> includeKeywords = new HashSet<>(0);
private final Set<String> excludeKeywords = new HashSet<>(0);
private final HashSet<String> includeKeywords = new HashSet<>(0);
private final HashSet<String> excludeKeywords = new HashSet<>(0);
private int page = 1;
@ -171,10 +170,6 @@ public class PixivSearchLinkBuilder {
return this;
}
public SearchArea getSearchArea() {
return searchArea;
}
/**
* 获取搜索条件.
* @return 搜索条件内容
@ -208,60 +203,32 @@ public class PixivSearchLinkBuilder {
return this;
}
public SearchMode getSearchMode() {
return searchMode;
}
public PixivSearchLinkBuilder setSearchType(SearchType searchType) {
this.searchType = Objects.requireNonNull(searchType);
return this;
}
public SearchType getSearchType() {
return searchType;
}
public PixivSearchLinkBuilder setSearchOrder(SearchOrder searchOrder) {
this.searchOrder = Objects.requireNonNull(searchOrder);
return this;
}
public SearchOrder getSearchOrder() {
return searchOrder;
}
public PixivSearchLinkBuilder setSearchContentOption(SearchContentOption searchContentOption) {
this.searchContentOption = Objects.requireNonNull(searchContentOption);
return this;
}
public SearchContentOption getSearchContentOption() {
return searchContentOption;
}
public PixivSearchLinkBuilder setRatioOption(RatioOption ratioOption) {
this.ratioOption = Objects.requireNonNull(ratioOption);
return this;
}
public RatioOption getRatioOption() {
return ratioOption;
}
public PixivSearchLinkBuilder setDateRange(Date startDate, Date endDate) {
this.startDate = startDate;
this.endDate = endDate;
return this;
}
public Date getStartDate() {
return startDate;
}
public Date getEndDate() {
return endDate;
}
public PixivSearchLinkBuilder setMaxSize(int width, int height) {
this.wgt = width;
this.hgt = height;
@ -282,10 +249,6 @@ public class PixivSearchLinkBuilder {
return this;
}
public int getPage() {
return page;
}
public PixivSearchLinkBuilder addExcludeKeyword(String keyword) {
excludeKeywords.add(keyword);
return this;
@ -306,14 +269,6 @@ public class PixivSearchLinkBuilder {
return this;
}
public Set<String> getIncludeKeywords() {
return new HashSet<>(includeKeywords);
}
public Set<String> getExcludeKeywords() {
return new HashSet<>(excludeKeywords);
}
/**
* 搜索区域
*/
@ -345,18 +300,13 @@ public class PixivSearchLinkBuilder {
*/
NOVELS("novel");
/**
* 可用的Json属性名
* @deprecated 该属性信息以移至 {@link PixivSearchAttribute}
* @see PixivSearchAttribute
*/
@Deprecated
public final String jsonKey;
SearchArea(String jsonKey) {
this.jsonKey = jsonKey;
}
}
/**
@ -455,4 +405,5 @@ public class PixivSearchLinkBuilder {
}
}

View File

@ -1,6 +1,7 @@
package net.lamgc.cgj.pixiv;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
@ -193,6 +194,16 @@ public final class PixivURL {
*/
public final static String PIXIV_USER_COLLECTION_PAGE = "https://www.pixiv.net/bookmark.php?rest=show&p={pageIndex}";
/**
* 搜索推荐接口.
* <p>可返回与搜索内容相关的标签信息, 以优化搜索效果.</p>
* 需要替换的文本:
* <ul>
* <li>{content} - 搜索内容</li>
* </ul>
*/
public final static String PIXIV_SEARCH_RECOMMENDS = "https://www.pixiv.net/rpc/cps.php?keywork={content}";
/**
* 获取排名榜
* @param mode 查询类型, 详细信息看{@link RankingMode}, 如本参数为null, 则为每天
@ -208,13 +219,7 @@ public final class PixivURL {
* @param pageIndex 页数一页50位总共10页
* @return 返回构建好的链接
*/
public static String getRankingLink(
RankingContentType contentType,
RankingMode mode,
Date time,
int pageIndex,
boolean json
){
public static String getRankingLink(RankingContentType contentType, RankingMode mode, Date time, int pageIndex, boolean json){
StringBuilder linkBuilder = new StringBuilder(PIXIV_RANKING_LINK);
linkBuilder.append("mode=").append(mode == null ? RankingMode.MODE_DAILY.modeParam : mode.modeParam);
if(contentType != null && !contentType.equals(RankingContentType.TYPE_ALL)){
@ -240,6 +245,63 @@ public final class PixivURL {
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/>
* 要使用该链接请使用{@link PixivSearchLinkBuilder}构造链接.<br/>
@ -248,4 +310,72 @@ public final class PixivURL {
*/
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;

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.utils.base.runner.StringParameterParser;

View File

@ -133,7 +133,7 @@ public class PixivDownloadTest {
zos.setLevel(9);
log.info("正在调用方法...");
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 {
ZipEntry entry = new ZipEntry("Rank" + rank + "-" + link.substring(link.lastIndexOf("/") + 1));
entry.setComment(rankInfo.toString());