Compare commits

...

40 Commits

Author SHA1 Message Date
5637ef30d4 Merge branch 'master' of github.com:LamGC/ContentGrabbingJi into add-framework-interface 2020-07-15 14:40:38 +08:00
bf8de1ac1e [Fix] 修复潜在的时区错误问题;
[Fix] Dockerfile.sample 将时区配置从`Asia/Shanghai`改成`GMT+8`;
2020-07-15 14:09:47 +08:00
6fc7d8ad78 [Change] 调整Framework接口, 为框架提供特定数据存储目录;
[Change] Framework 适配FrameworkResources的更改, 将`getName`调整为`getIdentify`, 增加`getFrameworkName`方法用于获取框架名(可能会改为注解方式以防止更改);
[Change] FrameworkManager 适配Framework的更改, 增加`checkFramework`方法以对FrameworkName进行检查;
[Change] FrameworkManager, FrameworkResources 将FrameworkResources从FrameworkManager分离成单独的类;
[Change] ConsoleMain, MiraiMain, SpringCQApplication 适配相关更改;
2020-07-15 10:57:30 +08:00
a7c434da61 [Change] 调整Readme内容;
[Fix] README.md 补充管理员命令内容;
2020-07-15 10:35:31 +08:00
575dc0c7fb [Fix] Dockerfile.sample 修复了容器无法正常启动的问题; 2020-07-14 11:01:21 +08:00
56ef463c63 [Change] MessageEvent 调整toString输出中hashCode的格式; 2020-07-13 20:35:39 +08:00
4387da37f5 [Change] 调整群禁言管理职责;
[Delete] BotEventHandler 移除禁言状态管理相关功能;
[Add] GroupMuteManager, GroupMuteManagerTest 增加群禁言状态管理类;
[Change] MiraiMain 将禁言状态对接由使用BotEventHandler改为独立管理;
2020-07-13 09:47:36 +08:00
0fc3e3ab48 [Change] 调整应用内事件线程池参数;
[Change] BotEventHandler 调整线程池参数;
2020-07-13 09:47:31 +08:00
a606ec0423 [Fix] IssueTemplates 修复模板错误的问题; 2020-07-12 11:18:29 +08:00
210aa84ed5 [Update] IssueTemplates 增加功能模板并更新Bug模板; 2020-07-12 11:12:21 +08:00
6fbbe522db [Fix #22] PixivDownload 修复因InputStream意外关闭导致的异常误判; 2020-07-12 01:12:58 +08:00
6d55325fc7 [Fix] PixivUgoiraBuilder 修复ZipInputStream在读取完第一帧图像后被意外关闭的问题; 2020-07-10 09:53:41 +08:00
d1c7f6f973 [Version] 更新版本(2.5.2-20200630.2-SNAPSHOT -> 2.5.2-20200709.1-SNAPSHOT); 2020-07-09 22:45:36 +08:00
0727ef4f93 [Clear] CQPluginMain 整理代码; 2020-07-09 22:19:35 +08:00
73a1caaf46 [Fix #21] 修复了RandomIntervalSendTimer在高版本Java中因非法反射导致应用异常终止的问题; 2020-07-09 22:17:09 +08:00
4784f8773b [Change] Pixiv搜索推荐候选接口.md 更新文档内容; 2020-07-03 10:09:21 +08:00
9a7d16124a [Add] FrameworkManager 添加"frameworkSet"方法; 2020-07-03 10:05:20 +08:00
b754559187 Merge branch 'master' into add-framework-interface 2020-07-03 09:15:27 +08:00
f80b6e72e0 [Fix] CQPluginMain 通过延迟加载来修复ApplicationBoot初始化失败的问题; 2020-07-03 09:11:27 +08:00
05e933838e Merge branch 'update-SpringCQ' 2020-07-03 08:20:18 +08:00
a87735d9e0 [Change] Main, SpringCQApplication 移除仅与SpringCQ相关的Spring相关代码, 转移到SpringCQApplication;
[Change] FrameworkManager 调整"registerFramework"返回值, 调整"shutdownAllFramework"的过程;
2020-07-03 08:19:21 +08:00
6ec99dbf17 Merge branch 'update-SpringCQ' into add-framework-interface
# Conflicts:
#	src/main/java/net/lamgc/cgj/Main.java
#	src/main/java/net/lamgc/cgj/bot/framework/coolq/SpringCQApplication.java
2020-07-03 08:02:50 +08:00
1599a5325a [Change] Framework 调整"getName"方法的默认实现;
[Change] Main 调整pluginMode启动方式;
[Change] SpringCQApplication 实现Framework接口;
2020-07-03 08:01:31 +08:00
3045b571a8 [Change] Main, SpringCQApplication 移除仅与SpringCQ相关的Spring相关代码, 转移到SpringCQApplication;
[Delete] CQPluginMain 移除注释信息;
2020-07-03 07:52:48 +08:00
5c2b6b4ee5 Merge branch 'update-SpringCQ' into add-framework-interface 2020-07-03 07:48:16 +08:00
c2e8a07500 [Change] ConsoleMain, MiraiMain 尝试为平台框架实现Framework接口;
[Change] Framework 补充Javadoc, 增加"getName"方法的默认方法体;
[Change] FrameworkManager 调整向frameworkThreadGroup发起中断的时机;
2020-07-03 00:46:23 +08:00
1b937953c3 [Add] Framework, FrameworkManager 增加框架统一管理接口; 2020-07-03 00:27:54 +08:00
553212e556 [Change] SpringCQApplication, Main 将SpringCQ启动部分迁移到SpringCQApplication内; 2020-07-03 00:23:56 +08:00
5383de7450 Merge remote-tracking branch 'origin/master' 2020-07-02 23:33:36 +08:00
9964205dc2 [Add] Pixiv搜索推荐候选接口.md 添加可用于优化搜索的接口文档; 2020-07-02 23:21:28 +08:00
394c3940e4 Merge remote-tracking branch 'origin/master' 2020-07-02 14:03:59 +08:00
d3d6f151d4 [Delete] application.properties 移除Properties版Application配置文件;
[Delete] CQConfig 移除不兼容的类;
[Add] application.yml 添加yml格式的Application配置文件;
[Change] Main 移除CQConfig类引用;
[Update] net.lz1998:spring-cq 升级依赖项版本(4.14.0.6 -> 4.15.0.1);
[Change] SpringCQMessageSenderFactory, CQPluginMain 使用较为妥协的方法实现SenderFactory;
2020-07-02 14:02:01 +08:00
62e3affef1 [Change] LocalHashCacheStore 调整内部类CacheObject的访问权; 2020-07-02 13:46:46 +08:00
51efc95c1c [Update] net.mamoe:mirai-core, net.mamoe:mirai-core-qqandroid 更新依赖库版本(1.0.2 -> 1.0.4); 2020-07-02 13:41:34 +08:00
d5c3a438b0 [Change] Pixiv预加载数据.md 更改文档标题; 2020-07-02 09:25:01 +08:00
792bfcb1bd [Add] Pixiv预加载数据.md 增加新的Pixiv接口文档; 2020-07-02 09:10:01 +08:00
cbd7db3570 Merge branch 'master' of github.com:LamGC/ContentGrabbingJi 2020-06-30 22:43:22 +08:00
467e7065fa [Update] net.lamgc:java-utils 更新依赖项版本(1.2.0_20200517.1-SNAPSHOT -> 1.3.1); 2020-06-30 22:40:39 +08:00
d2240e56fd [Change] README.md 调整格式; 2020-06-30 10:40:34 +08:00
eef9f285ca [Update] README.md 更新一份更规范的Readme; 2020-06-30 08:58:08 +08:00
27 changed files with 954 additions and 191 deletions

View File

@ -1,26 +1,35 @@
--- ---
name: Bug Report name: Bug 反馈
about: Use this template to feedback bugs. about: 使用这个模板反馈应用问题。
title: '' title: ''
labels: bug labels: bug
assignees: '' assignees: ''
--- ---
## Environmental information ## ## 环境信息 ##
OS(e.g: Windows 10 1909): 系统(例如: Windows 10 1909): ``
Java(e.g: Oracle Jdk 8.242): Java版本(例如: Oracle Jdk 8.242): ``
Issue version(versionTag or commitId): <!-- 如果直接使用发布版那么就填写发布版版本号v开头 -->
<!-- 如果你通过编译运行的方式运行开发版请你填写运行所使用的Commit Id -->
发生问题所在的版本: ``
## Problem description ## ## 问题描述 ##
// Describe the problem in as much detail as possible here <!-- 尽可能的清晰描述问题的信息 -->
## Expected behavior ## ## 预期行为 ##
// What will this function do under normal circumstances? <!-- 你觉得正常情况下应该会发生什么? -->
## Actual behavior ## ## 实际行为 ##
// But what does this feature actually look like? <!-- 实际上这个功能做了什么? -->
## Recurrence steps ## ## 复现步骤 ##
// What can we do to recreate this situation? <!-- 将复现步骤详细的写出,如果是偶发问题,可以写已知的,触发几率高的方法 -->
1. 1.
## 相关信息 ##
### 日志 ###
<!-- 如果日志涉及了问题,请务必将日志一同提交,这对排查问题非常有用 -->
```
```

View File

@ -0,0 +1,11 @@
---
name: 功能/想法 提议
about: 使用这个模板将你对应用的想法提出来,或许我们会采纳!
title: ''
labels: function, question
assignees: ''
---
<!-- 如果可以,尽可能的清晰、详细的表达你的想法 -->
<!-- 没关系的,我们会进一步向你交流以尝试了解你的想法! -->

View File

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

139
README.md
View File

@ -1,41 +1,118 @@
# ContentGrabbingJi # # ContentGrabbingJi - 色图姬 #
Pixiv爬虫一只同时也是一个机器人/插件! 一个以高性能、高效率为目标,多平台/框架支持、持续维护的Pixiv聊天机器人
## 支持的机器人平台 ## 色图姬存在的目的最初是作为**爬虫 + 机器人**的形式开发,在开发过程中逐渐以多聊天平台,高效率为目标进行。
- [Mirai](https://github.com/mamoe/mirai)
- [CoolQ](https://cqp.cc)(基于[`SpringCQ`](https://github.com/lz1998/spring-cq), 不支持多账号使用, 需要使用[`CQHttp`](https://cqhttp.cc/)插件)
## Usage ## ## 安装 ##
> 注意: 运行色图姬前, 你需要准备一个Pixiv账号的会话Cookie存储文件, 否则色图姬将无法运行. ### 通过Jar文件部署 ###
> 详见[PixivLoginProxyServer](https://github.com/LamGC/PixivLoginProxyServer)项目的[Readme](https://github.com/LamGC/PixivLoginProxyServer/blob/master/README.md). 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`, 然后设置如下内容:
```properties
# 该配置为全局配置文件, 当群组没有特定配置时, 将使用全局配置.
# 管理员QQ (必填)
admin.adminId=<管理员QQ号>
# 是否允许r18作品
image.allowR18=false
# 查询排行榜默认的长度(比如15就是发送1~15名的作品), 该选项请适当调整, 设置过长可能导致超出聊天平台的最长消息长度, 导致发送失败!
ranking.itemCountLimit=15
# 排行榜图片数量(比如排行榜长度为15, 可以设置前10名有图片, 后5名没有图片), 调整该配置可有效控制消息发送所需时间.
ranking.imageCountLimit=15
# 搜索结果缓存时间, 默认2小时, 单位毫秒
cache.searchBody.expire=7200000
# 搜索结果长度. 该选项请适当调整, 设置过长可能导致超出聊天平台的最长消息长度, 导致发送失败!
search.itemCountLimit=8
```
7. 配置完成后, 准备一台Redis服务端, 用于缓存数据.
8. Redis服务器准备好后, 使用命令启动色图姬:`java -jar <CGJ.jar> botMode -botDataDir <数据目录> -redisAddress <Redis服务器地址> [-proxy 代理服务器地址]`
9. 完成!好好享受!
### Arguments ### ### 通过Docker部署 ###
> ENV参数名为环境变量名, 用于给Docker容器提供设置方式. 使用Docker将可以更好的管理色图姬所使用的资源和管理色图姬的运行。
(正在完善中...)
- 通用参数 ## 使用 ##
- `-proxy` / `ENV: CGJ_PROXY`: (**可选**) 设置代理 ### 普通用户 ###
- 格式: `协议://地址:端口` 将色图姬部署完成,并且让色图姬在某个平台登录完成后,你就可以通过聊天平台向色图姬发起会话了!
- 示例: `socks5://127.0.0.1:1080` 使用 `.cgj` 向色图姬询问帮助信息!
- 机器人参数
- `-botDataDir` / `ENV: CGJ_BOT_DATA_DIR`: (**可选**) 设置`botMode`运行模式下机器人数据存储目录
- 格式: `路径`
- 示例: `./data`
- 默认: `./`
- `-redisAddress` / `ENV: CGJ_REDIS_URI`: (**必填, 计划支持可选**) Redis服务器地址
- 格式: `地址:端口`
- 示例: `127.0.0.1:6379`
> 例如以BotMode启动应用: `java -jar CGJ.jar botMode -proxy "socks5://127.0.0.1:1080 -redisAddress 127.0.0.1:6379` 另外,由于色图姬在开发过程中直接使用了原本应用在命令行中的参数解析工具,所以你需要了解一下色图姬命令的格式,
色图姬的命令格式为:
```bash
.cgj <命令> -<参数名> <参数值> ...
```
如果色图姬无法识别你的命令,那么它会发送一次帮助信息给你。
### Commands ### ### 管理员用户 ###
- `pluginMode`: CoolQ插件模式(依赖[酷Q机器人](https://cqp.cc/), 支持与CoolQ其他插件共存, 性能耗损大) 你应该注意到了在部署过程中你需要设置一个管理员QQ的配置色图姬支持通过命令来管理色图姬的运行。
- `botMode`: Mirai独立模式(机器人独立运行, 不支持与其他插件共存, 性能耗损小) 目前支持的管理员命令:
- `collectionDownload`: 收藏下载, 以原图画质下载Cookie所属账号的所有收藏作品 ```bash
- `getRecommends`: 将访问主页获得的推荐作品全部以原图画质下载 # 清除缓存(慎用)
- `getRankingIllust`: 以原图画质下载指定排行榜类型的全部作品 # 该操作将会清除Redis服务器内的所有数据, 以及色图姬下载到本地的所有图片缓存.
- `search`: 搜索指定内容并获取相关作品信息(不下载) .cgjadmin cleanCache
> 注意: 除去机器人模式外, 其他功能后续可能会出现改动. # 设置配置项
# 如果不使用group参数, 则设置全局配置
# 注意: 配置项设置后需要使用`.cgjadmin saveProperties`才会保存到文件中,
# 如不保存, 则仅能在本次运行中生效(或使用`.cgjadmin loadProperties`重新加载后失效).
.cgjadmin setProperty <-key 配置项名> <-value 配置项新值> [-group 指定群组]
# 查询配置项
# 如果不使用group参数, 则查询全局配置
.cgjadmin getProperty <-key 配置项名> [-group 指定群组]
# 保存所有配置
.cgjadmin saveProperties
# 读取所有配置
# 使用 reload 参数将会重载所有配置, 而不是覆盖读取
.cgjadmin loadProperties [-reload]
# 运行定时更新任务
# 可指定要更新数据的日期
.cgjadmin runUpdateTask [-date yyyy-MM-dd]
# 增加群组作品推送
# 如果增加了original参数, 则图片为原图发送
# 如果不指定group参数, 则群组为命令发送所在群组
# 最长发送时间 = 最短发送时间 + 随机时间范围
.cgjadmin addPushGroup [-group 指定群组号] [-minTime 最短发送时间] [-floatTime 随机时间范围] [-rankingStart 排行榜起始排名]
[-rankingStop 排行榜结束排名] [-mode 排行榜模式] [-type 排行榜类型] [-original]
# 删除群组推送功能
# 如果不指定group参数, 则群组为命令发送所在群组
.cgjadmin removePushGroup [-group 指定群组号]
# 加载作品推送配置
.cgjadmin loadPushList
# 保存作品推送配置
.cgjadmin savePushList
# 获取被报告的作品列表
# 该命令会返回被其他用户报告其存在问题的作品列表
.cgjadmin getReportList
# 解封被报告的作品
.cgjadmin unBanArtwork <-id 被ban作品的Id>
```
## 贡献 ##
向色图姬贡献不一定需要编程知识,向色图姬项目提出意见,反馈问题同样会为色图姬项目提供很大的帮助!
如果你在使用色图姬的过程中遇到了Bug可以通过色图姬项目的**Issues**使用[Bug反馈模板](https://github.com/LamGC/ContentGrabbingJi/issues/new?assignees=&labels=bug&template=Bug_Report.md&title=)向色图姬提供Bug信息。
如果是为色图姬提供一些新功能想法或者对色图姬有什么意见则可以直接通过Issues发起讨论。
如果你会Java开发又想为色图姬提供一些新功能可以通过Fork仓库的方法实现后发起PR合并到色图姬项目中
向色图姬贡献代码需要遵循一些贡献事项如果你的代码不符合这些事项PR有可能会被关闭
> 注意色图姬的初衷并没有任何恶意的意图如果尝试向色图姬提供恶意功能或代码PR将会被拒绝、关闭。
## LICENSE ## ## LICENSE ##
本项目基于 `GNU Affero General Public License 3.0` 开源许可协议开源, 本项目基于 `GNU Affero General Public License 3.0` 开源许可协议开源,

View File

@ -0,0 +1,47 @@
## 搜索推荐接口 ##
### 说明 ###
可用于优化搜索内容。
### 接口地址 ###
```
GET https://www.pixiv.net/rpc/cps.php?
```
- 是否需要登录: `否`
- 是否为Pixiv标准接口返回格式: `否`
- 是否需要Referer请求头: `是`
> 补充: Referer请求头只要是Pixiv的就可以了.
### 参数 ###
Url参数:
- `keyword`: 搜索内容
> 注意: 搜索内容需要进行Url编码空格要转换成`%20`而不是`+`
### 请求示例 ###
```
GET https://www.pixiv.net/rpc/cps.php?keyword=幸运星
```
### 返回数据 ###
#### 数据示例 ####
```json
{
"candidates":[
{
"tag_name":"\u3089\u304d\u2606\u3059\u305f",
"access_count":"68286498",
"tag_translation":"\u5e78\u8fd0\u661f",
"type":"tag_translation"
}, // ...
]
}
```
#### 字段说明 ####
- `candidates`: (`Object[]`) 搜索推荐候选列表
- `tag_name`: (`string`) 推荐词原名
- `access_count`: (`string` -> `number`) 推荐词访问量
- `tag_translation`: (`string`) 推荐词对应翻译名
- `type`: (`string`) 推荐词类型
- `tag_translation`: 标签翻译信息
- `prefix`: 前缀

View File

@ -0,0 +1,319 @@
## Pixiv预加载数据 ##
### 说明 ###
作品预加载数据仅在加载作品页面时存在,处理后删除。
### 接口地址 ###
```
GET https://www.pixiv.net/artworks/{IllustId}
```
- 是否需要登录: `是`
- 是否为Pixiv标准接口返回格式: `否`
- 是否需要Referer请求头: `否`
### 参数 ###
Url参数:
- `IllustId`: 作品Id
### 请求示例 ###
```
GET https://www.pixiv.net/artworks/82647306
```
### 返回数据 ###
> 注意: 该接口返回HTML格式数据并不是JSON格式数据。
预加载数据需要对返回的Html数据进行解析路径如下
- CSS Select: meta#meta-preload-data
- html>head>meta#meta-preload-data
获得标签后,获取`content`属性即可获得预加载数据内容
#### 数据示例 ####
```json
{
"timestamp":"2020-07-01T11:32:30+09:00",
"illust":{
"82647306":{
"illustId":"82647306",
"illustTitle":"水着キャルちゃん!",
"illustComment":"水着のキャルちゃんはかわいいぞ!!",
"id":"82647306",
"title":"水着キャルちゃん!",
"description":"水着のキャルちゃんはかわいいぞ!!",
"illustType":0,
"createDate":"2020-06-29T12:28:06+00:00",
"uploadDate":"2020-06-29T12:28:06+00:00",
"restrict":0,
"xRestrict":0,
"sl":2,
"urls":{
"mini":"https://i.pximg.net/c/48x48/img-master/img/2020/06/29/21/28/06/82647306_p0_square1200.jpg",
"thumb":"https://i.pximg.net/c/250x250_80_a2/img-master/img/2020/06/29/21/28/06/82647306_p0_square1200.jpg",
"small":"https://i.pximg.net/c/540x540_70/img-master/img/2020/06/29/21/28/06/82647306_p0_master1200.jpg",
"regular":"https://i.pximg.net/img-master/img/2020/06/29/21/28/06/82647306_p0_master1200.jpg",
"original":"https://i.pximg.net/img-original/img/2020/06/29/21/28/06/82647306_p0.jpg"
},
"tags":{
"authorId":"55859246",
"isLocked":false,
"tags":[
{
"tag":"プリンセスコネクト!Re:Dive",
"locked":true,
"deletable":false,
"userId":"55859246",
"translation":{
"en":"公主连结Re:Dive"
},
"userName":"秋鳩むぎ"
}, // ...
],
"writable":true
},
"alt":"#プリンセスコネクト!Re:Dive 水着キャルちゃん! - 秋鳩むぎ的插画",
"storableTags":[
"_bee-JX46i",
"nAtxkwJ5Sy",
"q303ip6Ui5"
],
"userId":"55859246",
"userName":"秋鳩むぎ",
"userAccount":"pigeonwheat",
"userIllusts":{
"82647306":{
"illustId":"82647306",
"illustTitle":"水着キャルちゃん!",
"id":"82647306",
"title":"水着キャルちゃん!",
"illustType":0,
"xRestrict":0,
"restrict":0,
"sl":2,
"url":"https://i.pximg.net/c/250x250_80_a2/img-master/img/2020/06/29/21/28/06/82647306_p0_square1200.jpg",
"description":"水着のキャルちゃんはかわいいぞ!!",
"tags":[
"プリンセスコネクト!Re:Dive",
"キャル(プリコネ)",
"おへそ"
],
"userId":"55859246",
"userName":"秋鳩むぎ",
"width":2000,
"height":3000,
"pageCount":1,
"isBookmarkable":true,
"bookmarkData":null,
"alt":"#プリンセスコネクト!Re:Dive 水着キャルちゃん! - 秋鳩むぎ的插画",
"isAdContainer":false,
"titleCaptionTranslation":{
"workTitle":null,
"workCaption":null
},
"createDate":"2020-06-29T21:28:06+09:00",
"updateDate":"2020-06-29T21:28:06+09:00",
"seriesId":null,
"seriesTitle":null
}
},
"likeData":false,
"width":2000,
"height":3000,
"pageCount":1,
"bookmarkCount":39,
"likeCount":31,
"commentCount":2,
"responseCount":0,
"viewCount":239,
"isHowto":false,
"isOriginal":false,
"imageResponseOutData":[
],
"imageResponseData":[
],
"imageResponseCount":0,
"pollData":null,
"seriesNavData":null,
"descriptionBoothId":null,
"descriptionYoutubeId":null,
"comicPromotion":null,
"fanboxPromotion":null,
"contestBanners":[
],
"isBookmarkable":true,
"bookmarkData":null,
"contestData":null,
"zoneConfig":{
"responsive":{
"url":"https://pixon.ads-pixiv.net/show?zone_id=illust_responsive&amp;format=js&amp;s=1&amp;up=0&amp;a=22&amp;ng=w&amp;l=zh&amp;uri=%2Fartworks%2F_PARAM_&amp;is_spa=1&amp;K=59bba275c645c&amp;ab_test_digits_first=32&amp;yuid=NDJ3gQk&amp;suid=Pggb9mua3yznnr7lz&amp;num=5efbf5be273&amp;t=_bee-JX46i&amp;t=b8b4-hqot7&amp;t=kY01H5r3Pd"
},
"rectangle":{
"url":"https://pixon.ads-pixiv.net/show?zone_id=illust_rectangle&amp;format=js&amp;s=1&amp;up=0&amp;a=22&amp;ng=w&amp;l=zh&amp;uri=%2Fartworks%2F_PARAM_&amp;is_spa=1&amp;K=59bba275c645c&amp;ab_test_digits_first=32&amp;yuid=NDJ3gQk&amp;suid=Pggb9mua42776dfuu&amp;num=5efbf5be810&amp;t=_bee-JX46i&amp;t=b8b4-hqot7&amp;t=kY01H5r3Pd"
},
"500x500":{
"url":"https://pixon.ads-pixiv.net/show?zone_id=bigbanner&amp;format=js&amp;s=1&amp;up=0&amp;a=22&amp;ng=w&amp;l=zh&amp;uri=%2Fartworks%2F_PARAM_&amp;is_spa=1&amp;K=59bba275c645c&amp;ab_test_digits_first=32&amp;yuid=NDJ3gQk&amp;suid=Pggb9mua442sjsueo&amp;num=5efbf5be568&amp;t=_bee-JX46i&amp;t=b8b4-hqot7&amp;t=kY01H5r3Pd"
},
"header":{
"url":"https://pixon.ads-pixiv.net/show?zone_id=header&amp;format=js&amp;s=1&amp;up=0&amp;a=22&amp;ng=w&amp;l=zh&amp;uri=%2Fartworks%2F_PARAM_&amp;is_spa=1&amp;K=59bba275c645c&amp;ab_test_digits_first=32&amp;yuid=NDJ3gQk&amp;suid=Pggb9mua45spzoimt&amp;num=5efbf5be155&amp;t=_bee-JX46i&amp;t=b8b4-hqot7&amp;t=kY01H5r3Pd"
},
"footer":{
"url":"https://pixon.ads-pixiv.net/show?zone_id=footer&amp;format=js&amp;s=1&amp;up=0&amp;a=22&amp;ng=w&amp;l=zh&amp;uri=%2Fartworks%2F_PARAM_&amp;is_spa=1&amp;K=59bba275c645c&amp;ab_test_digits_first=32&amp;yuid=NDJ3gQk&amp;suid=Pggb9mua47f9zcoim&amp;num=5efbf5be400&amp;t=_bee-JX46i&amp;t=b8b4-hqot7&amp;t=kY01H5r3Pd"
},
"expandedFooter":{
"url":"https://pixon.ads-pixiv.net/show?zone_id=multiple_illust_viewer&amp;format=js&amp;s=1&amp;up=0&amp;a=22&amp;ng=w&amp;l=zh&amp;uri=%2Fartworks%2F_PARAM_&amp;is_spa=1&amp;K=59bba275c645c&amp;ab_test_digits_first=32&amp;yuid=NDJ3gQk&amp;suid=Pggb9mua4928ct0yw&amp;num=5efbf5be471&amp;t=_bee-JX46i&amp;t=b8b4-hqot7&amp;t=kY01H5r3Pd"
},
"logo":{
"url":"https://pixon.ads-pixiv.net/show?zone_id=logo_side&amp;format=js&amp;s=1&amp;up=0&amp;a=22&amp;ng=w&amp;l=zh&amp;uri=%2Fartworks%2F_PARAM_&amp;is_spa=1&amp;K=59bba275c645c&amp;ab_test_digits_first=32&amp;yuid=NDJ3gQk&amp;suid=Pggb9mua4aqu6i4sr&amp;num=5efbf5be844&amp;t=_bee-JX46i&amp;t=b8b4-hqot7&amp;t=kY01H5r3Pd"
}
},
"extraData":{
"meta":{
"title":"#プリンセスコネクト!Re:Dive 水着キャルちゃん! - 秋鳩むぎ的插画 - pixiv",
"description":"この作品 「水着キャルちゃん!」 は 「プリンセスコネクト!Re:Dive」「キャル(プリコネ)」 等のタグがつけられた「秋鳩むぎ」さんのイラストです。 「水着のキャルちゃんはかわいいぞ!!」",
"canonical":"https://www.pixiv.net/artworks/82647306",
"alternateLanguages":{
"ja":"https://www.pixiv.net/artworks/82647306",
"en":"https://www.pixiv.net/en/artworks/82647306"
},
"descriptionHeader":"本作「水着キャルちゃん!」为附有「プリンセスコネクト!Re:Dive」「キャル(プリコネ)」等标签的插画。",
"ogp":{
"description":"水着のキャルちゃんはかわいいぞ!!",
"image":"https://embed.pixiv.net/decorate.php?illust_id=82647306",
"title":"#プリンセスコネクト!Re:Dive 水着キャルちゃん! - 秋鳩むぎ的插画 - pixiv",
"type":"article"
},
"twitter":{
"description":"水着のキャルちゃんはかわいいぞ!!",
"image":"https://embed.pixiv.net/decorate.php?illust_id=82647306",
"title":"水着キャルちゃん!",
"card":"summary_large_image"
}
}
},
"titleCaptionTranslation":{
"workTitle":null,
"workCaption":null
}
}
},
"user":{
"55859246":{
"userId":"55859246",
"name":"秋鳩むぎ",
"image":"https://i.pximg.net/user-profile/img/2020/06/29/21/20/14/18907670_b3f87d819f705ec418f120cd57f9dc41_50.jpg",
"imageBig":"https://i.pximg.net/user-profile/img/2020/06/29/21/20/14/18907670_b3f87d819f705ec418f120cd57f9dc41_170.jpg",
"premium":false,
"isFollowed":false,
"isMypixiv":false,
"isBlocking":false,
"background":null,
"partial":0
}
}
}
```
#### 字段说明 ####
- `timestamp`: (`string`) 请求时间
- `illust`: (`Object`) 作品预加载信息
- `{illustId}`: 作品ID(跟页面请求的IllustId一样)
- `illustId`: (`string` -> `number`) 作品Id
- `illustTitle`: (`string`) 作品标题
- `illustComment`: (`string`) 作品说明
- `id`: (`string` -> `number`) 与`illustId`一致, 猜测是以兼容旧版本为目录而存在
- `title`: (`string`) 与`illustTitle`一致, 猜测是以兼容旧版本为目录而存在
- `description`: (`string`) 作品说明
- `illustType`: (`number`) 作品类型
- `0`: 插画作品
- `1`: 漫画作品
- `2`: 动图作品
- `createDate`: (`string`) 作品创建时间(或者是完成时间?)
- `updateDate`: (`string`) 作品上传时间
- `restrict`: (`number`) 作品限制级(意义不明, 可能是兼容性问题?)?
- `xRestrict`: (`number`) 作品是否为限制级, 基本准确, 少部分不一定(看Pixiv审核怎么理解了)
- `0`: 非限制级内容(即非R18作品)
- `1`: 限制级内容(即R18作品)
- `sl`: (`number`) 不明?
- `urls`: (`string`) 作品图片链接, 需要`Referer`请求头
- `mini`: (`string`) 小尺寸预览图
- `thumb`: (`string`) 小尺寸预览图
- `small`: (`string`) 小尺寸预览图
- `regular`: (`string`) 经压缩,没啥画质损失的原尺寸预览图
- `original`: (`string`) 原图
- `tags`: (`Object`) 作品标签信息
- `authorId`: (`string` -> `number`) 作者用户Id
- `isLocked`: (`boolean`) 标签是否锁定(即不可被访客更改)
- `tags`: (`Object[]`) 标签信息数组
- `tag`: (`string`) 标签原始名
- `locked`: (`boolean`) 标签是否不可更改
- `deletable`: (`boolean`) 标签能否被删除?
- `userId`: (`string` -> `number`) 用户Id
- `translation`: (`Object`) 标签翻译
- `{语种}`: 翻译名
- `userName`: (`string`) 用户名
- `alt`: (`string`) 简略介绍信息(在图片加载失败时可提供给`img`标签使用)
- `storableTags`: (`string[]`) 不明?
- `userId`: (`string` -> `number`) 作者用户Id
- `userName`: (`string`) 作者用户名
- `userAccount`: (`string`) 作者登录名
- `userIllusts`: (`Object`) 作品信息?
- `{IllustId}`: 与请求IllustId一样
- (请转到Pixiv作品信息获取接口.md)
- `likeData`: (`boolean?`) 不明?
- `width`: (`number`) 作品长度
- `height`: (`number`) 作品高度
- `pageCount`: (`number`) 作品页数
- `bookmarkCount`: (`number`) 作品公开的收藏数
- `likeCount`: (`number`) 作品喜欢(点赞)数
- `commentCount`: (`number`) 作品评论数
- `responseCount`: (`number`) 作品响应数?
- `viewCount`: (`number`) 作品阅览数
- `isHowto`: (`boolean`) 不明?
- `isOriginal`: (`boolean`) 不明?
- `imageResponseOutData`: (`Unknown[]`) 不明?
- `imageResponseData`: (`Unknown[]`) 不明?
- `imageResponseCount`: (`number`) 不明?
- `pollData`: (`Unknown`) 不明?
- `seriesNavData`: (`Unknown`) 不明?
- `descriptionBoothId`: (`Unknown`) 不明?
- `descriptionYoutubeId`: (`Unknown`) 不明?
- `comicPromotion`: (`Unknown`) 不明?
- `fanboxPromotion`: (`Unknown`) 不明?
- `contestBanners`: (`Unknown[]`) 不明?
// TODO 待补充
- `isBookmarkable`: (`boolean`) 不明?
- `bookmarkData`: (`Unknown`) 不明?
- `contestData`: (`Unknown`) 不明?
- `zoneConfig`: (`Object`) 猜测是广告信息?
- (基本不用, 忽略...)
- `extraData`: (`Object`) 扩展数据
- `meta`: (`Object`) 元数据
- `title`: (`string`) 网页标题
- `description`: (`string`) Pixiv生成的作品说明
- `canonical`: (`string`) 作品页面链接
- `alternateLanguages`: (`Object`) 不同语言的作品页面链接
- `{语种}`: (`string`) 对应语种的作品链接
- `descriptionHeader`: (`string`) 说明文档(不过似乎是对应了会话所属账号的语种?)
- `ogp`: (`Object`) 猜测是某平台的分享数据?
- `description`: (`string`) 说明内容
- `image`: (`string`) 预览图链接
- `title`: (`string`) 分享标题
- `type`: (`string`) 分享类型?
- `twitter`: (`Object`)
- `description`: (`string`) 说明内容
- `image`: (`string`) 预览图链接
- `title`: (`string`) 分享标题
- `card`: (`string`) 分享类型?
- `titleCaptionTranslation`: (`Object`) 不明?
- `workTitle`: (`Unknown`) 不明?
- `workCaption`: (`Unknown`) 不明?
- `user`: (`Object`) 作者预加载信息
- `{userId}`: 可通过`illust.{illustId}.userId`获得
- `userId`: (`string` -> `number`) 作者用户Id
- `name`: (`string`) 作者用户名
- `image`: (`string`) 作者用户头像(小尺寸)
- `imageBig`: (`string`) 作者用户头像(大尺寸)
- `premium`: (`boolean`) 作者是否为Pixiv会员
- `isFollowed`: (`boolean`) 当前会话用户是否已关注
- `isMypixiv`: (`boolean`) 是否为当前会话本人?
- `isBlocking`: (`boolean`) 是否正在被封禁
- `background`: (`Object`) 背景图片?
- `partial`: (`number`) 不明?

View File

@ -6,7 +6,7 @@
<groupId>net.lamgc</groupId> <groupId>net.lamgc</groupId>
<artifactId>ContentGrabbingJi</artifactId> <artifactId>ContentGrabbingJi</artifactId>
<version>2.5.2-20200630.2-SNAPSHOT</version> <version>2.5.2-20200709.1-SNAPSHOT</version>
<licenses> <licenses>
<license> <license>
@ -27,7 +27,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding> <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<mirai.CoreVersion>1.0.2</mirai.CoreVersion> <mirai.CoreVersion>1.0.4</mirai.CoreVersion>
<mirai.JaptVersion>1.1.1</mirai.JaptVersion> <mirai.JaptVersion>1.1.1</mirai.JaptVersion>
<kotlin.version>1.3.71</kotlin.version> <kotlin.version>1.3.71</kotlin.version>
<ktor.version>1.3.2</ktor.version> <ktor.version>1.3.2</ktor.version>
@ -94,7 +94,7 @@
<dependency> <dependency>
<groupId>net.lamgc</groupId> <groupId>net.lamgc</groupId>
<artifactId>java-utils</artifactId> <artifactId>java-utils</artifactId>
<version>1.2.0_20200517.1-SNAPSHOT</version> <version>1.3.1</version>
</dependency> </dependency>
<dependency> <dependency>
@ -121,7 +121,7 @@
<dependency> <dependency>
<groupId>net.lz1998</groupId> <groupId>net.lz1998</groupId>
<artifactId>spring-cq</artifactId> <artifactId>spring-cq</artifactId>
<version>4.14.0.6</version> <version>4.15.0.1</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>ch.qos.logback</groupId> <groupId>ch.qos.logback</groupId>

View File

@ -7,8 +7,9 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import net.lamgc.cgj.bot.boot.ApplicationBoot; import net.lamgc.cgj.bot.boot.ApplicationBoot;
import net.lamgc.cgj.bot.boot.BotGlobal; import net.lamgc.cgj.bot.boot.BotGlobal;
import net.lamgc.cgj.bot.framework.FrameworkManager;
import net.lamgc.cgj.bot.framework.cli.ConsoleMain; import net.lamgc.cgj.bot.framework.cli.ConsoleMain;
import net.lamgc.cgj.bot.framework.coolq.CQConfig; 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.PixivDownload; import net.lamgc.cgj.pixiv.PixivDownload;
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder; import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
@ -25,20 +26,15 @@ import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.fileupload.util.Streams; import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
@SpringBootApplication
public class Main { public class Main {
private final static Logger log = LoggerFactory.getLogger(Main.class); private final static Logger log = LoggerFactory.getLogger(Main.class);
@ -93,29 +89,29 @@ public class Main {
@Command @Command
public static void botMode(@Argument(name = "args", force = false) String argsStr) { public static void botMode(@Argument(name = "args", force = false) String argsStr) {
MiraiMain main = new MiraiMain(); try {
main.init(); FrameworkManager.registerFramework(new MiraiMain()).join();
main.close(); } catch (InterruptedException ignored) {
}
} }
@Command @Command
public static void consoleMode() throws IOException { public static void consoleMode() {
ConsoleMain.start(); try {
FrameworkManager.registerFramework(new ConsoleMain()).join();
} catch (InterruptedException ignored) {
}
} }
@Command @Command
public static void pluginMode(@Argument(name = "args", force = false) String argsStr) { public static void pluginMode(@Argument(name = "args", force = false) String argsStr) {
log.info("酷Q机器人根目录: {}", BotGlobal.getGlobal().getDataStoreDir().getPath()); try {
CQConfig.init(); FrameworkManager.registerFramework(new SpringCQApplication()).join();
Pattern pattern = Pattern.compile("/\\s*(\".+?\"|[^:\\s])+((\\s*:\\s*(\".+?\"|[^\\s])+)|)|(\".+?\"|[^\"\\s])+"); } catch (InterruptedException ignored) {
Matcher matcher = pattern.matcher(Strings.nullToEmpty(argsStr));
ArrayList<String> argsList = new ArrayList<>();
while (matcher.find()) {
argsList.add(matcher.group());
} }
String[] args = new String[argsList.size()];
argsList.toArray(args);
SpringApplication.run(Main.class, args);
} }
@Command @Command

View File

@ -4,7 +4,6 @@ import com.google.common.base.Throwables;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.*; import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
@ -23,7 +22,7 @@ public class RandomIntervalSendTimer extends TimerTask {
private final long time; private final long time;
private final int floatTime; private final int floatTime;
private final AtomicBoolean loop = new AtomicBoolean(); private final AtomicBoolean loop = new AtomicBoolean();
private final AtomicBoolean start = new AtomicBoolean(); private final AtomicBoolean running = new AtomicBoolean();
private final String hashId = Integer.toHexString(this.hashCode()); private final String hashId = Integer.toHexString(this.hashCode());
@ -88,7 +87,6 @@ public class RandomIntervalSendTimer extends TimerTask {
this.sender = sender; this.sender = sender;
this.time = time; this.time = time;
this.floatTime = floatTime; this.floatTime = floatTime;
timerMap.put(timerId, this);
if(startNow) { if(startNow) {
start(loop); start(loop);
} }
@ -108,21 +106,18 @@ public class RandomIntervalSendTimer extends TimerTask {
Date nextDate = new Date(); Date nextDate = new Date();
nextDate.setTime(nextDate.getTime() + nextDelay); nextDate.setTime(nextDate.getTime() + nextDelay);
log.info("定时器 {} 下一延迟: {}ms ({})", hashId, nextDelay, nextDate); log.info("定时器 {} 下一延迟: {}ms ({})", hashId, nextDelay, nextDate);
if(start.get()) { if(running.get()) {
try { reset();
Field state = this.getClass().getSuperclass().getDeclaredField("state"); return;
state.setAccessible(true);
state.setInt(this, 0);
state.setAccessible(false);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
return;
}
} }
start.set(true); running.set(true);
timer.schedule(this, nextDelay); timer.schedule(this, nextDelay);
} }
public void reset() {
timerMap.put(timerId, (RandomIntervalSendTimer) clone());
}
@Override @Override
public void run() { public void run() {
log.info("定时器 {} 开始执行...(Sender: {}@{})", this.hashId, sender.getClass().getSimpleName(), sender.hashCode()); log.info("定时器 {} 开始执行...(Sender: {}@{})", this.hashId, sender.getClass().getSimpleName(), sender.hashCode());
@ -145,7 +140,7 @@ public class RandomIntervalSendTimer extends TimerTask {
*/ */
@Override @Override
public boolean cancel() { public boolean cancel() {
start.set(false); running.set(false);
loop.set(false); loop.set(false);
return super.cancel(); return super.cancel();
} }
@ -158,4 +153,18 @@ public class RandomIntervalSendTimer extends TimerTask {
timerMap.remove(this.timerId); timerMap.remove(this.timerId);
} }
/**
* 克隆一个参数完全一样的TimerTask对象.
* @return 返回对象不同, 参数相同的TimerTask对象.
*/
@Override
@SuppressWarnings("MethodDoesntCallSuperMethod")
public Object clone() {
RandomIntervalSendTimer newTimerTask = new RandomIntervalSendTimer(
this.timerId, this.sender,
time, floatTime,
running.get(), loop.get());
this.destroy();
return newTimerTask;
}
} }

View File

@ -158,7 +158,7 @@ public class LocalHashCacheStore<T> implements CacheStore<T>, Cleanable {
expireKeySet.forEach(cache::remove); expireKeySet.forEach(cache::remove);
} }
public static class CacheObject<T> implements Comparable<CacheObject<T>> { private static class CacheObject<T> implements Comparable<CacheObject<T>> {
private final AtomicReference<T> value; private final AtomicReference<T> value;
private final AtomicReference<Date> expire; private final AtomicReference<Date> expire;

View File

@ -26,7 +26,6 @@ import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -40,15 +39,13 @@ public class BotEventHandler implements EventHandler {
private final static Logger log = LoggerFactory.getLogger(BotEventHandler.class); private final static Logger log = LoggerFactory.getLogger(BotEventHandler.class);
private final static Map<Long, AtomicBoolean> muteStateMap = new Hashtable<>();
/** /**
* 消息事件执行器 * 消息事件执行器
*/ */
private final static EventExecutor executor = new EventExecutor(new TimeLimitThreadPoolExecutor( private final static EventExecutor executor = new EventExecutor(new TimeLimitThreadPoolExecutor(
180000, // 3minThr 180000, // 3min limit
Math.max(Runtime.getRuntime().availableProcessors(), 4), Math.max(Runtime.getRuntime().availableProcessors(), 4), // 4 ~ processors
Math.min(Math.max(Runtime.getRuntime().availableProcessors(), 4), 32), Math.min(Math.max(Runtime.getRuntime().availableProcessors() * 2, 8), 32),// (8 ~ processors * 2) ~ 32
30L, 30L,
TimeUnit.SECONDS, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1536), new LinkedBlockingQueue<>(1536),
@ -167,9 +164,6 @@ public class BotEventHandler implements EventHandler {
log.debug(event.toString()); log.debug(event.toString());
if(mismatch(msg)) { if(mismatch(msg)) {
return; return;
} else if(isMute(event.getFromGroup())) {
log.debug("机器人已被禁言, 忽略请求.");
return;
} }
Pattern pattern = Pattern.compile("/\\s*(\".+?\"|[^:\\s])+((\\s*:\\s*(\".+?\"|[^\\s])+)|)|(\".+?\"|[^\"\\s])+"); Pattern pattern = Pattern.compile("/\\s*(\".+?\"|[^:\\s])+((\\s*:\\s*(\".+?\"|[^\\s])+)|)|(\".+?\"|[^\"\\s])+");
@ -236,7 +230,7 @@ public class BotEventHandler implements EventHandler {
} }
} }
long processTime = System.currentTimeMillis() - time; long processTime = System.currentTimeMillis() - time;
if(!Objects.isNull(result) && result instanceof String && !isMute(event.getFromGroup())) { if(!Objects.isNull(result) && result instanceof String) {
try { try {
int sendResult = event.sendMessage((String) result); int sendResult = event.sendMessage((String) result);
if (sendResult < 0) { if (sendResult < 0) {
@ -248,8 +242,6 @@ public class BotEventHandler implements EventHandler {
} catch (Exception e) { } catch (Exception e) {
log.error("发送消息时发生异常", e); log.error("发送消息时发生异常", e);
} }
} else if(isMute(event.getFromGroup())) {
log.warn("命令反馈时机器人已被禁言, 跳过反馈.");
} }
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,
@ -266,45 +258,4 @@ public class BotEventHandler implements EventHandler {
return !message.startsWith(COMMAND_PREFIX) && !message.startsWith(ADMIN_COMMAND_PREFIX); return !message.startsWith(COMMAND_PREFIX) && !message.startsWith(ADMIN_COMMAND_PREFIX);
} }
/**
* 查询某群组中Bot是否被禁言
* @param groupId 待查询的群组号
* @return 如果被禁言, 返回true, 如果未被禁言或禁言情况未知, 返回false
*/
private static boolean isMute(long groupId) {
Boolean mute = isMute(groupId, false);
return mute != null && mute;
}
/**
* 查询某群是否被禁言.
* @param groupId 群组Id
* @param rawValue 是否返回原始值(当没有该群状态, 且本参数为true时, 将返回null)
* @return 返回状态值, 如无该群禁言记录且rawValue = true, 则返回null
*/
public static Boolean isMute(long groupId, boolean rawValue) {
if(groupId <= 0) {
return false;
}
AtomicBoolean state = muteStateMap.get(groupId);
if(state == null && rawValue) {
return null;
}
return state != null && state.get();
}
/**
* 设置机器人禁言状态.
* <p>设置该项可防止因机器人在禁言期间反馈请求导致被封号.</p>
* @param mute 如果被禁言, 传入true
*/
public static void setMuteState(long groupId, boolean mute) {
if(!muteStateMap.containsKey(groupId)) {
muteStateMap.put(groupId, new AtomicBoolean(mute));
} else {
muteStateMap.get(groupId).set(mute);
}
log.warn("群组 {} 机器人禁言状态已变更: {}", groupId, mute ? "已禁言" : "已解除");
}
} }

View File

@ -57,7 +57,7 @@ public abstract class MessageEvent implements EventObject, MessageSender {
@Override @Override
public String toString() { public String toString() {
return this.getClass().getSimpleName() + "@" + this.hashCode() + "{" + return this.getClass().getSimpleName() + "@" + Integer.toHexString(this.hashCode()) + "{" +
"fromGroup=" + getFromGroup() + "fromGroup=" + getFromGroup() +
", fromQQ=" + getFromQQ() + ", fromQQ=" + getFromQQ() +
", message='" + getMessage() + '\'' + ", message='" + getMessage() + '\'' +

View File

@ -0,0 +1,41 @@
package net.lamgc.cgj.bot.framework;
public interface Framework {
/**
* 框架初始化方法
* @param resources 框架所分配到的资源.
* @throws Exception 当框架抛出异常时, 将不会继续运行框架.
* @see FrameworkResources
*/
void init(FrameworkResources resources) throws Exception;
/**
* 框架运行方法
* @throws Exception 当框架抛出异常时, 将会终止框架的所有活动.
*/
void run() throws Exception;
/**
* 关闭框架
* @throws Exception 即使该方法抛出异常, {@link FrameworkManager}依然会尝试向框架所属的线程发起中断, 以试图清除框架资源.
*/
void close() throws Exception;
/**
* 获取框架标识名.
* <p>可根据需要自行调整框架标识名.</p>
* @return 返回标识名.
*/
default String getIdentify() {
return this.getClass().getSimpleName() + "@" + Integer.toHexString(this.hashCode());
}
/**
* 获取框架名称.
* <p>框架名称不可更改.</p>
* @return 返回框架名称.
*/
String getFrameworkName();
}

View File

@ -0,0 +1,75 @@
package net.lamgc.cgj.bot.framework;
import org.slf4j.Logger;
import java.util.*;
import java.util.regex.Pattern;
public final class FrameworkManager {
private FrameworkManager() {}
private final static Map<Framework, FrameworkResources> resourcesMap = new HashMap<>();
private final static ThreadGroup frameworkRootGroup = new ThreadGroup("FrameworkRootGroup");
static {
Runtime.getRuntime()
.addShutdownHook(new Thread(FrameworkManager::shutdownAllFramework, "FrameworkManager-Shutdown"));
}
public static Thread registerFramework(Framework framework) {
checkFramework(framework);
FrameworkResources resources = new FrameworkResources(framework);
resourcesMap.put(framework, resources);
Thread frameworkThread = new Thread(resources.getFrameworkThreadGroup(),
() -> FrameworkManager.runFramework(framework), "FrameworkThread-" + framework.getIdentify());
frameworkThread.start();
return frameworkThread;
}
private static final Pattern FRAMEWORK_NAME_CHECK_PATTERN = Pattern.compile("^[A-Za-z0-9_\\-$]+$");
private static void checkFramework(Framework framework) {
if(!FRAMEWORK_NAME_CHECK_PATTERN.matcher(framework.getFrameworkName()).matches()) {
throw new IllegalStateException("Invalid Framework Name: " + framework.getFrameworkName());
}
}
public static Set<Framework> frameworkSet() {
return new HashSet<>(resourcesMap.keySet());
}
public static void shutdownAllFramework() {
for (Framework framework : resourcesMap.keySet()) {
FrameworkResources frameworkResources = resourcesMap.get(framework);
Logger frameworkLogger = frameworkResources.getLogger();
try {
frameworkLogger.info("正在关闭框架...");
framework.close();
frameworkLogger.info("框架已关闭.");
frameworkResources.getFrameworkThreadGroup().interrupt();
resourcesMap.remove(framework);
} catch(Throwable e) {
frameworkLogger.error("退出框架时发生异常", e);
}
}
}
static ThreadGroup getFrameworkRootGroup() {
return frameworkRootGroup;
}
private static void runFramework(Framework framework) {
FrameworkResources frameworkResources = resourcesMap.get(framework);
try {
framework.init(frameworkResources);
framework.run();
} catch(Throwable e) {
frameworkResources.getLogger().error("框架未捕获异常, 导致异常退出.", e);
} finally {
frameworkResources.getFrameworkThreadGroup().interrupt();
}
}
}

View File

@ -0,0 +1,35 @@
package net.lamgc.cgj.bot.framework;
import net.lamgc.cgj.bot.boot.BotGlobal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class FrameworkResources {
private final static File frameworkDataStoreRootDir = new File(BotGlobal.getGlobal().getDataStoreDir(),
"frameworks/");
private final ThreadGroup frameworkThreadGroup;
private final Logger logger;
private final File frameworkDataStoreDir;
public FrameworkResources(Framework framework) {
frameworkThreadGroup = new ThreadGroup(FrameworkManager.getFrameworkRootGroup(),
"Framework-" + framework.getIdentify());
frameworkDataStoreDir = new File(frameworkDataStoreRootDir, framework.getClass().getSimpleName());
logger = LoggerFactory.getLogger("Framework-" + framework.getIdentify());
}
ThreadGroup getFrameworkThreadGroup() {
return frameworkThreadGroup;
}
public Logger getLogger() {
return logger;
}
}

View File

@ -2,6 +2,9 @@ package net.lamgc.cgj.bot.framework.cli;
import net.lamgc.cgj.bot.boot.ApplicationBoot; import net.lamgc.cgj.bot.boot.ApplicationBoot;
import net.lamgc.cgj.bot.event.BotEventHandler; import net.lamgc.cgj.bot.event.BotEventHandler;
import net.lamgc.cgj.bot.framework.Framework;
import net.lamgc.cgj.bot.framework.FrameworkManager;
import net.lamgc.cgj.bot.framework.FrameworkResources;
import net.lamgc.cgj.bot.framework.cli.message.ConsoleMessageEvent; import net.lamgc.cgj.bot.framework.cli.message.ConsoleMessageEvent;
import net.lamgc.cgj.bot.framework.cli.message.ConsoleMessageSenderFactory; import net.lamgc.cgj.bot.framework.cli.message.ConsoleMessageSenderFactory;
import net.lamgc.cgj.bot.message.MessageSenderBuilder; import net.lamgc.cgj.bot.message.MessageSenderBuilder;
@ -12,13 +15,18 @@ import org.jline.terminal.TerminalBuilder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean;
public class ConsoleMain { public class ConsoleMain implements Framework {
private final static Logger log = LoggerFactory.getLogger(ConsoleMain.class); private final static Logger log = LoggerFactory.getLogger(ConsoleMain.class);
private final AtomicBoolean quitState = new AtomicBoolean();
public static void start() throws IOException { @Override
public void init(FrameworkResources resources) { }
@Override
public void run() throws Exception {
MessageSenderBuilder.setCurrentMessageSenderFactory(new ConsoleMessageSenderFactory()); MessageSenderBuilder.setCurrentMessageSenderFactory(new ConsoleMessageSenderFactory());
ApplicationBoot.initialBot(); ApplicationBoot.initialBot();
LineReader lineReader = LineReaderBuilder.builder() LineReader lineReader = LineReaderBuilder.builder()
@ -45,7 +53,22 @@ public class ConsoleMain {
} catch (InterruptedException e) { } catch (InterruptedException e) {
log.error("执行时发生中断", e); log.error("执行时发生中断", e);
} }
} while(true); } while(!quitState.get());
} }
@Override
public void close() {
quitState.set(true);
Thread.currentThread().getThreadGroup().interrupt();
}
@Override
public String getIdentify() {
return this.toString();
}
@Override
public String getFrameworkName() {
return "console";
}
} }

View File

@ -1,27 +0,0 @@
package net.lamgc.cgj.bot.framework.coolq;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import net.lz1998.cq.CQGlobal;
import net.lz1998.cq.EnableCQ;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@EnableCQ
public class CQConfig {
public static void init() {
CQGlobal.pluginList.add(CQPluginMain.class);
CQGlobal.executor = new ThreadPoolExecutor(
(int) Math.ceil(Runtime.getRuntime().availableProcessors() / 2F),
Runtime.getRuntime().availableProcessors(),
25, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(512),
new ThreadFactoryBuilder()
.setNameFormat("Plugin-ProcessThread-%d")
.build()
);
}
}

View File

@ -3,6 +3,7 @@ package net.lamgc.cgj.bot.framework.coolq;
import net.lamgc.cgj.bot.boot.ApplicationBoot; import net.lamgc.cgj.bot.boot.ApplicationBoot;
import net.lamgc.cgj.bot.event.BotEventHandler; import net.lamgc.cgj.bot.event.BotEventHandler;
import net.lamgc.cgj.bot.framework.coolq.message.SpringCQMessageEvent; import net.lamgc.cgj.bot.framework.coolq.message.SpringCQMessageEvent;
import net.lamgc.cgj.bot.framework.coolq.message.SpringCQMessageSenderFactory;
import net.lamgc.utils.event.EventHandler; import net.lamgc.utils.event.EventHandler;
import net.lz1998.cq.event.message.CQDiscussMessageEvent; import net.lz1998.cq.event.message.CQDiscussMessageEvent;
import net.lz1998.cq.event.message.CQGroupMessageEvent; import net.lz1998.cq.event.message.CQGroupMessageEvent;
@ -13,13 +14,15 @@ import net.lz1998.cq.robot.CoolQ;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicBoolean;
@Component @Component
@SuppressWarnings("unused")
public class CQPluginMain extends CQPlugin implements EventHandler { public class CQPluginMain extends CQPlugin implements EventHandler {
private final static AtomicBoolean initialState = new AtomicBoolean();
public CQPluginMain() { public CQPluginMain() {
// TODO(LamGC, 2020.04.21): SpringCQ无法适配MessageSenderBuilder
// MessageSenderBuilder.setCurrentMessageSenderFactory(new SpringCQMessageSenderFactory());
ApplicationBoot.initialBot();
LoggerFactory.getLogger(CQPluginMain.class) LoggerFactory.getLogger(CQPluginMain.class)
.info("BotEventHandler.COMMAND_PREFIX = {}", BotEventHandler.COMMAND_PREFIX); .info("BotEventHandler.COMMAND_PREFIX = {}", BotEventHandler.COMMAND_PREFIX);
} }
@ -46,6 +49,13 @@ public class CQPluginMain extends CQPlugin implements EventHandler {
* @return 是否拦截消息 * @return 是否拦截消息
*/ */
private static int processMessage(CoolQ cq, CQMessageEvent event) { private static int processMessage(CoolQ cq, CQMessageEvent event) {
SpringCQMessageSenderFactory.setCoolQ(cq);
synchronized (initialState) {
if(!initialState.get()) {
ApplicationBoot.initialBot();
initialState.set(true);
}
}
if(BotEventHandler.mismatch(event.getMessage())) { if(BotEventHandler.mismatch(event.getMessage())) {
return MESSAGE_IGNORE; return MESSAGE_IGNORE;
} }

View File

@ -0,0 +1,64 @@
package net.lamgc.cgj.bot.framework.coolq;
import net.lamgc.cgj.bot.boot.BotGlobal;
import net.lamgc.cgj.bot.framework.Framework;
import net.lamgc.cgj.bot.framework.FrameworkResources;
import org.slf4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextStoppedEvent;
@SpringBootApplication
public class SpringCQApplication implements Framework {
private Logger log;
private final Object quitLock = new Object();
@Override
public void init(FrameworkResources resources) {
this.log = resources.getLogger();
}
public void run() {
log.info("酷Q机器人根目录: {}", BotGlobal.getGlobal().getDataStoreDir().getPath());
ConfigurableApplicationContext context = SpringApplication.run(SpringCQApplication.class);
registerShutdownHook(context);
try {
synchronized (quitLock) {
quitLock.wait();
}
} catch (InterruptedException e) {
log.warn("发生中断, 退出SpringCQ...", e);
}
context.stop();
context.close();
}
private void registerShutdownHook(ConfigurableApplicationContext context) {
context.addApplicationListener((ApplicationListener<ApplicationFailedEvent>)
event -> close());
context.addApplicationListener((ApplicationListener<ContextClosedEvent>)
event -> close());
context.addApplicationListener((ApplicationListener<ContextStoppedEvent>)
event -> close());
Runtime.getRuntime().addShutdownHook(new Thread(this::close));
}
public void close() {
synchronized (quitLock) {
quitLock.notify();
}
}
@Override
public String getFrameworkName() {
return "SpringCoolQ";
}
}

View File

@ -6,13 +6,26 @@ import net.lamgc.cgj.bot.message.MessageSource;
import net.lz1998.cq.robot.CoolQ; import net.lz1998.cq.robot.CoolQ;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
public class SpringCQMessageSenderFactory implements MessageSenderFactory { public class SpringCQMessageSenderFactory implements MessageSenderFactory {
private final static ThreadLocal<CoolQ> threadCoolQ = new ThreadLocal<>(); private final static AtomicReference<CoolQ> coolQ = new AtomicReference<>();
/**
* 设置CoolQ对象.
* <p>该方法仅接受第一次设置的CoolQ对象, 其他对象将会忽略.</p>
* @param coolQObj CoolQ对象
*/
public static void setCoolQ(CoolQ coolQObj) {
if(coolQ.get() == null) {
coolQ.set(coolQObj);
}
}
@Override @Override
public MessageSender createMessageSender(MessageSource source, long id) { public MessageSender createMessageSender(MessageSource source, long id) {
return new SpringCQMessageSender( return new SpringCQMessageSender(
Objects.requireNonNull(threadCoolQ.get(), "CoolQ object is not included in ThreadLocal"), source, id); Objects.requireNonNull(coolQ.get(), "CoolQ object not ready"), source, id);
} }
} }

View File

@ -3,9 +3,12 @@ package net.lamgc.cgj.bot.framework.mirai;
import net.lamgc.cgj.bot.boot.ApplicationBoot; import net.lamgc.cgj.bot.boot.ApplicationBoot;
import net.lamgc.cgj.bot.boot.BotGlobal; import net.lamgc.cgj.bot.boot.BotGlobal;
import net.lamgc.cgj.bot.event.BotEventHandler; import net.lamgc.cgj.bot.event.BotEventHandler;
import net.lamgc.cgj.bot.framework.Framework;
import net.lamgc.cgj.bot.framework.FrameworkResources;
import net.lamgc.cgj.bot.framework.mirai.message.MiraiMessageEvent; import net.lamgc.cgj.bot.framework.mirai.message.MiraiMessageEvent;
import net.lamgc.cgj.bot.framework.mirai.message.MiraiMessageSenderFactory; import net.lamgc.cgj.bot.framework.mirai.message.MiraiMessageSenderFactory;
import net.lamgc.cgj.bot.message.MessageSenderBuilder; import net.lamgc.cgj.bot.message.MessageSenderBuilder;
import net.lamgc.cgj.bot.util.GroupMuteManager;
import net.mamoe.mirai.Bot; import net.mamoe.mirai.Bot;
import net.mamoe.mirai.BotFactoryJvm; import net.mamoe.mirai.BotFactoryJvm;
import net.mamoe.mirai.event.events.BotMuteEvent; import net.mamoe.mirai.event.events.BotMuteEvent;
@ -24,15 +27,18 @@ import java.io.*;
import java.util.Base64; import java.util.Base64;
import java.util.Properties; import java.util.Properties;
public class MiraiMain implements Closeable { public class MiraiMain implements Framework {
private final Logger log = LoggerFactory.getLogger(MiraiMain.class); private final Logger log = LoggerFactory.getLogger(MiraiMain.class);
private Bot bot; private Bot bot;
private final static Properties botProperties = new Properties(); private final Properties botProperties = new Properties();
public void init() { private final GroupMuteManager muteManager = new GroupMuteManager();
@Override
public void init(FrameworkResources resources) {
Runtime.getRuntime().addShutdownHook(new Thread(this::close)); Runtime.getRuntime().addShutdownHook(new Thread(this::close));
try { try {
Class.forName(BotEventHandler.class.getName()); Class.forName(BotEventHandler.class.getName());
@ -69,19 +75,26 @@ public class MiraiMain implements Closeable {
bot = BotFactoryJvm.newBot(Long.parseLong(botProperties.getProperty("bot.qq", "0")), bot = BotFactoryJvm.newBot(Long.parseLong(botProperties.getProperty("bot.qq", "0")),
Base64.getDecoder().decode(botProperties.getProperty("bot.password", "")), configuration); Base64.getDecoder().decode(botProperties.getProperty("bot.password", "")), configuration);
// TODO: 看看能不能单独订阅某个Bot?
Events.subscribeAlways(GroupMessageEvent.class, this::executeMessageEvent); Events.subscribeAlways(GroupMessageEvent.class, this::executeMessageEvent);
Events.subscribeAlways(FriendMessageEvent.class, this::executeMessageEvent); Events.subscribeAlways(FriendMessageEvent.class, this::executeMessageEvent);
Events.subscribeAlways(TempMessageEvent.class, this::executeMessageEvent); Events.subscribeAlways(TempMessageEvent.class, this::executeMessageEvent);
Events.subscribeAlways(BotMuteEvent.class, Events.subscribeAlways(BotMuteEvent.class,
event -> BotEventHandler.setMuteState(event.getGroup().getId(), true)); event -> muteManager.setMuteState(event.getGroup().getId(), true));
Events.subscribeAlways(BotUnmuteEvent.class, Events.subscribeAlways(BotUnmuteEvent.class,
event -> BotEventHandler.setMuteState(event.getGroup().getId(), false)); event -> muteManager.setMuteState(event.getGroup().getId(), false));
bot.login(); bot.login();
MessageSenderBuilder.setCurrentMessageSenderFactory(new MiraiMessageSenderFactory(bot)); MessageSenderBuilder.setCurrentMessageSenderFactory(new MiraiMessageSenderFactory(bot));
ApplicationBoot.initialBot(); ApplicationBoot.initialBot();
bot.join(); bot.join();
} }
@Override
public void run() {
bot.login();
bot.join();
}
/** /**
* 处理消息事件 * 处理消息事件
* @param message 消息事件对象 * @param message 消息事件对象
@ -90,9 +103,12 @@ public class MiraiMain implements Closeable {
log.debug("Mirai Message: {}", message); log.debug("Mirai Message: {}", message);
if(message instanceof GroupMessageEvent) { if(message instanceof GroupMessageEvent) {
GroupMessageEvent GroupMessageEvent = (GroupMessageEvent) message; GroupMessageEvent GroupMessageEvent = (GroupMessageEvent) message;
if(BotEventHandler.isMute(GroupMessageEvent.getGroup().getId(), true) == null) { Boolean muteState = muteManager.isMute(GroupMessageEvent.getGroup().getId(), true);
BotEventHandler.setMuteState(GroupMessageEvent.getGroup().getId(), if(muteState == null) {
muteManager.setMuteState(GroupMessageEvent.getGroup().getId(),
((GroupMessageEvent) message).getGroup().getBotMuteRemaining() != 0); ((GroupMessageEvent) message).getGroup().getBotMuteRemaining() != 0);
} else if(muteState) {
return;
} }
} }
BotEventHandler.executeMessageEvent(MiraiMessageEvent.covertEventObject(message)); BotEventHandler.executeMessageEvent(MiraiMessageEvent.covertEventObject(message));
@ -101,6 +117,7 @@ public class MiraiMain implements Closeable {
/** /**
* 关闭机器人 * 关闭机器人
*/ */
@Override
public synchronized void close() { public synchronized void close() {
if(bot == null) { if(bot == null) {
return; return;
@ -111,4 +128,9 @@ public class MiraiMain implements Closeable {
log.warn("机器人已关闭."); log.warn("机器人已关闭.");
} }
@Override
public String getFrameworkName() {
return "MiraiQQ";
}
} }

View File

@ -0,0 +1,48 @@
package net.lamgc.cgj.bot.util;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* 群禁言管理器.
* <p>该管理器用于存取群组禁言状态.</p>
*/
public class GroupMuteManager {
private final Map<Long, AtomicBoolean> muteStateMap = new Hashtable<>();
/**
* 查询某群是否被禁言.
* @param groupId 群组Id
* @param rawValue 是否返回原始值(当没有该群状态, 且本参数为true时, 将返回null)
* @return 返回状态值, 如无该群禁言记录且rawValue = true, 则返回null
*/
public Boolean isMute(long groupId, boolean rawValue) {
if(groupId <= 0) {
return false;
}
AtomicBoolean state = muteStateMap.get(groupId);
if(state == null && rawValue) {
return null;
}
return state != null && state.get();
}
/**
* 设置机器人禁言状态.
* <p>设置该项可防止因机器人在禁言期间反馈请求导致被封号.</p>
* @param mute 如果被禁言, 传入true
*/
public void setMuteState(long groupId, boolean mute) {
if(groupId <= 0) {
return;
}
if(!muteStateMap.containsKey(groupId)) {
muteStateMap.put(groupId, new AtomicBoolean(mute));
} else {
muteStateMap.get(groupId).set(mute);
}
}
}

View File

@ -402,7 +402,7 @@ public class PixivDownload {
if(resultObject.get("error").getAsBoolean()) { if(resultObject.get("error").getAsBoolean()) {
String message = resultObject.get("message").getAsString(); String message = resultObject.get("message").getAsString();
log.warn("作品页面接口请求错误, 错误信息: {}", message); log.warn("作品页面接口请求错误, 错误信息: {}", message);
throw new HttpRequestException(response); throw new HttpRequestException(response.getStatusLine(), resultObject.toString());
} }
JsonArray linkArray = resultObject.getAsJsonArray("body"); JsonArray linkArray = resultObject.getAsJsonArray("body");

View File

@ -1,5 +1,6 @@
package net.lamgc.cgj.pixiv; package net.lamgc.cgj.pixiv;
import com.google.common.io.ByteStreams;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
@ -12,7 +13,6 @@ import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -127,14 +127,13 @@ public final class PixivUgoiraBuilder {
HashMap<String, InputStream> frameMap = new HashMap<>(frames.size()); HashMap<String, InputStream> frameMap = new HashMap<>(frames.size());
while((entry = zipInputStream.getNextEntry()) != null) { while((entry = zipInputStream.getNextEntry()) != null) {
log.trace("ZipEntry {} 正在接收...", entry); log.trace("ZipEntry {} 正在接收...", entry);
Streams.copy(zipInputStream, cacheOutputStream, false); ByteStreams.copy(zipInputStream, cacheOutputStream);
frameMap.put(entry.getName(), new ByteArrayInputStream(cacheOutputStream.toByteArray())); frameMap.put(entry.getName(), new ByteArrayInputStream(cacheOutputStream.toByteArray()));
log.trace("ZipEntry {} 已接收完成.", entry); log.trace("ZipEntry {} 已接收完成.", entry);
cacheOutputStream.reset(); cacheOutputStream.reset();
} }
InputStream firstFrameInput = frameMap.get(frames.get(0).getAsJsonObject().get("file").getAsString());
InputStream firstFrameInput = frameMap.get("000000.jpg");
BufferedImage firstFrame = ImageIO.read(firstFrameInput); BufferedImage firstFrame = ImageIO.read(firstFrameInput);
firstFrameInput.reset(); firstFrameInput.reset();
if(width != firstFrame.getWidth() || height != firstFrame.getHeight()) { if(width != firstFrame.getWidth() || height != firstFrame.getHeight()) {

View File

@ -1,2 +0,0 @@
server.port=8081
server.tomcat.max-threads=1

View File

@ -0,0 +1,12 @@
server:
port: 8081
spring:
cq:
plugin-list:
- net.lamgc.cgj.bot.framework.coolq.CQPluginMain
event:
corePoolSize: 8
maxPoolSize: 16
keepAliveTime: 25000
workQueueSize: 1024

View File

@ -0,0 +1,30 @@
package net.lamgc.cgj.bot.util;
import org.junit.Assert;
import org.junit.Test;
public class GroupMuteManagerTest {
@Test
public void muteStateTest() {
GroupMuteManager manager = new GroupMuteManager();
Assert.assertNull(manager.isMute(1, true)); // 未设置的群组返回null
Assert.assertFalse(manager.isMute(1, false)); // 未设置就返回false
manager.setMuteState(1, true); // mute == true
Assert.assertNotNull(manager.isMute(1, true)); // 第一次设置后不为null
Assert.assertTrue(manager.isMute(1, false)); // 确保条件正常
manager.setMuteState(2, true); // 不能出现不同群号的冲突
manager.setMuteState(1, false);
Assert.assertTrue(manager.isMute(2, false));
Assert.assertNotNull(manager.isMute(1, true)); // 变更为false后依然不能返回null
Assert.assertFalse(manager.isMute(1, false));
}
@Test
public void invalidGroupIdTest() {
GroupMuteManager manager = new GroupMuteManager();
manager.setMuteState(-1, true); // 设置应该是无效的
Assert.assertFalse(manager.isMute(-1, false)); // 由于设置无效, 返回false即可
}
}