mirror of
https://github.com/LamGC/ContentGrabbingJi.git
synced 2025-07-01 21:07:25 +00:00
Compare commits
35 Commits
v2.5.2-202
...
add-parame
Author | SHA1 | Date | |
---|---|---|---|
27ede0fe92
|
|||
7bd9e1c410 | |||
cc4eeac728
|
|||
6b47e19569
|
|||
24ff4b214e | |||
bf8de1ac1e | |||
a7c434da61 | |||
575dc0c7fb
|
|||
56ef463c63
|
|||
4387da37f5
|
|||
0fc3e3ab48
|
|||
a606ec0423
|
|||
210aa84ed5 | |||
6fbbe522db | |||
6d55325fc7 | |||
d1c7f6f973
|
|||
0727ef4f93
|
|||
73a1caaf46
|
|||
4784f8773b
|
|||
f80b6e72e0
|
|||
05e933838e
|
|||
3045b571a8
|
|||
553212e556
|
|||
5383de7450
|
|||
9964205dc2
|
|||
394c3940e4
|
|||
d3d6f151d4
|
|||
62e3affef1
|
|||
51efc95c1c
|
|||
d5c3a438b0
|
|||
792bfcb1bd
|
|||
cbd7db3570
|
|||
467e7065fa
|
|||
d2240e56fd | |||
eef9f285ca
|
37
.github/ISSUE_TEMPLATE/Bug_Report.md
vendored
37
.github/ISSUE_TEMPLATE/Bug_Report.md
vendored
@ -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.
|
||||||
|
|
||||||
|
## 相关信息 ##
|
||||||
|
### 日志 ###
|
||||||
|
<!-- 如果日志涉及了问题,请务必将日志一同提交,这对排查问题非常有用 -->
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
11
.github/ISSUE_TEMPLATE/Feature_Report.md
vendored
Normal file
11
.github/ISSUE_TEMPLATE/Feature_Report.md
vendored
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
name: 功能/想法 提议
|
||||||
|
about: 使用这个模板将你对应用的想法提出来,或许我们会采纳!
|
||||||
|
title: ''
|
||||||
|
labels: function, question
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- 如果可以,尽可能的清晰、详细的表达你的想法 -->
|
||||||
|
<!-- 没关系的,我们会进一步向你交流以尝试了解你的想法! -->
|
@ -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
|
||||||
|
140
README.md
140
README.md
@ -1,41 +1,119 @@
|
|||||||
# ContentGrabbingJi #
|
# ContentGrabbingJi - 色图姬 #
|
||||||
Pixiv爬虫一只,同时也是一个机器人/插件!
|
一个以高性能、高效率为目标,多平台/框架支持、持续维护的 Pixiv 聊天机器人;
|
||||||
|
色图姬存在的目的最初是作为**爬虫 + 机器人**的形式开发,在开发过程中逐渐以多聊天平台,高效率为目标进行。
|
||||||
|
|
||||||
## 支持的机器人平台 ##
|
## 安装 ##
|
||||||
- [Mirai](https://github.com/mamoe/mirai)
|
### 通过 Jar 文件部署 ###
|
||||||
- [CoolQ](https://cqp.cc)(基于[`SpringCQ`](https://github.com/lz1998/spring-cq), 不支持多账号使用, 需要使用[`CQHttp`](https://cqhttp.cc/)插件)
|
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
|
||||||
|
```
|
||||||
|
(管理员 QQ 的作用/用法将在下面详细说明。)
|
||||||
|
7. 配置完成后,准备一台 Redis 服务端,用于缓存数据。
|
||||||
|
8. Redis 服务器准备好后,使用命令启动色图姬:
|
||||||
|
`java -jar <CGJ.jar> botMode -botDataDir <数据目录> -redisAddress <Redis服务器地址> [-proxy 代理服务器地址]`
|
||||||
|
9. 完成!好好享受!
|
||||||
|
|
||||||
## Usage ##
|
### 通过 Docker 部署 ###
|
||||||
> 注意: 运行色图姬前, 你需要准备一个Pixiv账号的会话Cookie存储文件, 否则色图姬将无法运行.
|
使用 Docker 将可以更好的管理色图姬所使用的资源,和管理色图姬的运行。
|
||||||
> 详见[PixivLoginProxyServer](https://github.com/LamGC/PixivLoginProxyServer)项目的[Readme](https://github.com/LamGC/PixivLoginProxyServer/blob/master/README.md).
|
(正在完善中...)
|
||||||
|
|
||||||
### Arguments ###
|
## 使用 ##
|
||||||
> ENV参数名为环境变量名, 用于给Docker容器提供设置方式.
|
### 普通用户 ###
|
||||||
|
将色图姬部署完成,并且让色图姬在某个平台登录完成后,你就可以通过聊天平台向色图姬发起会话了!
|
||||||
|
使用 `.cgj` 向色图姬询问帮助信息!
|
||||||
|
|
||||||
- 通用参数
|
另外,由于色图姬在开发过程中直接使用了原本应用在命令行中的参数解析工具,所以你需要了解一下色图姬命令的格式,
|
||||||
- `-proxy` / `ENV: CGJ_PROXY`: (**可选**) 设置代理
|
色图姬的命令格式为:
|
||||||
- 格式: `协议://地址:端口`
|
```bash
|
||||||
- 示例: `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`
|
### 管理员用户 ###
|
||||||
|
你应该注意到了,在部署过程中,你需要设置一个管理员 QQ 的配置,色图姬支持通过命令来管理色图姬的运行。
|
||||||
|
目前支持的管理员命令:
|
||||||
|
```bash
|
||||||
|
# 清除缓存(慎用)
|
||||||
|
# 该操作将会清除Redis服务器内的所有数据, 以及色图姬下载到本地的所有图片缓存.
|
||||||
|
.cgjadmin cleanCache
|
||||||
|
|
||||||
### Commands ###
|
# 设置配置项
|
||||||
- `pluginMode`: CoolQ插件模式(依赖[酷Q机器人](https://cqp.cc/), 支持与CoolQ其他插件共存, 性能耗损大)
|
# 如果不使用group参数, 则设置全局配置
|
||||||
- `botMode`: Mirai独立模式(机器人独立运行, 不支持与其他插件共存, 性能耗损小)
|
# 注意: 配置项设置后需要使用`.cgjadmin saveProperties`才会保存到文件中,
|
||||||
- `collectionDownload`: 收藏下载, 以原图画质下载Cookie所属账号的所有收藏作品
|
# 如不保存, 则仅能在本次运行中生效(或使用`.cgjadmin loadProperties`重新加载后失效).
|
||||||
- `getRecommends`: 将访问主页获得的推荐作品全部以原图画质下载
|
.cgjadmin setProperty <-key 配置项名> <-value 配置项新值> [-group 指定群组]
|
||||||
- `getRankingIllust`: 以原图画质下载指定排行榜类型的全部作品
|
|
||||||
- `search`: 搜索指定内容并获取相关作品信息(不下载)
|
|
||||||
|
|
||||||
> 注意: 除去机器人模式外, 其他功能后续可能会出现改动.
|
# 查询配置项
|
||||||
|
# 如果不使用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 信息。
|
||||||
|
如果是为色图姬提供一些新功能想法,或者对色图姬有什么意见,则可以使用[功能/意见提议模板](https://github.com/LamGC/ContentGrabbingJi/issues/new?assignees=&labels=function%2C+question&template=Feature_Report.md&title=)反馈你的想法!
|
||||||
|
|
||||||
|
如果你会 Java 开发,又想为色图姬提供一些新功能,可以通过 Fork 仓库的方法,实现后发起 PR,合并到色图姬项目中!
|
||||||
|
向色图姬贡献代码,需要遵循一些贡献事项,如果你的代码不符合这些事项,PR有可能会被关闭!
|
||||||
|
> 注意:色图姬的初衷并没有任何恶意的意图,如果尝试向色图姬提供恶意功能或代码,PR 将会被拒绝、关闭。
|
||||||
|
|
||||||
## LICENSE ##
|
## LICENSE ##
|
||||||
本项目基于 `GNU Affero General Public License 3.0` 开源许可协议开源,
|
本项目基于 `GNU Affero General Public License 3.0` 开源许可协议开源,
|
||||||
|
@ -41,16 +41,15 @@ GET https://www.pixiv.net/ranking.php
|
|||||||
:-: |:-:| :-: | :-: | :-:
|
:-: |:-:| :-: | :-: | :-:
|
||||||
daily |`√`|`√`|`√`|`√`
|
daily |`√`|`√`|`√`|`√`
|
||||||
weekly |`√`|`√`|`√`|`√`
|
weekly |`√`|`√`|`√`|`√`
|
||||||
monthly |`√`|`√`|×|`√`
|
monthly |`√`|`√`| × |`√`
|
||||||
rookie |`√`|`√`|×|`√`
|
rookie |`√`|`√`| × |`√`
|
||||||
original |`√`|×|×|×
|
original |`√`| × | × | ×
|
||||||
male |`√`|×|×|×
|
male |`√`| × | × | ×
|
||||||
female |`√`|×|×|×
|
female |`√`| × | × | ×
|
||||||
daily_r18 |`√`|`√`|`√`|`√`
|
daily_r18 |`√`|`√`|`√`|`√`
|
||||||
weekly_r18|`√`|`√`|`√`|`√`
|
weekly_r18|`√`|`√`|`√`|`√`
|
||||||
male_r18 |`√`|×|×|×
|
male_r18 |`√`| × | × | ×
|
||||||
female_r18|`√`|×|×|×
|
female_r18|`√`| × | × | ×
|
||||||
|
|
||||||
|
|
||||||
### 返回数据 ###
|
### 返回数据 ###
|
||||||
#### 数据示例 ####
|
#### 数据示例 ####
|
||||||
|
@ -16,14 +16,17 @@ GET https://www.pixiv.net/ajax/search/{Type}/{Content}?{Param...}
|
|||||||
### 参数 ###
|
### 参数 ###
|
||||||
#### Url参数 ####
|
#### Url参数 ####
|
||||||
- `Type`: 内容类型
|
- `Type`: 内容类型
|
||||||
- illustrations(插画)
|
- `artworks` - 所有类型
|
||||||
- top(推荐)
|
- `top` - 推荐
|
||||||
- manga(漫画)
|
- `illustrations` - 插画
|
||||||
- novels(小说)
|
- `manga` - 漫画
|
||||||
|
- `novels` - 小说
|
||||||
|
- `tags` - 查询标签信息
|
||||||
- `Content`: 搜索内容
|
- `Content`: 搜索内容
|
||||||
|
|
||||||
#### GET参数 ####
|
#### GET参数 ####
|
||||||
##### 必填 #####
|
##### 必填 #####
|
||||||
|
> 注意:除 `tags` 类型外,其他内容类型都需要以下参数。
|
||||||
- `word`: 与搜索内容一致 (经测试似乎可以省略)
|
- `word`: 与搜索内容一致 (经测试似乎可以省略)
|
||||||
- `s_mode`: 匹配模式
|
- `s_mode`: 匹配模式
|
||||||
- `s_tag`: 标签,部分一致
|
- `s_tag`: 标签,部分一致
|
||||||
@ -82,7 +85,8 @@ GET https://www.pixiv.net/ajax/search/{Type}/{Content}?{Param...}
|
|||||||
"風景",
|
"風景",
|
||||||
"空",
|
"空",
|
||||||
"草",
|
"草",
|
||||||
"雲"],
|
"雲"
|
||||||
|
],
|
||||||
"userId":"31507675",
|
"userId":"31507675",
|
||||||
"userName":"昏omeme",
|
"userName":"昏omeme",
|
||||||
"width":1600,
|
"width":1600,
|
||||||
@ -155,7 +159,8 @@ GET https://www.pixiv.net/ajax/search/{Type}/{Content}?{Param...}
|
|||||||
"女の子",
|
"女の子",
|
||||||
"カラス",
|
"カラス",
|
||||||
"风景",
|
"风景",
|
||||||
"線路"],
|
"線路"
|
||||||
|
],
|
||||||
"userId":"1069005",
|
"userId":"1069005",
|
||||||
"userName":"へちま",
|
"userName":"へちま",
|
||||||
"width":2000,
|
"width":2000,
|
||||||
@ -310,24 +315,10 @@ 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`) 漫画和插画的搜索结果
|
- `illustManga`: (`Object`) 漫画和插画的搜索结果
|
||||||
- `total`: (`number`) 搜索结果总量
|
- `total`: (`number`) 搜索结果总量
|
||||||
- `data`: (`Object[]`) 搜索结果(仅当前页数)
|
- `data`: (`Object[]`) 搜索结果(仅当前页数)
|
||||||
@ -362,4 +353,45 @@ GET https://www.pixiv.net/ajax/search/{Type}/{Content}?{Param...}
|
|||||||
- `createDate`: (`string`) 作品创建时间(或者是完成时间?)
|
- `createDate`: (`string`) 作品创建时间(或者是完成时间?)
|
||||||
- `updateDate`: (`string`) 作品上传时间
|
- `updateDate`: (`string`) 作品上传时间
|
||||||
- `profileImageUrl`: (`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` |×|×|×|√
|
||||||
|
|
||||||
|
符号解释:
|
||||||
|
- `√`: 该属性一定存在
|
||||||
|
- `?`: 该属性可能存在
|
||||||
|
- `×`: 该属性不存在
|
||||||
|
47
documents/interfaces/Pixiv搜索推荐候选接口.md
Normal file
47
documents/interfaces/Pixiv搜索推荐候选接口.md
Normal 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`: 前缀
|
319
documents/interfaces/Pixiv预加载数据.md
Normal file
319
documents/interfaces/Pixiv预加载数据.md
Normal 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&format=js&s=1&up=0&a=22&ng=w&l=zh&uri=%2Fartworks%2F_PARAM_&is_spa=1&K=59bba275c645c&ab_test_digits_first=32&yuid=NDJ3gQk&suid=Pggb9mua3yznnr7lz&num=5efbf5be273&t=_bee-JX46i&t=b8b4-hqot7&t=kY01H5r3Pd"
|
||||||
|
},
|
||||||
|
"rectangle":{
|
||||||
|
"url":"https://pixon.ads-pixiv.net/show?zone_id=illust_rectangle&format=js&s=1&up=0&a=22&ng=w&l=zh&uri=%2Fartworks%2F_PARAM_&is_spa=1&K=59bba275c645c&ab_test_digits_first=32&yuid=NDJ3gQk&suid=Pggb9mua42776dfuu&num=5efbf5be810&t=_bee-JX46i&t=b8b4-hqot7&t=kY01H5r3Pd"
|
||||||
|
},
|
||||||
|
"500x500":{
|
||||||
|
"url":"https://pixon.ads-pixiv.net/show?zone_id=bigbanner&format=js&s=1&up=0&a=22&ng=w&l=zh&uri=%2Fartworks%2F_PARAM_&is_spa=1&K=59bba275c645c&ab_test_digits_first=32&yuid=NDJ3gQk&suid=Pggb9mua442sjsueo&num=5efbf5be568&t=_bee-JX46i&t=b8b4-hqot7&t=kY01H5r3Pd"
|
||||||
|
},
|
||||||
|
"header":{
|
||||||
|
"url":"https://pixon.ads-pixiv.net/show?zone_id=header&format=js&s=1&up=0&a=22&ng=w&l=zh&uri=%2Fartworks%2F_PARAM_&is_spa=1&K=59bba275c645c&ab_test_digits_first=32&yuid=NDJ3gQk&suid=Pggb9mua45spzoimt&num=5efbf5be155&t=_bee-JX46i&t=b8b4-hqot7&t=kY01H5r3Pd"
|
||||||
|
},
|
||||||
|
"footer":{
|
||||||
|
"url":"https://pixon.ads-pixiv.net/show?zone_id=footer&format=js&s=1&up=0&a=22&ng=w&l=zh&uri=%2Fartworks%2F_PARAM_&is_spa=1&K=59bba275c645c&ab_test_digits_first=32&yuid=NDJ3gQk&suid=Pggb9mua47f9zcoim&num=5efbf5be400&t=_bee-JX46i&t=b8b4-hqot7&t=kY01H5r3Pd"
|
||||||
|
},
|
||||||
|
"expandedFooter":{
|
||||||
|
"url":"https://pixon.ads-pixiv.net/show?zone_id=multiple_illust_viewer&format=js&s=1&up=0&a=22&ng=w&l=zh&uri=%2Fartworks%2F_PARAM_&is_spa=1&K=59bba275c645c&ab_test_digits_first=32&yuid=NDJ3gQk&suid=Pggb9mua4928ct0yw&num=5efbf5be471&t=_bee-JX46i&t=b8b4-hqot7&t=kY01H5r3Pd"
|
||||||
|
},
|
||||||
|
"logo":{
|
||||||
|
"url":"https://pixon.ads-pixiv.net/show?zone_id=logo_side&format=js&s=1&up=0&a=22&ng=w&l=zh&uri=%2Fartworks%2F_PARAM_&is_spa=1&K=59bba275c645c&ab_test_digits_first=32&yuid=NDJ3gQk&suid=Pggb9mua4aqu6i4sr&num=5efbf5be844&t=_bee-JX46i&t=b8b4-hqot7&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`) 不明?
|
8
pom.xml
8
pom.xml
@ -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>
|
||||||
|
@ -8,11 +8,9 @@ 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.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.*;
|
||||||
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
|
|
||||||
import net.lamgc.cgj.pixiv.PixivURL;
|
|
||||||
import net.lamgc.utils.base.runner.Argument;
|
import net.lamgc.utils.base.runner.Argument;
|
||||||
import net.lamgc.utils.base.runner.ArgumentsRunner;
|
import net.lamgc.utils.base.runner.ArgumentsRunner;
|
||||||
import net.lamgc.utils.base.runner.Command;
|
import net.lamgc.utils.base.runner.Command;
|
||||||
@ -25,20 +23,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);
|
||||||
@ -105,17 +98,7 @@ public class Main {
|
|||||||
|
|
||||||
@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());
|
new SpringCQApplication().start(argsStr);
|
||||||
CQConfig.init();
|
|
||||||
Pattern pattern = Pattern.compile("/\\s*(\".+?\"|[^:\\s])+((\\s*:\\s*(\".+?\"|[^\\s])+)|)|(\".+?\"|[^\"\\s])+");
|
|
||||||
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
|
||||||
@ -197,18 +180,18 @@ public class Main {
|
|||||||
date = format.format(queryDate);
|
date = format.format(queryDate);
|
||||||
|
|
||||||
log.info("查询时间: {}", date);
|
log.info("查询时间: {}", date);
|
||||||
PixivURL.RankingMode rankingMode = PixivURL.RankingMode.MODE_DAILY;
|
RankingMode rankingMode = RankingMode.MODE_DAILY;
|
||||||
PixivURL.RankingContentType contentType = null;
|
RankingContentType contentType = null;
|
||||||
if(mode != null) {
|
if(mode != null) {
|
||||||
try {
|
try {
|
||||||
rankingMode = PixivURL.RankingMode.valueOf(mode);
|
rankingMode = RankingMode.valueOf(mode);
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("不支持的RankingMode: {}", mode);
|
log.warn("不支持的RankingMode: {}", mode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(content != null) {
|
if(content != null) {
|
||||||
try {
|
try {
|
||||||
contentType = PixivURL.RankingContentType.valueOf(content);
|
contentType = RankingContentType.valueOf(content);
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("不支持的RankingContentType: {}", content);
|
log.warn("不支持的RankingContentType: {}", content);
|
||||||
}
|
}
|
||||||
@ -230,7 +213,8 @@ public class Main {
|
|||||||
|
|
||||||
log.info("正在调用方法...");
|
log.info("正在调用方法...");
|
||||||
try {
|
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 {
|
try {
|
||||||
ZipEntry entry = new ZipEntry("Rank" + rank + "-" + link.substring(link.lastIndexOf("/") + 1));
|
ZipEntry entry = new ZipEntry("Rank" + rank + "-" + link.substring(link.lastIndexOf("/") + 1));
|
||||||
entry.setComment(rankInfo.toString());
|
entry.setComment(rankInfo.toString());
|
||||||
@ -316,35 +300,39 @@ public class Main {
|
|||||||
|
|
||||||
JsonObject resultBody = jsonObject.getAsJsonObject("body");
|
JsonObject resultBody = jsonObject.getAsJsonObject("body");
|
||||||
|
|
||||||
for(PixivSearchLinkBuilder.SearchArea searchArea : PixivSearchLinkBuilder.SearchArea.values()) {
|
for(PixivSearchAttribute attribute : PixivSearchAttribute.values()) {
|
||||||
if(!resultBody.has(searchArea.jsonKey) || resultBody.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data").size() == 0) {
|
for(String attrName : attribute.attributeNames) {
|
||||||
//log.info("返回数据不包含 {}", searchArea.jsonKey);
|
if(!resultBody.has(attrName) ||
|
||||||
continue;
|
resultBody.getAsJsonObject(attrName).getAsJsonArray("data").size() == 0) {
|
||||||
}
|
//log.info("返回数据不包含 {}", attrName);
|
||||||
JsonArray illustsArray = resultBody
|
|
||||||
.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data");
|
|
||||||
log.info("已找到与 {} 相关插图信息({}):", content, searchArea.name().toLowerCase());
|
|
||||||
int count = 1;
|
|
||||||
for (JsonElement jsonElement : illustsArray) {
|
|
||||||
JsonObject illustObj = jsonElement.getAsJsonObject();
|
|
||||||
if(!illustObj.has("illustId")) {
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
int illustId = illustObj.get("illustId").getAsInt();
|
JsonArray illustsArray = resultBody
|
||||||
StringBuilder builder = new StringBuilder("[");
|
.getAsJsonObject(attrName).getAsJsonArray("data");
|
||||||
illustObj.get("tags").getAsJsonArray().forEach(el -> builder.append(el.getAsString()).append(", "));
|
log.info("已找到与 {} 相关插图信息({}):", content, attribute.name().toLowerCase());
|
||||||
builder.replace(builder.length() - 2, builder.length(), "]");
|
int count = 1;
|
||||||
log.info("{} ({} / {})\n\t作品id: {}, \n\t作者名(作者id): {} ({}), \n\t作品标题: {}, \n\t作品Tags: {}, \n\t作品链接: {}",
|
for (JsonElement jsonElement : illustsArray) {
|
||||||
searchArea.name(),
|
JsonObject illustObj = jsonElement.getAsJsonObject();
|
||||||
count++,
|
if(!illustObj.has("illustId")) {
|
||||||
illustsArray.size(),
|
continue;
|
||||||
illustId,
|
}
|
||||||
illustObj.get("userName").getAsString(),
|
int illustId = illustObj.get("illustId").getAsInt();
|
||||||
illustObj.get("userId").getAsInt(),
|
StringBuilder builder = new StringBuilder("[");
|
||||||
illustObj.get("illustTitle").getAsString(),
|
illustObj.get("tags").getAsJsonArray().forEach(el -> builder.append(el.getAsString()).append(", "));
|
||||||
builder,
|
builder.replace(builder.length() - 2, builder.length(), "]");
|
||||||
PixivURL.getPixivRefererLink(illustId)
|
log.info("{} ({} / {})\n\t作品id: {}, \n\t作者名(作者id): {} ({}), " +
|
||||||
);
|
"\n\t作品标题: {}, \n\t作品Tags: {}, \n\t作品链接: {}",
|
||||||
|
attribute.name(),
|
||||||
|
count++,
|
||||||
|
illustsArray.size(),
|
||||||
|
illustId,
|
||||||
|
illustObj.get("userName").getAsString(),
|
||||||
|
illustObj.get("userId").getAsInt(),
|
||||||
|
illustObj.get("illustTitle").getAsString(),
|
||||||
|
builder,
|
||||||
|
PixivURL.getPixivRefererLink(illustId)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,7 +9,8 @@ import net.lamgc.cgj.bot.boot.BotGlobal;
|
|||||||
import net.lamgc.cgj.bot.message.MessageSenderBuilder;
|
import net.lamgc.cgj.bot.message.MessageSenderBuilder;
|
||||||
import net.lamgc.cgj.bot.message.MessageSource;
|
import net.lamgc.cgj.bot.message.MessageSource;
|
||||||
import net.lamgc.cgj.pixiv.PixivDownload;
|
import net.lamgc.cgj.pixiv.PixivDownload;
|
||||||
import net.lamgc.cgj.pixiv.PixivURL;
|
import net.lamgc.cgj.pixiv.RankingContentType;
|
||||||
|
import net.lamgc.cgj.pixiv.RankingMode;
|
||||||
import net.lamgc.utils.base.runner.Argument;
|
import net.lamgc.utils.base.runner.Argument;
|
||||||
import net.lamgc.utils.base.runner.Command;
|
import net.lamgc.utils.base.runner.Command;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@ -118,16 +119,16 @@ public class BotAdminCommandProcess {
|
|||||||
return "排行榜范围选取错误!";
|
return "排行榜范围选取错误!";
|
||||||
}
|
}
|
||||||
|
|
||||||
PixivURL.RankingContentType type;
|
RankingContentType type;
|
||||||
PixivURL.RankingMode mode;
|
RankingMode mode;
|
||||||
try {
|
try {
|
||||||
type = PixivURL.RankingContentType.valueOf("TYPE_" + rankingContentType.toUpperCase());
|
type = RankingContentType.valueOf("TYPE_" + rankingContentType.toUpperCase());
|
||||||
} catch(IllegalArgumentException e) {
|
} catch(IllegalArgumentException e) {
|
||||||
return "无效的排行榜类型参数!";
|
return "无效的排行榜类型参数!";
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
mode = PixivURL.RankingMode.valueOf("MODE_" + rankingMode.toUpperCase());
|
mode = RankingMode.valueOf("MODE_" + rankingMode.toUpperCase());
|
||||||
} catch(IllegalArgumentException e) {
|
} catch(IllegalArgumentException e) {
|
||||||
return "无效的排行榜模式参数!";
|
return "无效的排行榜模式参数!";
|
||||||
}
|
}
|
||||||
@ -225,10 +226,13 @@ public class BotAdminCommandProcess {
|
|||||||
} catch(NoSuchElementException ignored) {
|
} catch(NoSuchElementException ignored) {
|
||||||
}
|
}
|
||||||
|
|
||||||
int rankingStart = setting.has(RANKING_SETTING_RANKING_START) ? setting.get(RANKING_SETTING_RANKING_START).getAsInt() : 1;
|
int rankingStart = setting.has(RANKING_SETTING_RANKING_START) ?
|
||||||
int rankingEnd = setting.has(RANKING_SETTING_RANKING_END) ? setting.get(RANKING_SETTING_RANKING_END).getAsInt() : 150;
|
setting.get(RANKING_SETTING_RANKING_START).getAsInt() : 1;
|
||||||
PixivURL.RankingMode rankingMode = PixivURL.RankingMode.MODE_DAILY;
|
int rankingEnd = setting.has(RANKING_SETTING_RANKING_END) ?
|
||||||
PixivURL.RankingContentType rankingContentType = PixivURL.RankingContentType.TYPE_ILLUST;
|
setting.get(RANKING_SETTING_RANKING_END).getAsInt() : 150;
|
||||||
|
|
||||||
|
RankingMode rankingMode = RankingMode.MODE_DAILY;
|
||||||
|
RankingContentType rankingContentType = RankingContentType.TYPE_ILLUST;
|
||||||
PixivDownload.PageQuality pageQuality = PixivDownload.PageQuality.REGULAR;
|
PixivDownload.PageQuality pageQuality = PixivDownload.PageQuality.REGULAR;
|
||||||
|
|
||||||
if(rankingStart <= 0 || rankingStart > 500) {
|
if(rankingStart <= 0 || rankingStart > 500) {
|
||||||
@ -246,7 +250,7 @@ public class BotAdminCommandProcess {
|
|||||||
if(setting.has(RANKING_SETTING_RANKING_MODE)) {
|
if(setting.has(RANKING_SETTING_RANKING_MODE)) {
|
||||||
String value = setting.get(RANKING_SETTING_RANKING_MODE).getAsString().trim().toUpperCase();
|
String value = setting.get(RANKING_SETTING_RANKING_MODE).getAsString().trim().toUpperCase();
|
||||||
try {
|
try {
|
||||||
rankingMode = PixivURL.RankingMode.valueOf(value.startsWith("MODE_") ? value : "MODE_" + value);
|
rankingMode = RankingMode.valueOf(value.startsWith("MODE_") ? value : "MODE_" + value);
|
||||||
} catch(IllegalArgumentException e) {
|
} catch(IllegalArgumentException e) {
|
||||||
log.warn("群组ID [{}] - 无效的RankingMode设定值, 将重置为默认值: {}", id, value);
|
log.warn("群组ID [{}] - 无效的RankingMode设定值, 将重置为默认值: {}", id, value);
|
||||||
}
|
}
|
||||||
@ -254,7 +258,7 @@ public class BotAdminCommandProcess {
|
|||||||
if(setting.has(RANKING_SETTING_RANKING_CONTENT_TYPE)) {
|
if(setting.has(RANKING_SETTING_RANKING_CONTENT_TYPE)) {
|
||||||
String value = setting.get(RANKING_SETTING_RANKING_CONTENT_TYPE).getAsString().trim().toUpperCase();
|
String value = setting.get(RANKING_SETTING_RANKING_CONTENT_TYPE).getAsString().trim().toUpperCase();
|
||||||
try {
|
try {
|
||||||
rankingContentType = PixivURL.RankingContentType.valueOf(value.startsWith("TYPE_") ? value : "TYPE_" + value);
|
rankingContentType = RankingContentType.valueOf(value.startsWith("TYPE_") ? value : "TYPE_" + value);
|
||||||
} catch(IllegalArgumentException e) {
|
} catch(IllegalArgumentException e) {
|
||||||
log.warn("群组ID [{}] - 无效的RankingContentType设定值: {}", id, value);
|
log.warn("群组ID [{}] - 无效的RankingContentType设定值: {}", id, value);
|
||||||
}
|
}
|
||||||
@ -293,7 +297,10 @@ public class BotAdminCommandProcess {
|
|||||||
* @throws NoSuchElementException 当这个群号没有定时器的时候抛出异常
|
* @throws NoSuchElementException 当这个群号没有定时器的时候抛出异常
|
||||||
*/
|
*/
|
||||||
@Command
|
@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;
|
long group = id <= 0 ? fromGroup : id;
|
||||||
RandomIntervalSendTimer.getTimerById(group).destroy();
|
RandomIntervalSendTimer.getTimerById(group).destroy();
|
||||||
pushInfoMap.remove(group);
|
pushInfoMap.remove(group);
|
||||||
@ -324,7 +331,8 @@ public class BotAdminCommandProcess {
|
|||||||
log.debug("{} - Report: {}", illustIdStr, report);
|
log.debug("{} - Report: {}", illustIdStr, report);
|
||||||
String reason = report.get("reason").isJsonNull() ? "" : report.get("reason").getAsString();
|
String reason = report.get("reason").isJsonNull() ? "" : report.get("reason").getAsString();
|
||||||
msgBuilder.append(count).append(". 作品Id: ").append(illustIdStr)
|
msgBuilder.append(count).append(". 作品Id: ").append(illustIdStr)
|
||||||
.append("(").append(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("报告者QQ:").append(report.get("fromQQ").getAsLong()).append("\n")
|
||||||
.append("报告所在群:").append(report.get("fromGroup").getAsLong()).append("\n")
|
.append("报告所在群:").append(report.get("fromGroup").getAsLong()).append("\n")
|
||||||
.append("报告原因:\n").append(reason).append("\n");
|
.append("报告原因:\n").append(reason).append("\n");
|
||||||
|
@ -11,10 +11,9 @@ import net.lamgc.cgj.bot.cache.JsonRedisCacheStore;
|
|||||||
import net.lamgc.cgj.bot.event.BufferedMessageSender;
|
import net.lamgc.cgj.bot.event.BufferedMessageSender;
|
||||||
import net.lamgc.cgj.bot.sort.PreLoadDataAttribute;
|
import net.lamgc.cgj.bot.sort.PreLoadDataAttribute;
|
||||||
import net.lamgc.cgj.bot.sort.PreLoadDataAttributeComparator;
|
import net.lamgc.cgj.bot.sort.PreLoadDataAttributeComparator;
|
||||||
import net.lamgc.cgj.pixiv.PixivDownload;
|
import net.lamgc.cgj.pixiv.*;
|
||||||
import net.lamgc.cgj.pixiv.PixivDownload.PageQuality;
|
import net.lamgc.cgj.pixiv.PixivDownload.PageQuality;
|
||||||
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
|
import net.lamgc.cgj.util.PixivUtils;
|
||||||
import net.lamgc.cgj.pixiv.PixivURL;
|
|
||||||
import net.lamgc.utils.base.runner.Argument;
|
import net.lamgc.utils.base.runner.Argument;
|
||||||
import net.lamgc.utils.base.runner.Command;
|
import net.lamgc.utils.base.runner.Command;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@ -40,6 +39,8 @@ public class BotCommandProcess {
|
|||||||
|
|
||||||
private final static RankingUpdateTimer updateTimer = new RankingUpdateTimer();
|
private final static RankingUpdateTimer updateTimer = new RankingUpdateTimer();
|
||||||
|
|
||||||
|
private final static int SEARCH_PAGE_MAX_ITEM = 60;
|
||||||
|
|
||||||
public static void initialize() {
|
public static void initialize() {
|
||||||
log.info("正在初始化...");
|
log.info("正在初始化...");
|
||||||
|
|
||||||
@ -142,9 +143,14 @@ public class BotCommandProcess {
|
|||||||
@Argument(name = "$fromGroup") long fromGroup,
|
@Argument(name = "$fromGroup") long fromGroup,
|
||||||
@Argument(force = false, name = "date") Date queryTime,
|
@Argument(force = false, name = "date") Date queryTime,
|
||||||
@Argument(force = false, name = "force") boolean force,
|
@Argument(force = false, name = "force") boolean force,
|
||||||
@Argument(force = false, name = "mode", defaultValue = "DAILY") String contentMode,
|
@Argument(force = false, name = "mode", defaultValue = "DAILY") RankingMode contentMode,
|
||||||
@Argument(force = false, name = "type", defaultValue = "ALL") String contentType
|
@Argument(force = false, name = "type", defaultValue = "ALL") RankingContentType contentType,
|
||||||
|
@Argument(force = false, name = "p", defaultValue = "1") int pageIndex
|
||||||
) throws InterruptedException {
|
) throws InterruptedException {
|
||||||
|
if(pageIndex <= 0) {
|
||||||
|
return "色图姬找不到指定页数的排行榜!";
|
||||||
|
}
|
||||||
|
|
||||||
Date queryDate = queryTime;
|
Date queryDate = queryTime;
|
||||||
if (queryDate == null) {
|
if (queryDate == null) {
|
||||||
queryDate = new Date();
|
queryDate = new Date();
|
||||||
@ -164,33 +170,13 @@ public class BotCommandProcess {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
PixivURL.RankingMode mode;
|
if(!contentType.isSupportedMode(contentMode)) {
|
||||||
try {
|
|
||||||
String rankingModeValue = contentMode.toUpperCase();
|
|
||||||
mode = PixivURL.RankingMode.valueOf(rankingModeValue.startsWith("MODE_") ?
|
|
||||||
rankingModeValue : "MODE_" + rankingModeValue);
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
log.warn("无效的RankingMode值: {}", contentMode);
|
|
||||||
return "参数无效, 请查看帮助信息";
|
|
||||||
}
|
|
||||||
|
|
||||||
PixivURL.RankingContentType type;
|
|
||||||
try {
|
|
||||||
String contentTypeValue = contentType.toUpperCase();
|
|
||||||
type = PixivURL.RankingContentType.valueOf(
|
|
||||||
contentTypeValue.startsWith("TYPE_") ? contentTypeValue : "TYPE_" + contentTypeValue);
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
log.warn("无效的RankingContentType值: {}", contentType);
|
|
||||||
return "参数无效, 请查看帮助信息";
|
|
||||||
}
|
|
||||||
|
|
||||||
if(!type.isSupportedMode(mode)) {
|
|
||||||
log.warn("RankingContentType不支持指定的RankingMode.(ContentType: {}, RankingMode: {})",
|
log.warn("RankingContentType不支持指定的RankingMode.(ContentType: {}, RankingMode: {})",
|
||||||
type.name(), mode.name());
|
contentType.name(), contentMode.name());
|
||||||
return "不支持的内容类型或模式!";
|
return "不支持的内容类型或模式!";
|
||||||
}
|
}
|
||||||
|
|
||||||
StringBuilder resultBuilder = new StringBuilder(mode.name() + " - 以下是 ")
|
StringBuilder resultBuilder = new StringBuilder(contentMode.name() + " - 以下是 ")
|
||||||
.append(new SimpleDateFormat("yyyy-MM-dd").format(queryDate)).append(" 的Pixiv插画排名榜前十名:\n");
|
.append(new SimpleDateFormat("yyyy-MM-dd").format(queryDate)).append(" 的Pixiv插画排名榜前十名:\n");
|
||||||
try {
|
try {
|
||||||
int index = 0;
|
int index = 0;
|
||||||
@ -212,8 +198,10 @@ public class BotCommandProcess {
|
|||||||
log.warn("配置项 {} 的参数值格式有误!", imageLimitPropertyKey);
|
log.warn("配置项 {} 的参数值格式有误!", imageLimitPropertyKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int startsIndex = itemLimit * pageIndex - (itemLimit - 1);
|
||||||
List<JsonObject> rankingInfoList = CacheStoreCentral.getCentral()
|
List<JsonObject> rankingInfoList = CacheStoreCentral.getCentral()
|
||||||
.getRankingInfoByCache(type, mode, queryDate, 1, Math.max(0, itemLimit), false);
|
.getRankingInfoByCache(contentType, contentMode, queryDate,
|
||||||
|
Math.max(1, startsIndex), Math.max(0, itemLimit), false);
|
||||||
if(rankingInfoList.isEmpty()) {
|
if(rankingInfoList.isEmpty()) {
|
||||||
return "无法查询排行榜,可能排行榜尚未更新。";
|
return "无法查询排行榜,可能排行榜尚未更新。";
|
||||||
}
|
}
|
||||||
@ -232,7 +220,7 @@ public class BotCommandProcess {
|
|||||||
if (index <= imageLimit) {
|
if (index <= imageLimit) {
|
||||||
resultBuilder
|
resultBuilder
|
||||||
.append(CacheStoreCentral.getCentral()
|
.append(CacheStoreCentral.getCentral()
|
||||||
.getImageById(fromGroup, illustId, PixivDownload.PageQuality.REGULAR, 1))
|
.getImageById(fromGroup, illustId, PageQuality.REGULAR, 1))
|
||||||
.append("\n");
|
.append("\n");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -262,20 +250,20 @@ public class BotCommandProcess {
|
|||||||
@Argument(name = "$fromGroup") long fromGroup,
|
@Argument(name = "$fromGroup") long fromGroup,
|
||||||
@Argument(force = false, name = "mode", defaultValue = "DAILY") String contentMode,
|
@Argument(force = false, name = "mode", defaultValue = "DAILY") String contentMode,
|
||||||
@Argument(force = false, name = "type", defaultValue = "ILLUST") String contentType) {
|
@Argument(force = false, name = "type", defaultValue = "ILLUST") String contentType) {
|
||||||
PixivURL.RankingMode mode;
|
RankingMode mode;
|
||||||
try {
|
try {
|
||||||
String rankingModeValue = contentMode.toUpperCase();
|
String rankingModeValue = contentMode.toUpperCase();
|
||||||
mode = PixivURL.RankingMode.valueOf(rankingModeValue.startsWith("MODE_") ?
|
mode = RankingMode.valueOf(rankingModeValue.startsWith("MODE_") ?
|
||||||
rankingModeValue : "MODE_" + rankingModeValue);
|
rankingModeValue : "MODE_" + rankingModeValue);
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("无效的RankingMode值: {}", contentMode);
|
log.warn("无效的RankingMode值: {}", contentMode);
|
||||||
return "参数无效, 请查看帮助信息";
|
return "参数无效, 请查看帮助信息";
|
||||||
}
|
}
|
||||||
|
|
||||||
PixivURL.RankingContentType type;
|
RankingContentType type;
|
||||||
try {
|
try {
|
||||||
String contentTypeValue = contentType.toUpperCase();
|
String contentTypeValue = contentType.toUpperCase();
|
||||||
type = PixivURL.RankingContentType.valueOf(
|
type = RankingContentType.valueOf(
|
||||||
contentTypeValue.startsWith("TYPE_") ? contentTypeValue : "TYPE_" + contentTypeValue);
|
contentTypeValue.startsWith("TYPE_") ? contentTypeValue : "TYPE_" + contentTypeValue);
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("无效的RankingContentType值: {}", contentType);
|
log.warn("无效的RankingContentType值: {}", contentType);
|
||||||
@ -314,12 +302,9 @@ public class BotCommandProcess {
|
|||||||
@Argument(name = "option", force = false) String contentOption,
|
@Argument(name = "option", force = false) String contentOption,
|
||||||
@Argument(name = "p", force = false, defaultValue = "1") int pagesIndex
|
@Argument(name = "p", force = false, defaultValue = "1") int pagesIndex
|
||||||
) throws IOException, InterruptedException {
|
) throws IOException, InterruptedException {
|
||||||
|
PixivSearchLinkBuilder searchLinkBuilder = PixivUtils.buildSearchLinkBuilderFromString(content, type, area,
|
||||||
|
includeKeywords, excludeKeywords, contentOption, pagesIndex);
|
||||||
log.debug("正在执行搜索...");
|
log.debug("正在执行搜索...");
|
||||||
JsonObject resultBody = CacheStoreCentral.getCentral()
|
|
||||||
.getSearchBody(content, type, area, includeKeywords, excludeKeywords, contentOption, pagesIndex);
|
|
||||||
|
|
||||||
StringBuilder result = new StringBuilder("内容 " + content + " 的搜索结果:\n");
|
|
||||||
log.debug("正在处理信息...");
|
|
||||||
int limit = 8;
|
int limit = 8;
|
||||||
try {
|
try {
|
||||||
limit = Integer.parseInt(SettingProperties.
|
limit = Integer.parseInt(SettingProperties.
|
||||||
@ -327,95 +312,112 @@ public class BotCommandProcess {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("参数转换异常!将使用默认值(" + limit + ")", e);
|
log.warn("参数转换异常!将使用默认值(" + limit + ")", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
int totalCount = 0;
|
int totalCount = 0;
|
||||||
for (PixivSearchLinkBuilder.SearchArea searchArea : PixivSearchLinkBuilder.SearchArea.values()) {
|
StringBuilder result = new StringBuilder("内容 " + content + " 的搜索结果:\n");
|
||||||
if (!resultBody.has(searchArea.jsonKey) ||
|
List<JsonObject> artworkList = getSearchResult(searchLinkBuilder, fromGroup, limit, pagesIndex);
|
||||||
resultBody.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data").size() == 0) {
|
artworkList.sort(new PreLoadDataAttributeComparator(PreLoadDataAttribute.LIKE));
|
||||||
log.debug("返回数据不包含 {}", searchArea.jsonKey);
|
int startIndex = limit * pagesIndex - limit + 1;
|
||||||
continue;
|
int pageStartIndex = startIndex % SEARCH_PAGE_MAX_ITEM;
|
||||||
}
|
for(int index = pageStartIndex; totalCount < limit && index < artworkList.size(); index++) {
|
||||||
JsonArray illustsArray = resultBody
|
int illustId = artworkList.get(index - 1).get("illustId").getAsInt();
|
||||||
.getAsJsonObject(searchArea.jsonKey).getAsJsonArray("data");
|
// 预加载数据有更多信息可以提供
|
||||||
ArrayList<JsonElement> illustsList = new ArrayList<>();
|
JsonObject artworkPreLoadData = CacheStoreCentral.getCentral()
|
||||||
illustsArray.forEach(illustsList::add);
|
.getIllustPreLoadData(illustId, false);
|
||||||
illustsList.sort(new PreLoadDataAttributeComparator(PreLoadDataAttribute.BOOKMARK));
|
|
||||||
|
|
||||||
log.debug("已找到与 {} 相关插图信息({}):", content, searchArea.name().toLowerCase());
|
// 构造消息内容
|
||||||
int count = 1;
|
result.append(startIndex++).append(". (").append(artworkPreLoadData.get("illustId").getAsInt()).append(") ")
|
||||||
for (JsonElement jsonElement : illustsList) {
|
.append(artworkPreLoadData.get("illustTitle").getAsString());
|
||||||
if (count > limit) {
|
result.append("\n\t").append("作者:").append(artworkPreLoadData.get("userName").getAsString());
|
||||||
break;
|
result.append("\n\t").append("作品页数:").append(artworkPreLoadData.get("pageCount").getAsInt()).append(" 页");
|
||||||
}
|
result.append("\n\t").append("点赞数:")
|
||||||
JsonObject illustObj = jsonElement.getAsJsonObject();
|
.append(artworkPreLoadData.get(PreLoadDataAttribute.LIKE.attrName).getAsInt()).append(" 页");
|
||||||
if (!illustObj.has("illustId")) {
|
result.append("\n\t").append("收藏数:")
|
||||||
continue;
|
.append(artworkPreLoadData.get(PreLoadDataAttribute.BOOKMARK.attrName).getAsInt()).append(" 页");
|
||||||
}
|
result.append("\n\t").append("围观数:")
|
||||||
int illustId = illustObj.get("illustId").getAsInt();
|
.append(artworkPreLoadData.get(PreLoadDataAttribute.VIEW.attrName).getAsInt()).append(" 页");
|
||||||
StringBuilder builder = new StringBuilder("[");
|
result.append("\n\t").append("评论数:")
|
||||||
illustObj.get("tags").getAsJsonArray().forEach(el -> builder.append(el.getAsString()).append(", "));
|
.append(artworkPreLoadData.get(PreLoadDataAttribute.COMMENT.attrName).getAsInt()).append(" 页");
|
||||||
builder.replace(builder.length() - 2, builder.length(), "]");
|
result.append(CacheStoreCentral.getCentral()
|
||||||
log.debug("{} ({} / {})\n\t作品id: {}, \n\t作者名(作者id): {} ({}), \n\t" +
|
.getImageById(fromGroup, illustId, PageQuality.REGULAR, 1)).append("\n");
|
||||||
"作品标题: {}, \n\t作品Tags: {}, \n\t页数: {}页, \n\t作品链接: {}",
|
totalCount++;
|
||||||
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 ?
|
return totalCount <= 0 ?
|
||||||
"搜索完成,未找到相关作品。" :
|
"搜索完成,未找到相关作品。" :
|
||||||
Strings.nullToEmpty(result.toString()) + "预览图片并非原图,使用“.cgj image -id 作品id”获取原图\n" +
|
Strings.nullToEmpty(result.toString()) + "预览图片并非原图,使用“.cgj image -id 作品id”获取原图\n" +
|
||||||
"如有不当作品,可使用\".cgj report -id 作品id\"向色图姬反馈。";
|
"如有不当作品,可使用\".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
|
* @param illustId 作品Id
|
||||||
|
@ -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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,8 @@ import com.google.gson.JsonObject;
|
|||||||
import net.lamgc.cgj.bot.cache.CacheStoreCentral;
|
import net.lamgc.cgj.bot.cache.CacheStoreCentral;
|
||||||
import net.lamgc.cgj.bot.message.MessageSender;
|
import net.lamgc.cgj.bot.message.MessageSender;
|
||||||
import net.lamgc.cgj.pixiv.PixivDownload;
|
import net.lamgc.cgj.pixiv.PixivDownload;
|
||||||
import net.lamgc.cgj.pixiv.PixivURL;
|
import net.lamgc.cgj.pixiv.RankingContentType;
|
||||||
|
import net.lamgc.cgj.pixiv.RankingMode;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
@ -22,8 +23,8 @@ public class RandomRankingArtworksSender extends AutoSender {
|
|||||||
private final long groupId;
|
private final long groupId;
|
||||||
private final int rankingStart;
|
private final int rankingStart;
|
||||||
private final int rankingStop;
|
private final int rankingStop;
|
||||||
private final PixivURL.RankingMode mode;
|
private final RankingMode mode;
|
||||||
private final PixivURL.RankingContentType contentType;
|
private final RankingContentType contentType;
|
||||||
private final PixivDownload.PageQuality quality;
|
private final PixivDownload.PageQuality quality;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -40,8 +41,8 @@ public class RandomRankingArtworksSender extends AutoSender {
|
|||||||
MessageSender messageSender,
|
MessageSender messageSender,
|
||||||
int rankingStart,
|
int rankingStart,
|
||||||
int rankingStop,
|
int rankingStop,
|
||||||
PixivURL.RankingMode mode,
|
RankingMode mode,
|
||||||
PixivURL.RankingContentType contentType,
|
RankingContentType contentType,
|
||||||
PixivDownload.PageQuality quality) {
|
PixivDownload.PageQuality quality) {
|
||||||
this(messageSender, 0, rankingStart, rankingStop, mode, contentType, quality);
|
this(messageSender, 0, rankingStart, rankingStop, mode, contentType, quality);
|
||||||
}
|
}
|
||||||
@ -62,8 +63,8 @@ public class RandomRankingArtworksSender extends AutoSender {
|
|||||||
long groupId,
|
long groupId,
|
||||||
int rankingStart,
|
int rankingStart,
|
||||||
int rankingStop,
|
int rankingStop,
|
||||||
PixivURL.RankingMode mode,
|
RankingMode mode,
|
||||||
PixivURL.RankingContentType contentType,
|
RankingContentType contentType,
|
||||||
PixivDownload.PageQuality quality) {
|
PixivDownload.PageQuality quality) {
|
||||||
super(messageSender);
|
super(messageSender);
|
||||||
this.groupId = groupId;
|
this.groupId = groupId;
|
||||||
@ -73,7 +74,8 @@ public class RandomRankingArtworksSender extends AutoSender {
|
|||||||
this.rankingStart = rankingStart > 0 ? rankingStart : 1;
|
this.rankingStart = rankingStart > 0 ? rankingStart : 1;
|
||||||
this.rankingStop = rankingStop > 0 ? rankingStop : 150;
|
this.rankingStop = rankingStop > 0 ? rankingStop : 150;
|
||||||
if(this.rankingStart > this.rankingStop) {
|
if(this.rankingStart > this.rankingStop) {
|
||||||
throw new IndexOutOfBoundsException("rankingStart=" + this.rankingStart + ", rankingStop=" + this.rankingStop);
|
throw new IndexOutOfBoundsException(
|
||||||
|
"rankingStart=" + this.rankingStart + ", rankingStop=" + this.rankingStop);
|
||||||
}
|
}
|
||||||
this.quality = quality == null ? PixivDownload.PageQuality.REGULAR : quality;
|
this.quality = quality == null ? PixivDownload.PageQuality.REGULAR : quality;
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,8 @@ package net.lamgc.cgj.bot;
|
|||||||
|
|
||||||
import net.lamgc.cgj.bot.event.BotEventHandler;
|
import net.lamgc.cgj.bot.event.BotEventHandler;
|
||||||
import net.lamgc.cgj.bot.event.VirtualLoadMessageEvent;
|
import net.lamgc.cgj.bot.event.VirtualLoadMessageEvent;
|
||||||
import net.lamgc.cgj.pixiv.PixivURL;
|
import net.lamgc.cgj.pixiv.RankingContentType;
|
||||||
|
import net.lamgc.cgj.pixiv.RankingMode;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
@ -64,14 +65,15 @@ public class RankingUpdateTimer {
|
|||||||
|
|
||||||
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
|
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
|
||||||
log.info("正在获取 {} 期排行榜数据...", calendar.getTime());
|
log.info("正在获取 {} 期排行榜数据...", calendar.getTime());
|
||||||
for (PixivURL.RankingMode rankingMode : PixivURL.RankingMode.values()) {
|
for (RankingMode rankingMode : RankingMode.values()) {
|
||||||
for (PixivURL.RankingContentType contentType : PixivURL.RankingContentType.values()) {
|
for (RankingContentType contentType : RankingContentType.values()) {
|
||||||
if(!contentType.isSupportedMode(rankingMode)) {
|
if(!contentType.isSupportedMode(rankingMode)) {
|
||||||
log.debug("不支持的类型, 填空值跳过...(类型: {}.{})", rankingMode.name(), contentType.name());
|
log.debug("不支持的类型, 填空值跳过...(类型: {}.{})", rankingMode.name(), contentType.name());
|
||||||
}
|
}
|
||||||
log.info("当前排行榜类型: {}.{}, 正在更新...", rankingMode.name(), contentType.name());
|
log.info("当前排行榜类型: {}.{}, 正在更新...", rankingMode.name(), contentType.name());
|
||||||
BotEventHandler.executeMessageEvent(new VirtualLoadMessageEvent(0,0,
|
BotEventHandler.executeMessageEvent(new VirtualLoadMessageEvent(0,0,
|
||||||
".cgj ranking -type=" + contentType.name() + " -mode=" + rankingMode.name() + " -force -date " + dateStr));
|
".cgj ranking -type=" + contentType.name() +
|
||||||
|
" -mode=" + rankingMode.name() + " -force -date " + dateStr));
|
||||||
log.info("排行榜 {}.{} 负载指令已投递.", rankingMode.name(), contentType.name());
|
log.info("排行榜 {}.{} 负载指令已投递.", rankingMode.name(), contentType.name());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,8 @@ import net.lamgc.cgj.bot.boot.BotGlobal;
|
|||||||
import net.lamgc.cgj.exception.HttpRequestException;
|
import net.lamgc.cgj.exception.HttpRequestException;
|
||||||
import net.lamgc.cgj.pixiv.PixivDownload;
|
import net.lamgc.cgj.pixiv.PixivDownload;
|
||||||
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
|
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
|
||||||
import net.lamgc.cgj.pixiv.PixivURL;
|
import net.lamgc.cgj.pixiv.RankingContentType;
|
||||||
|
import net.lamgc.cgj.pixiv.RankingMode;
|
||||||
import net.lamgc.cgj.util.Locker;
|
import net.lamgc.cgj.util.Locker;
|
||||||
import net.lamgc.cgj.util.LockerMap;
|
import net.lamgc.cgj.util.LockerMap;
|
||||||
import net.lamgc.cgj.util.URLs;
|
import net.lamgc.cgj.util.URLs;
|
||||||
@ -124,7 +125,8 @@ public final class CacheStoreCentral {
|
|||||||
* @param pageIndex 指定页面索引, 从1开始
|
* @param pageIndex 指定页面索引, 从1开始
|
||||||
* @return 如果成功, 返回BotCode, 否则返回错误信息.
|
* @return 如果成功, 返回BotCode, 否则返回错误信息.
|
||||||
*/
|
*/
|
||||||
public String getImageById(long fromGroup, int illustId, PixivDownload.PageQuality quality, int pageIndex) 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);
|
log.debug("IllustId: {}, Quality: {}, PageIndex: {}", illustId, quality.name(), pageIndex);
|
||||||
if(pageIndex <= 0) {
|
if(pageIndex <= 0) {
|
||||||
log.warn("指定的页数不能小于或等于0: {}", pageIndex);
|
log.warn("指定的页数不能小于或等于0: {}", pageIndex);
|
||||||
@ -354,9 +356,9 @@ public final class CacheStoreCentral {
|
|||||||
* @return 成功返回有值List, 失败且无异常返回空
|
* @return 成功返回有值List, 失败且无异常返回空
|
||||||
* @throws IOException 获取异常时抛出
|
* @throws IOException 获取异常时抛出
|
||||||
*/
|
*/
|
||||||
public List<JsonObject> getRankingInfoByCache(PixivURL.RankingContentType contentType,
|
public List<JsonObject> getRankingInfoByCache(RankingContentType contentType,
|
||||||
PixivURL.RankingMode mode,
|
RankingMode mode,
|
||||||
Date queryDate, int start, int range, boolean flushCache)
|
Date queryDate, int start, int range, boolean flushCache)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
if(!contentType.isSupportedMode(mode)) {
|
if(!contentType.isSupportedMode(mode)) {
|
||||||
log.warn("试图获取不支持的排行榜类型已拒绝.(ContentType: {}, RankingMode: {})", contentType.name(), mode.name());
|
log.warn("试图获取不支持的排行榜类型已拒绝.(ContentType: {}, RankingMode: {})", contentType.name(), mode.name());
|
||||||
@ -402,84 +404,29 @@ public final class CacheStoreCentral {
|
|||||||
result = rankingCache.getCache(requestSign, start - 1, range);
|
result = rankingCache.getCache(requestSign, start - 1, range);
|
||||||
log.trace("RequestSign [{}] 缓存命中.", requestSign);
|
log.trace("RequestSign [{}] 缓存命中.", requestSign);
|
||||||
}
|
}
|
||||||
return PixivDownload.getRanking(result, start - 1, range);
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取搜索结果
|
* 获取搜索结果
|
||||||
* @param content 搜索内容
|
* @param searchBuilder 需要执行搜索的搜索链接构造器
|
||||||
* @param type 类型
|
|
||||||
* @param area 范围
|
|
||||||
* @param includeKeywords 包含关键词
|
|
||||||
* @param excludeKeywords 排除关键词
|
|
||||||
* @param contentOption 内容类型
|
|
||||||
* @return 返回完整搜索结果
|
* @return 返回完整搜索结果
|
||||||
* @throws IOException 当请求发生异常, 或接口返回异常信息时抛出.
|
* @throws IOException 当请求发生异常, 或接口返回异常信息时抛出.
|
||||||
*/
|
*/
|
||||||
public JsonObject getSearchBody(
|
public JsonObject getSearchBody(PixivSearchLinkBuilder searchBuilder) throws IOException {
|
||||||
String content,
|
|
||||||
String type,
|
|
||||||
String area,
|
|
||||||
String includeKeywords,
|
|
||||||
String excludeKeywords,
|
|
||||||
String contentOption,
|
|
||||||
int pageIndex
|
|
||||||
) throws IOException {
|
|
||||||
PixivSearchLinkBuilder searchBuilder = new PixivSearchLinkBuilder(Strings.isNullOrEmpty(content) ? "" : content);
|
|
||||||
if (type != null) {
|
|
||||||
try {
|
|
||||||
searchBuilder.setSearchType(PixivSearchLinkBuilder.SearchType.valueOf(type.toUpperCase()));
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
log.warn("不支持的SearchType: {}", type);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (area != null) {
|
|
||||||
try {
|
|
||||||
searchBuilder.setSearchArea(PixivSearchLinkBuilder.SearchArea.valueOf(area));
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
log.warn("不支持的SearchArea: {}", area);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (contentOption != null) {
|
|
||||||
try {
|
|
||||||
searchBuilder.setSearchContentOption(
|
|
||||||
PixivSearchLinkBuilder.SearchContentOption.valueOf(contentOption.trim().toUpperCase()));
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
log.warn("不支持的SearchContentOption: {}", contentOption);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!Strings.isNullOrEmpty(includeKeywords)) {
|
|
||||||
for (String keyword : includeKeywords.split(";")) {
|
|
||||||
searchBuilder.removeExcludeKeyword(keyword.trim());
|
|
||||||
searchBuilder.addIncludeKeyword(keyword.trim());
|
|
||||||
log.trace("已添加关键字: {}", keyword);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!Strings.isNullOrEmpty(excludeKeywords)) {
|
|
||||||
for (String keyword : excludeKeywords.split(";")) {
|
|
||||||
searchBuilder.removeIncludeKeyword(keyword.trim());
|
|
||||||
searchBuilder.addExcludeKeyword(keyword.trim());
|
|
||||||
log.trace("已添加排除关键字: {}", keyword);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if(pageIndex > 0) {
|
|
||||||
searchBuilder.setPage(pageIndex);
|
|
||||||
}
|
|
||||||
|
|
||||||
log.debug("正在搜索作品, 条件: {}", searchBuilder.getSearchCondition());
|
log.debug("正在搜索作品, 条件: {}", searchBuilder.getSearchCondition());
|
||||||
|
String requestUrl = searchBuilder.buildURL();
|
||||||
Locker<String> locker
|
String searchIdentify =
|
||||||
= buildSyncKey(searchBuilder.buildURL());
|
requestUrl.substring(requestUrl.lastIndexOf("/", requestUrl.lastIndexOf("/") - 1) + 1);
|
||||||
String requestUrl = locker.getKey();
|
Locker<String> locker =
|
||||||
|
buildSyncKey(searchIdentify);
|
||||||
log.debug("RequestUrl: {}", requestUrl);
|
log.debug("RequestUrl: {}", requestUrl);
|
||||||
JsonObject resultBody = null;
|
JsonObject resultBody = null;
|
||||||
if(!searchBodyCache.exists(requestUrl)) {
|
if(!searchBodyCache.exists(searchIdentify)) {
|
||||||
try {
|
try {
|
||||||
locker.lock();
|
locker.lock();
|
||||||
synchronized (locker) {
|
synchronized (locker) {
|
||||||
if (!searchBodyCache.exists(requestUrl)) {
|
if (!searchBodyCache.exists(searchIdentify)) {
|
||||||
log.trace("searchBody缓存失效, 正在更新...");
|
log.trace("searchBody缓存失效, 正在更新...");
|
||||||
JsonObject jsonObject;
|
JsonObject jsonObject;
|
||||||
HttpGet httpGetRequest = BotGlobal.getGlobal().getPixivDownload().
|
HttpGet httpGetRequest = BotGlobal.getGlobal().getPixivDownload().
|
||||||
@ -504,8 +451,8 @@ public final class CacheStoreCentral {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("全局配置项 \"{}\" 值非法, 已使用默认值: {}", propValue, expire);
|
log.warn("全局配置项 \"{}\" 值非法, 已使用默认值: {}", propValue, expire);
|
||||||
}
|
}
|
||||||
resultBody = jsonObject.getAsJsonObject().getAsJsonObject("body");
|
resultBody = jsonObject;
|
||||||
searchBodyCache.update(requestUrl, jsonObject, expire);
|
searchBodyCache.update(searchIdentify, jsonObject, expire);
|
||||||
log.trace("searchBody缓存已更新(有效时间: {})", expire);
|
log.trace("searchBody缓存已更新(有效时间: {})", expire);
|
||||||
} else {
|
} else {
|
||||||
log.trace("搜索缓存命中.");
|
log.trace("搜索缓存命中.");
|
||||||
@ -519,9 +466,9 @@ public final class CacheStoreCentral {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if(Objects.isNull(resultBody)) {
|
if(Objects.isNull(resultBody)) {
|
||||||
resultBody = searchBodyCache.getCache(requestUrl).getAsJsonObject().getAsJsonObject("body");
|
resultBody = searchBodyCache.getCache(searchIdentify).getAsJsonObject();
|
||||||
}
|
}
|
||||||
return resultBody;
|
return resultBody.getAsJsonObject("body");
|
||||||
}
|
}
|
||||||
|
|
||||||
protected ImageChecksum getImageChecksum(int illustId, int pageIndex) {
|
protected ImageChecksum getImageChecksum(int illustId, int pageIndex) {
|
||||||
|
@ -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;
|
||||||
|
@ -7,17 +7,18 @@ import net.lamgc.cgj.bot.BotAdminCommandProcess;
|
|||||||
import net.lamgc.cgj.bot.BotCommandProcess;
|
import net.lamgc.cgj.bot.BotCommandProcess;
|
||||||
import net.lamgc.cgj.bot.MessageEventExecutionDebugger;
|
import net.lamgc.cgj.bot.MessageEventExecutionDebugger;
|
||||||
import net.lamgc.cgj.bot.SettingProperties;
|
import net.lamgc.cgj.bot.SettingProperties;
|
||||||
import net.lamgc.cgj.util.DateParser;
|
import net.lamgc.cgj.bot.util.parser.DateParser;
|
||||||
import net.lamgc.cgj.util.PagesQualityParser;
|
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.TimeLimitThreadPoolExecutor;
|
import net.lamgc.cgj.util.TimeLimitThreadPoolExecutor;
|
||||||
import net.lamgc.utils.base.runner.ArgumentsRunner;
|
import net.lamgc.utils.base.runner.ArgumentsRunner;
|
||||||
import net.lamgc.utils.base.runner.ArgumentsRunnerConfig;
|
import net.lamgc.utils.base.runner.ArgumentsRunnerConfig;
|
||||||
import net.lamgc.utils.base.runner.exception.DeveloperRunnerException;
|
import net.lamgc.utils.base.runner.exception.DeveloperRunnerException;
|
||||||
import net.lamgc.utils.base.runner.exception.NoSuchCommandException;
|
import net.lamgc.utils.base.runner.exception.NoSuchCommandException;
|
||||||
import net.lamgc.utils.base.runner.exception.ParameterNoFoundException;
|
import net.lamgc.utils.base.runner.exception.ParameterNoFoundException;
|
||||||
import net.lamgc.utils.event.*;
|
|
||||||
import net.lamgc.utils.event.EventObject;
|
import net.lamgc.utils.event.EventObject;
|
||||||
|
import net.lamgc.utils.event.*;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
@ -26,7 +27,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 +40,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),
|
||||||
@ -73,7 +71,13 @@ public class BotEventHandler implements EventHandler {
|
|||||||
executor.setEventUncaughtExceptionHandler(new EventUncaughtExceptionHandler() {
|
executor.setEventUncaughtExceptionHandler(new EventUncaughtExceptionHandler() {
|
||||||
private final Logger log = LoggerFactory.getLogger(this.getClass());
|
private final Logger log = LoggerFactory.getLogger(this.getClass());
|
||||||
@Override
|
@Override
|
||||||
public void exceptionHandler(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" +
|
log.error("EventExecutor@{} 发生未捕获异常:\n\t" +
|
||||||
"Thread:{}\n\tEventHandler: {}\n\tHandlerMethod: {}\n\tEventObject: {}\n" +
|
"Thread:{}\n\tEventHandler: {}\n\tHandlerMethod: {}\n\tEventObject: {}\n" +
|
||||||
"------------------ Stack Trace ------------------\n{}",
|
"------------------ Stack Trace ------------------\n{}",
|
||||||
@ -106,8 +110,11 @@ public class BotEventHandler implements EventHandler {
|
|||||||
ArgumentsRunnerConfig runnerConfig = new ArgumentsRunnerConfig();
|
ArgumentsRunnerConfig runnerConfig = new ArgumentsRunnerConfig();
|
||||||
runnerConfig.setUseDefaultValueInsteadOfException(true);
|
runnerConfig.setUseDefaultValueInsteadOfException(true);
|
||||||
runnerConfig.setCommandIgnoreCase(true);
|
runnerConfig.setCommandIgnoreCase(true);
|
||||||
|
|
||||||
runnerConfig.addStringParameterParser(new DateParser(new SimpleDateFormat("yyyy-MM-dd")));
|
runnerConfig.addStringParameterParser(new DateParser(new SimpleDateFormat("yyyy-MM-dd")));
|
||||||
runnerConfig.addStringParameterParser(new PagesQualityParser());
|
runnerConfig.addStringParameterParser(new PagesQualityParser());
|
||||||
|
runnerConfig.addStringParameterParser(new RankingModeParser());
|
||||||
|
runnerConfig.addStringParameterParser(new RankingContentTypeParser());
|
||||||
|
|
||||||
processRunner = new ArgumentsRunner(BotCommandProcess.class, runnerConfig);
|
processRunner = new ArgumentsRunner(BotCommandProcess.class, runnerConfig);
|
||||||
adminRunner = new ArgumentsRunner(BotAdminCommandProcess.class, runnerConfig);
|
adminRunner = new ArgumentsRunner(BotAdminCommandProcess.class, runnerConfig);
|
||||||
@ -140,7 +147,8 @@ public class BotEventHandler implements EventHandler {
|
|||||||
if(!event.getMessage().startsWith(ADMIN_COMMAND_PREFIX) &&
|
if(!event.getMessage().startsWith(ADMIN_COMMAND_PREFIX) &&
|
||||||
!Strings.isNullOrEmpty(debuggerName)) {
|
!Strings.isNullOrEmpty(debuggerName)) {
|
||||||
try {
|
try {
|
||||||
MessageEventExecutionDebugger debugger = MessageEventExecutionDebugger.valueOf(debuggerName.toUpperCase());
|
MessageEventExecutionDebugger debugger =
|
||||||
|
MessageEventExecutionDebugger.valueOf(debuggerName.toUpperCase());
|
||||||
debugger.debugger.accept(executor, event, SettingProperties.getProperties(SettingProperties.GLOBAL),
|
debugger.debugger.accept(executor, event, SettingProperties.getProperties(SettingProperties.GLOBAL),
|
||||||
MessageEventExecutionDebugger.getDebuggerLogger(debugger));
|
MessageEventExecutionDebugger.getDebuggerLogger(debugger));
|
||||||
} catch(IllegalArgumentException e) {
|
} catch(IllegalArgumentException e) {
|
||||||
@ -157,6 +165,9 @@ public class BotEventHandler implements EventHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private final static Pattern MESSAGE_PATTERN =
|
||||||
|
Pattern.compile("/\\s*(\".+?\"|[^:\\s])+((\\s*:\\s*(\".+?\"|[^\\s])+)|)|(\".+?\"|[^\"\\s])+");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 以事件形式处理消息事件
|
* 以事件形式处理消息事件
|
||||||
* @param event 消息事件对象
|
* @param event 消息事件对象
|
||||||
@ -167,13 +178,9 @@ 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])+");
|
Matcher matcher = MESSAGE_PATTERN.matcher(Strings.nullToEmpty(msg));
|
||||||
Matcher matcher = pattern.matcher(Strings.nullToEmpty(msg));
|
|
||||||
List<String> argsList = new ArrayList<>();
|
List<String> argsList = new ArrayList<>();
|
||||||
while (matcher.find()) {
|
while (matcher.find()) {
|
||||||
String arg = matcher.group();
|
String arg = matcher.group();
|
||||||
@ -203,6 +210,7 @@ public class BotEventHandler implements EventHandler {
|
|||||||
args = Arrays.copyOf(args, args.length + 4);
|
args = Arrays.copyOf(args, args.length + 4);
|
||||||
argsList.toArray(args);
|
argsList.toArray(args);
|
||||||
|
|
||||||
|
String[] runnerArguments = args.length <= 1 ? new String[0] : Arrays.copyOfRange(args, 1, args.length);
|
||||||
log.info("正在处理命令...");
|
log.info("正在处理命令...");
|
||||||
long time = System.currentTimeMillis();
|
long time = System.currentTimeMillis();
|
||||||
Object result;
|
Object result;
|
||||||
@ -212,10 +220,10 @@ public class BotEventHandler implements EventHandler {
|
|||||||
.equals(SettingProperties.getProperty(0, "admin.adminId"))) {
|
.equals(SettingProperties.getProperty(0, "admin.adminId"))) {
|
||||||
result = "你没有执行该命令的权限!";
|
result = "你没有执行该命令的权限!";
|
||||||
} else {
|
} else {
|
||||||
result = adminRunner.run(args.length <= 1 ? new String[0] : Arrays.copyOfRange(args, 1, args.length));
|
result = adminRunner.run(runnerArguments);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
result = processRunner.run(args.length <= 1 ? new String[0] : Arrays.copyOfRange(args, 1, args.length));
|
result = processRunner.run(runnerArguments);
|
||||||
}
|
}
|
||||||
} catch(NoSuchCommandException e) {
|
} catch(NoSuchCommandException e) {
|
||||||
result = "没有这个命令!请使用“.cgj”查看帮助说明!";
|
result = "没有这个命令!请使用“.cgj”查看帮助说明!";
|
||||||
@ -236,7 +244,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,13 +256,12 @@ 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,
|
||||||
String.format("%.3f", ((double) processTime / (double)totalTime) * 100F), processTime,
|
String.format("%.3f", ((double) processTime / (double)totalTime) * 100F), processTime,
|
||||||
String.format("%.3f", ((double) (totalTime - processTime) / (double)totalTime) * 100F), totalTime - processTime);
|
String.format("%.3f", ((double) (totalTime - processTime) / (double)totalTime) * 100F),
|
||||||
|
totalTime - processTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -266,45 +273,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 ? "已禁言" : "已解除");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -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() + '\'' +
|
||||||
|
@ -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()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -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;
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,63 @@
|
|||||||
|
package net.lamgc.cgj.bot.framework.coolq;
|
||||||
|
|
||||||
|
import com.google.common.base.Strings;
|
||||||
|
import net.lamgc.cgj.bot.boot.BotGlobal;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
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;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class SpringCQApplication {
|
||||||
|
|
||||||
|
private final static Logger log = LoggerFactory.getLogger(SpringCQApplication.class);
|
||||||
|
|
||||||
|
private final Object quitLock = new Object();
|
||||||
|
|
||||||
|
public void start(String argsStr) {
|
||||||
|
log.info("酷Q机器人根目录: {}", BotGlobal.getGlobal().getDataStoreDir().getPath());
|
||||||
|
Pattern pattern = Pattern.compile("/\\s*(\".+?\"|[^:\\s])+((\\s*:\\s*(\".+?\"|[^\\s])+)|)|(\".+?\"|[^\"\\s])+");
|
||||||
|
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);
|
||||||
|
ConfigurableApplicationContext context = SpringApplication.run(SpringCQApplication.class, args);
|
||||||
|
registerShutdownHook(context);
|
||||||
|
try {
|
||||||
|
synchronized (quitLock) {
|
||||||
|
quitLock.wait();
|
||||||
|
}
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
log.warn("发生中断, 退出SpringCQ...", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void registerShutdownHook(ConfigurableApplicationContext context) {
|
||||||
|
context.addApplicationListener((ApplicationListener<ApplicationFailedEvent>)
|
||||||
|
event -> notifyThread());
|
||||||
|
context.addApplicationListener((ApplicationListener<ContextClosedEvent>)
|
||||||
|
event -> notifyThread());
|
||||||
|
context.addApplicationListener((ApplicationListener<ContextStoppedEvent>)
|
||||||
|
event -> notifyThread());
|
||||||
|
Runtime.getRuntime().addShutdownHook(new Thread(this::notifyThread));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void notifyThread() {
|
||||||
|
synchronized (quitLock) {
|
||||||
|
quitLock.notify();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,6 +6,7 @@ import net.lamgc.cgj.bot.event.BotEventHandler;
|
|||||||
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;
|
||||||
@ -30,7 +31,9 @@ public class MiraiMain implements Closeable {
|
|||||||
|
|
||||||
private Bot bot;
|
private Bot bot;
|
||||||
|
|
||||||
private final static Properties botProperties = new Properties();
|
private final Properties botProperties = new Properties();
|
||||||
|
|
||||||
|
private final GroupMuteManager muteManager = new GroupMuteManager();
|
||||||
|
|
||||||
public void init() {
|
public void init() {
|
||||||
Runtime.getRuntime().addShutdownHook(new Thread(this::close));
|
Runtime.getRuntime().addShutdownHook(new Thread(this::close));
|
||||||
@ -73,9 +76,9 @@ public class MiraiMain implements Closeable {
|
|||||||
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();
|
||||||
@ -89,10 +92,16 @@ public class MiraiMain implements Closeable {
|
|||||||
private void executeMessageEvent(MessageEvent message) {
|
private void executeMessageEvent(MessageEvent message) {
|
||||||
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) {
|
||||||
((GroupMessageEvent) message).getGroup().getBotMuteRemaining() != 0);
|
boolean mute = groupMessageEvent.getGroup().getBotMuteRemaining() != 0;
|
||||||
|
muteManager.setMuteState(groupMessageEvent.getGroup().getId(), mute);
|
||||||
|
if(mute) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if(muteState) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
BotEventHandler.executeMessageEvent(MiraiMessageEvent.covertEventObject(message));
|
BotEventHandler.executeMessageEvent(MiraiMessageEvent.covertEventObject(message));
|
||||||
|
48
src/main/java/net/lamgc/cgj/bot/util/GroupMuteManager.java
Normal file
48
src/main/java/net/lamgc/cgj/bot/util/GroupMuteManager.java
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package net.lamgc.cgj.util;
|
package net.lamgc.cgj.bot.util.parser;
|
||||||
|
|
||||||
import net.lamgc.utils.base.runner.StringParameterParser;
|
import net.lamgc.utils.base.runner.StringParameterParser;
|
||||||
|
|
@ -1,4 +1,4 @@
|
|||||||
package net.lamgc.cgj.util;
|
package net.lamgc.cgj.bot.util.parser;
|
||||||
|
|
||||||
import net.lamgc.cgj.pixiv.PixivDownload;
|
import net.lamgc.cgj.pixiv.PixivDownload;
|
||||||
import net.lamgc.utils.base.runner.StringParameterParser;
|
import net.lamgc.utils.base.runner.StringParameterParser;
|
@ -0,0 +1,29 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
@ -4,7 +4,6 @@ import com.google.gson.Gson;
|
|||||||
import com.google.gson.JsonArray;
|
import com.google.gson.JsonArray;
|
||||||
import com.google.gson.JsonElement;
|
import com.google.gson.JsonElement;
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
import com.google.gson.reflect.TypeToken;
|
|
||||||
import io.netty.handler.codec.http.HttpHeaderNames;
|
import io.netty.handler.codec.http.HttpHeaderNames;
|
||||||
import net.lamgc.cgj.exception.HttpRequestException;
|
import net.lamgc.cgj.exception.HttpRequestException;
|
||||||
import org.apache.http.Header;
|
import org.apache.http.Header;
|
||||||
@ -32,7 +31,6 @@ import java.util.*;
|
|||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import java.util.function.BiConsumer;
|
import java.util.function.BiConsumer;
|
||||||
|
|
||||||
@SuppressWarnings("ALL")
|
|
||||||
public class PixivDownload {
|
public class PixivDownload {
|
||||||
|
|
||||||
private final static Logger log = LoggerFactory.getLogger(PixivDownload.class);
|
private final static Logger log = LoggerFactory.getLogger(PixivDownload.class);
|
||||||
@ -58,10 +56,10 @@ public class PixivDownload {
|
|||||||
this.cookieStore = cookieStore;
|
this.cookieStore = cookieStore;
|
||||||
HttpClientBuilder builder = HttpClientBuilder.create();
|
HttpClientBuilder builder = HttpClientBuilder.create();
|
||||||
builder.setDefaultCookieStore(cookieStore);
|
builder.setDefaultCookieStore(cookieStore);
|
||||||
// UA: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36
|
|
||||||
ArrayList<Header> defaultHeaders = new ArrayList<>(2);
|
ArrayList<Header> defaultHeaders = new ArrayList<>(2);
|
||||||
defaultHeaders.add(new BasicHeader("User-Agent",
|
defaultHeaders.add(new BasicHeader("User-Agent",
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) 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.setDefaultHeaders(defaultHeaders);
|
||||||
builder.setProxy(proxy);
|
builder.setProxy(proxy);
|
||||||
httpClient = builder.build();
|
httpClient = builder.build();
|
||||||
@ -86,7 +84,8 @@ public class PixivDownload {
|
|||||||
Document document;
|
Document document;
|
||||||
ArrayList<String> linkList = new ArrayList<>();
|
ArrayList<String> linkList = new ArrayList<>();
|
||||||
do {
|
do {
|
||||||
request = new HttpGet(PixivURL.PIXIV_USER_COLLECTION_PAGE.replace("{pageIndex}", Integer.toString(++pageIndex)));
|
request = new HttpGet(PixivURL.PIXIV_USER_COLLECTION_PAGE
|
||||||
|
.replace("{pageIndex}", Integer.toString(++pageIndex)));
|
||||||
setCookieInRequest(request, cookieStore);
|
setCookieInRequest(request, cookieStore);
|
||||||
log.debug("Request Link: " + request.getURI().toString());
|
log.debug("Request Link: " + request.getURI().toString());
|
||||||
HttpResponse response = httpClient.execute(request);
|
HttpResponse response = httpClient.execute(request);
|
||||||
@ -101,10 +100,13 @@ public class PixivDownload {
|
|||||||
|
|
||||||
Gson gson = new Gson();
|
Gson gson = new Gson();
|
||||||
for (String href : hrefList) {
|
for (String href : hrefList) {
|
||||||
HttpGet linkApiRequest = createHttpGetRequest(PixivURL.PIXIV_ILLUST_API_URL.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());
|
log.debug(linkApiRequest.getURI().toString());
|
||||||
HttpResponse httpResponse = httpClient.execute(linkApiRequest);
|
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()) {
|
if(linkResult.get("error").getAsBoolean()) {
|
||||||
log.error("接口返回错误信息: {}", linkResult.get("message").getAsString());
|
log.error("接口返回错误信息: {}", linkResult.get("message").getAsString());
|
||||||
continue;
|
continue;
|
||||||
@ -113,7 +115,10 @@ public class PixivDownload {
|
|||||||
JsonArray linkArray = linkResult.get("body").getAsJsonArray();
|
JsonArray linkArray = linkResult.get("body").getAsJsonArray();
|
||||||
for (int i = 0; i < linkArray.size(); i++) {
|
for (int i = 0; i < linkArray.size(); i++) {
|
||||||
JsonObject linkObject = linkArray.get(i).getAsJsonObject().get("urls").getAsJsonObject();
|
JsonObject linkObject = linkArray.get(i).getAsJsonObject().get("urls").getAsJsonObject();
|
||||||
linkList.add(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());
|
} while(!document.select(".pager-container>.next").isEmpty());
|
||||||
@ -155,7 +160,8 @@ public class PixivDownload {
|
|||||||
Document document = Jsoup.parse(EntityUtils.toString(response.getEntity()));
|
Document document = Jsoup.parse(EntityUtils.toString(response.getEntity()));
|
||||||
|
|
||||||
HttpClient imageClient = HttpClientBuilder.create().build();
|
HttpClient imageClient = HttpClientBuilder.create().build();
|
||||||
Elements elements = document.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++){
|
for(int illustIndex = 0; illustIndex < elements.size(); illustIndex++){
|
||||||
String href = elements.get(illustIndex).attr("href");
|
String href = elements.get(illustIndex).attr("href");
|
||||||
int illustId = Integer.parseInt(href.substring(href.lastIndexOf("/") + 1));
|
int illustId = Integer.parseInt(href.substring(href.lastIndexOf("/") + 1));
|
||||||
@ -197,8 +203,14 @@ public class PixivDownload {
|
|||||||
* @param fn 回调函数
|
* @param fn 回调函数
|
||||||
* @throws IOException 当请求发生异常时抛出
|
* @throws IOException 当请求发生异常时抛出
|
||||||
*/
|
*/
|
||||||
public void getRankingAsInputStream(PixivURL.RankingContentType contentType, PixivURL.RankingMode mode,
|
public void getRankingAsInputStream(
|
||||||
Date time, int range, PageQuality quality, RankingDownloadFunction fn) throws IOException {
|
RankingContentType contentType,
|
||||||
|
RankingMode mode,
|
||||||
|
Date time,
|
||||||
|
int range,
|
||||||
|
PageQuality quality,
|
||||||
|
RankingDownloadFunction fn
|
||||||
|
) throws IOException {
|
||||||
getRankingAsInputStream(contentType, mode, time, 1, range, quality, fn);
|
getRankingAsInputStream(contentType, mode, time, 1, range, quality, fn);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -213,15 +225,23 @@ public class PixivDownload {
|
|||||||
* @param fn 回调函数
|
* @param fn 回调函数
|
||||||
* @throws IOException 当请求发生异常时抛出
|
* @throws IOException 当请求发生异常时抛出
|
||||||
*/
|
*/
|
||||||
public void getRankingAsInputStream(PixivURL.RankingContentType contentType, PixivURL.RankingMode mode,
|
public void getRankingAsInputStream(
|
||||||
Date time, int rankStart, int range, PageQuality quality, RankingDownloadFunction fn) throws IOException {
|
RankingContentType contentType,
|
||||||
|
RankingMode mode,
|
||||||
|
Date time,
|
||||||
|
int rankStart,
|
||||||
|
int range,
|
||||||
|
PageQuality quality,
|
||||||
|
RankingDownloadFunction fn
|
||||||
|
) throws IOException {
|
||||||
getRanking(contentType, mode, time, rankStart, range).forEach(rankInfo -> {
|
getRanking(contentType, mode, time, rankStart, range).forEach(rankInfo -> {
|
||||||
int rank = rankInfo.get("rank").getAsInt();
|
int rank = rankInfo.get("rank").getAsInt();
|
||||||
int illustId = rankInfo.get("illust_id").getAsInt();
|
int illustId = rankInfo.get("illust_id").getAsInt();
|
||||||
int authorId = rankInfo.get("user_id").getAsInt();
|
int authorId = rankInfo.get("user_id").getAsInt();
|
||||||
String authorName = rankInfo.get("user_name").getAsString();
|
String authorName = rankInfo.get("user_name").getAsString();
|
||||||
String title = rankInfo.get("title").getAsString();
|
String title = rankInfo.get("title").getAsString();
|
||||||
log.trace("当前到第 {}/{} 名(总共 {} 名), IllustID: {}, Author: ({}) {}, Title: {}", 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...");
|
log.trace("正在获取PagesLink...");
|
||||||
List<String> linkList;
|
List<String> linkList;
|
||||||
try {
|
try {
|
||||||
@ -238,7 +258,11 @@ public class PixivDownload {
|
|||||||
for (int pageIndex = 0; pageIndex < linkList.size(); pageIndex++) {
|
for (int pageIndex = 0; pageIndex < linkList.size(); pageIndex++) {
|
||||||
String downloadLink = linkList.get(pageIndex);
|
String downloadLink = linkList.get(pageIndex);
|
||||||
log.trace("当前Page: {}/{}", pageIndex + 1, linkList.size());
|
log.trace("当前Page: {}/{}", pageIndex + 1, linkList.size());
|
||||||
try(InputStream imageInputStream = 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);
|
fn.download(rank, downloadLink, rankInfo.deepCopy(), imageInputStream);
|
||||||
} catch(IOException e) {
|
} catch(IOException e) {
|
||||||
log.error("下载插画时发生异常", e);
|
log.error("下载插画时发生异常", e);
|
||||||
@ -249,43 +273,6 @@ 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>
|
* <p>注意: 如果范围实际上没超出, 但返回排行榜不足, 会导致与实际请求的数量不符, 需要检查</p>
|
||||||
@ -295,22 +282,24 @@ public class PixivDownload {
|
|||||||
* @param rankStart 开始排名, 从1开始
|
* @param rankStart 开始排名, 从1开始
|
||||||
* @param range 取范围
|
* @param range 取范围
|
||||||
* @return 成功返回有值List, 失败且无异常返回空
|
* @return 成功返回有值List, 失败且无异常返回空
|
||||||
* @throws IllegalArgumentException 当{@linkplain net.lamgc.cgj.pixiv.PixivURL.RankingContentType RankingContentType}
|
* @throws IllegalArgumentException 当{@linkplain net.lamgc.cgj.pixiv.RankingContentType RankingContentType}
|
||||||
* 与{@linkplain net.lamgc.cgj.pixiv.PixivURL.RankingMode RankingMode}互不兼容时抛出
|
* 与{@linkplain net.lamgc.cgj.pixiv.RankingMode RankingMode}互不兼容时抛出
|
||||||
* @throws IndexOutOfBoundsException 当排行榜选取范围超出排行榜范围时抛出(排行榜范围为 1 ~ 500 名)
|
* @throws IndexOutOfBoundsException 当排行榜选取范围超出排行榜范围时抛出(排行榜范围为 1 ~ 500 名)
|
||||||
* @throws IOException 当Http请求发生异常时抛出, 或Http请求响应码非200时抛出
|
* @throws IOException 当Http请求发生异常时抛出, 或Http请求响应码非200时抛出
|
||||||
*/
|
*/
|
||||||
public List<JsonObject> getRanking(PixivURL.RankingContentType contentType, PixivURL.RankingMode mode,
|
public List<JsonObject> getRanking(RankingContentType contentType, RankingMode mode,
|
||||||
Date time, int rankStart, int range) throws IOException {
|
Date time, int rankStart, int range) throws IOException {
|
||||||
Objects.requireNonNull(time);
|
Objects.requireNonNull(time);
|
||||||
if(!Objects.requireNonNull(contentType).isSupportedMode(Objects.requireNonNull(mode))) {
|
if(!Objects.requireNonNull(contentType).isSupportedMode(Objects.requireNonNull(mode))) {
|
||||||
throw new IllegalArgumentException("ContentType不支持指定的RankingMode: ContentType: " + contentType.name() + ", Mode: " + mode.name());
|
throw new IllegalArgumentException("ContentType不支持指定的RankingMode: ContentType: "
|
||||||
|
+ contentType.name() + ", Mode: " + mode.name());
|
||||||
} else if(rankStart <= 0) {
|
} else if(rankStart <= 0) {
|
||||||
throw new IndexOutOfBoundsException("rankStart cannot be less than or equal to zero: " + rankStart);
|
throw new IndexOutOfBoundsException("rankStart cannot be less than or equal to zero: " + rankStart);
|
||||||
} else if(range <= 0) {
|
} else if(range <= 0) {
|
||||||
throw new IndexOutOfBoundsException("range cannot be less than or equal to zero:" + range);
|
throw new IndexOutOfBoundsException("range cannot be less than or equal to zero:" + range);
|
||||||
} else if(rankStart + range - 1 > 500) {
|
} else if(rankStart + range - 1 > 500) {
|
||||||
throw new IndexOutOfBoundsException("排名选取范围超出了排行榜范围: rankStart=" + 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));
|
int startPages = (int) Math.max(1, Math.floor(rankStart / 50F));
|
||||||
@ -333,7 +322,8 @@ public class PixivDownload {
|
|||||||
JsonObject resultObject = gson.fromJson(responseBody, JsonObject.class);
|
JsonObject resultObject = gson.fromJson(responseBody, JsonObject.class);
|
||||||
canNext = resultObject.get("next").getAsJsonPrimitive().isNumber();
|
canNext = resultObject.get("next").getAsJsonPrimitive().isNumber();
|
||||||
JsonArray resultArray = resultObject.getAsJsonArray("contents");
|
JsonArray resultArray = resultObject.getAsJsonArray("contents");
|
||||||
for (int resultIndex = startIndex; resultIndex < resultArray.size() && count < range; resultIndex++, count++) {
|
for (int resultIndex = startIndex;
|
||||||
|
resultIndex < resultArray.size() && count < range; resultIndex++, count++) {
|
||||||
results.add(resultArray.get(resultIndex).getAsJsonObject());
|
results.add(resultArray.get(resultIndex).getAsJsonObject());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -393,8 +383,14 @@ public class PixivDownload {
|
|||||||
* @return 返回该illust所有Page的下载链接
|
* @return 返回该illust所有Page的下载链接
|
||||||
* @throws IOException 当HttpClient在请求时发生异常, 或接口报错时抛出, 注意{@link IOException#getMessage()}
|
* @throws IOException 当HttpClient在请求时发生异常, 或接口报错时抛出, 注意{@link IOException#getMessage()}
|
||||||
*/
|
*/
|
||||||
public static List<String> getIllustAllPageDownload(HttpClient httpClient, CookieStore cookieStore, int illustId, PageQuality quality) throws IOException {
|
public static List<String> getIllustAllPageDownload(
|
||||||
HttpGet linkApiRequest = new HttpGet(PixivURL.PIXIV_ILLUST_API_URL.replace("{illustId}", Integer.toString(illustId)));
|
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);
|
setCookieInRequest(linkApiRequest, cookieStore);
|
||||||
HttpResponse response = httpClient.execute(linkApiRequest);
|
HttpResponse response = httpClient.execute(linkApiRequest);
|
||||||
JsonObject resultObject = new Gson().fromJson(EntityUtils.toString(response.getEntity()), JsonObject.class);
|
JsonObject resultObject = new Gson().fromJson(EntityUtils.toString(response.getEntity()), JsonObject.class);
|
||||||
@ -402,7 +398,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");
|
||||||
@ -421,6 +417,7 @@ public class PixivDownload {
|
|||||||
/**
|
/**
|
||||||
* 插图质量
|
* 插图质量
|
||||||
*/
|
*/
|
||||||
|
@SuppressWarnings("unused")
|
||||||
public enum PageQuality{
|
public enum PageQuality{
|
||||||
/**
|
/**
|
||||||
* 原图画质
|
* 原图画质
|
||||||
@ -450,7 +447,8 @@ public class PixivDownload {
|
|||||||
@Deprecated
|
@Deprecated
|
||||||
public Set<Map.Entry<String, InputStream>> getCollectionAsInputStream(PageQuality quality) throws IOException {
|
public Set<Map.Entry<String, InputStream>> getCollectionAsInputStream(PageQuality quality) throws IOException {
|
||||||
HashSet<Map.Entry<String, InputStream>> illustInputStreamSet = new HashSet<>();
|
HashSet<Map.Entry<String, InputStream>> illustInputStreamSet = new HashSet<>();
|
||||||
getCollectionAsInputStream(quality, (link, inputStream) -> illustInputStreamSet.add(new AbstractMap.SimpleEntry<>(link, inputStream)));
|
getCollectionAsInputStream(quality, (link, inputStream) ->
|
||||||
|
illustInputStreamSet.add(new AbstractMap.SimpleEntry<>(link, inputStream)));
|
||||||
return illustInputStreamSet;
|
return illustInputStreamSet;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -531,7 +529,8 @@ public class PixivDownload {
|
|||||||
|
|
||||||
public static void setCookieInRequest(HttpRequest request, CookieStore cookieStore) {
|
public static void setCookieInRequest(HttpRequest request, CookieStore cookieStore) {
|
||||||
StringBuilder builder = new StringBuilder();
|
StringBuilder builder = new StringBuilder();
|
||||||
cookieStore.getCookies().forEach(cookie -> 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());
|
request.setHeader(HttpHeaderNames.COOKIE.toString(), builder.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
22
src/main/java/net/lamgc/cgj/pixiv/PixivSearchAttribute.java
Normal file
22
src/main/java/net/lamgc/cgj/pixiv/PixivSearchAttribute.java
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -8,6 +8,7 @@ import java.text.SimpleDateFormat;
|
|||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pixiv搜索URL构造器
|
* Pixiv搜索URL构造器
|
||||||
@ -15,7 +16,7 @@ import java.util.Objects;
|
|||||||
* @author LamGC
|
* @author LamGC
|
||||||
* @see PixivURL#PIXIV_SEARCH_CONTENT_URL
|
* @see PixivURL#PIXIV_SEARCH_CONTENT_URL
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings({"unused", "UnusedReturnValue"})
|
||||||
public class PixivSearchLinkBuilder {
|
public class PixivSearchLinkBuilder {
|
||||||
|
|
||||||
private final String content;
|
private final String content;
|
||||||
@ -26,8 +27,8 @@ public class PixivSearchLinkBuilder {
|
|||||||
private SearchOrder searchOrder = SearchOrder.DATE_D;
|
private SearchOrder searchOrder = SearchOrder.DATE_D;
|
||||||
private SearchContentOption searchContentOption = SearchContentOption.ALL;
|
private SearchContentOption searchContentOption = SearchContentOption.ALL;
|
||||||
|
|
||||||
private final HashSet<String> includeKeywords = new HashSet<>(0);
|
private final Set<String> includeKeywords = new HashSet<>(0);
|
||||||
private final HashSet<String> excludeKeywords = new HashSet<>(0);
|
private final Set<String> excludeKeywords = new HashSet<>(0);
|
||||||
|
|
||||||
private int page = 1;
|
private int page = 1;
|
||||||
|
|
||||||
@ -161,11 +162,19 @@ public class PixivSearchLinkBuilder {
|
|||||||
'}';
|
'}';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getContent() {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
public PixivSearchLinkBuilder setSearchArea(SearchArea searchArea) {
|
public PixivSearchLinkBuilder setSearchArea(SearchArea searchArea) {
|
||||||
this.searchArea = Objects.requireNonNull(searchArea);
|
this.searchArea = Objects.requireNonNull(searchArea);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public SearchArea getSearchArea() {
|
||||||
|
return searchArea;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取搜索条件.
|
* 获取搜索条件.
|
||||||
* @return 搜索条件内容
|
* @return 搜索条件内容
|
||||||
@ -199,32 +208,60 @@ public class PixivSearchLinkBuilder {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public SearchMode getSearchMode() {
|
||||||
|
return searchMode;
|
||||||
|
}
|
||||||
|
|
||||||
public PixivSearchLinkBuilder setSearchType(SearchType searchType) {
|
public PixivSearchLinkBuilder setSearchType(SearchType searchType) {
|
||||||
this.searchType = Objects.requireNonNull(searchType);
|
this.searchType = Objects.requireNonNull(searchType);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public SearchType getSearchType() {
|
||||||
|
return searchType;
|
||||||
|
}
|
||||||
|
|
||||||
public PixivSearchLinkBuilder setSearchOrder(SearchOrder searchOrder) {
|
public PixivSearchLinkBuilder setSearchOrder(SearchOrder searchOrder) {
|
||||||
this.searchOrder = Objects.requireNonNull(searchOrder);
|
this.searchOrder = Objects.requireNonNull(searchOrder);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public SearchOrder getSearchOrder() {
|
||||||
|
return searchOrder;
|
||||||
|
}
|
||||||
|
|
||||||
public PixivSearchLinkBuilder setSearchContentOption(SearchContentOption searchContentOption) {
|
public PixivSearchLinkBuilder setSearchContentOption(SearchContentOption searchContentOption) {
|
||||||
this.searchContentOption = Objects.requireNonNull(searchContentOption);
|
this.searchContentOption = Objects.requireNonNull(searchContentOption);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public SearchContentOption getSearchContentOption() {
|
||||||
|
return searchContentOption;
|
||||||
|
}
|
||||||
|
|
||||||
public PixivSearchLinkBuilder setRatioOption(RatioOption ratioOption) {
|
public PixivSearchLinkBuilder setRatioOption(RatioOption ratioOption) {
|
||||||
this.ratioOption = Objects.requireNonNull(ratioOption);
|
this.ratioOption = Objects.requireNonNull(ratioOption);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public RatioOption getRatioOption() {
|
||||||
|
return ratioOption;
|
||||||
|
}
|
||||||
|
|
||||||
public PixivSearchLinkBuilder setDateRange(Date startDate, Date endDate) {
|
public PixivSearchLinkBuilder setDateRange(Date startDate, Date endDate) {
|
||||||
this.startDate = startDate;
|
this.startDate = startDate;
|
||||||
this.endDate = endDate;
|
this.endDate = endDate;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Date getStartDate() {
|
||||||
|
return startDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Date getEndDate() {
|
||||||
|
return endDate;
|
||||||
|
}
|
||||||
|
|
||||||
public PixivSearchLinkBuilder setMaxSize(int width, int height) {
|
public PixivSearchLinkBuilder setMaxSize(int width, int height) {
|
||||||
this.wgt = width;
|
this.wgt = width;
|
||||||
this.hgt = height;
|
this.hgt = height;
|
||||||
@ -245,6 +282,10 @@ public class PixivSearchLinkBuilder {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public int getPage() {
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
|
||||||
public PixivSearchLinkBuilder addExcludeKeyword(String keyword) {
|
public PixivSearchLinkBuilder addExcludeKeyword(String keyword) {
|
||||||
excludeKeywords.add(keyword);
|
excludeKeywords.add(keyword);
|
||||||
return this;
|
return this;
|
||||||
@ -265,6 +306,14 @@ public class PixivSearchLinkBuilder {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Set<String> getIncludeKeywords() {
|
||||||
|
return new HashSet<>(includeKeywords);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<String> getExcludeKeywords() {
|
||||||
|
return new HashSet<>(excludeKeywords);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 搜索区域
|
* 搜索区域
|
||||||
*/
|
*/
|
||||||
@ -296,13 +345,18 @@ public class PixivSearchLinkBuilder {
|
|||||||
*/
|
*/
|
||||||
NOVELS("novel");
|
NOVELS("novel");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 可用的Json属性名
|
||||||
|
* @deprecated 该属性信息以移至 {@link PixivSearchAttribute}
|
||||||
|
* @see PixivSearchAttribute
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
public final String jsonKey;
|
public final String jsonKey;
|
||||||
|
|
||||||
SearchArea(String jsonKey) {
|
SearchArea(String jsonKey) {
|
||||||
this.jsonKey = jsonKey;
|
this.jsonKey = jsonKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -401,5 +455,4 @@ public class PixivSearchLinkBuilder {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
package net.lamgc.cgj.pixiv;
|
package net.lamgc.cgj.pixiv;
|
||||||
|
|
||||||
import java.text.SimpleDateFormat;
|
import java.text.SimpleDateFormat;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.GregorianCalendar;
|
import java.util.GregorianCalendar;
|
||||||
@ -209,7 +208,13 @@ public final class PixivURL {
|
|||||||
* @param pageIndex 页数,一页50位,总共10页
|
* @param pageIndex 页数,一页50位,总共10页
|
||||||
* @return 返回构建好的链接
|
* @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);
|
StringBuilder linkBuilder = new StringBuilder(PIXIV_RANKING_LINK);
|
||||||
linkBuilder.append("mode=").append(mode == null ? RankingMode.MODE_DAILY.modeParam : mode.modeParam);
|
linkBuilder.append("mode=").append(mode == null ? RankingMode.MODE_DAILY.modeParam : mode.modeParam);
|
||||||
if(contentType != null && !contentType.equals(RankingContentType.TYPE_ALL)){
|
if(contentType != null && !contentType.equals(RankingContentType.TYPE_ALL)){
|
||||||
@ -235,63 +240,6 @@ public final class PixivURL {
|
|||||||
return linkBuilder.toString();
|
return linkBuilder.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 排名榜模式
|
|
||||||
*/
|
|
||||||
public enum RankingMode{
|
|
||||||
/**
|
|
||||||
* 每天
|
|
||||||
*/
|
|
||||||
MODE_DAILY("daily"),
|
|
||||||
/**
|
|
||||||
* 每周
|
|
||||||
*/
|
|
||||||
MODE_WEEKLY("weekly"),
|
|
||||||
/**
|
|
||||||
* 每月
|
|
||||||
*/
|
|
||||||
MODE_MONTHLY("monthly"),
|
|
||||||
/**
|
|
||||||
* 新人
|
|
||||||
*/
|
|
||||||
MODE_ROOKIE("rookie"),
|
|
||||||
/**
|
|
||||||
* 原创
|
|
||||||
*/
|
|
||||||
MODE_ORIGINAL("original"),
|
|
||||||
/**
|
|
||||||
* 受男性喜欢
|
|
||||||
*/
|
|
||||||
MODE_MALE("male"),
|
|
||||||
/**
|
|
||||||
* 受女性喜欢
|
|
||||||
*/
|
|
||||||
MODE_FEMALE("female"),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 每天 - R18
|
|
||||||
*/
|
|
||||||
MODE_DAILY_R18("daily_r18"),
|
|
||||||
/**
|
|
||||||
* 每周 - R18
|
|
||||||
*/
|
|
||||||
MODE_WEEKLY_R18("weekly_r18"),
|
|
||||||
/**
|
|
||||||
* 受男性喜欢 - R18
|
|
||||||
*/
|
|
||||||
MODE_MALE_R18("male_r18"),
|
|
||||||
/**
|
|
||||||
* 受女性喜欢 - R18
|
|
||||||
*/
|
|
||||||
MODE_FEMALE_R18("female_r18"),
|
|
||||||
;
|
|
||||||
public String modeParam;
|
|
||||||
|
|
||||||
RankingMode(String modeParamName){
|
|
||||||
this.modeParam = modeParamName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pixiv搜索接口.<br/>
|
* Pixiv搜索接口.<br/>
|
||||||
* 要使用该链接请使用{@link PixivSearchLinkBuilder}构造链接.<br/>
|
* 要使用该链接请使用{@link PixivSearchLinkBuilder}构造链接.<br/>
|
||||||
@ -300,72 +248,4 @@ public final class PixivURL {
|
|||||||
*/
|
*/
|
||||||
final static String PIXIV_SEARCH_CONTENT_URL = "https://www.pixiv.net/ajax/search/{area}/{content}?word={content}";
|
final static String PIXIV_SEARCH_CONTENT_URL = "https://www.pixiv.net/ajax/search/{area}/{content}?word={content}";
|
||||||
|
|
||||||
/**
|
|
||||||
* 排名榜类型
|
|
||||||
*/
|
|
||||||
public enum RankingContentType{
|
|
||||||
TYPE_ALL("", RankingMode.values()),
|
|
||||||
/**
|
|
||||||
* 插画
|
|
||||||
* 支持的时间类型: 每天, 每周, 每月, 新人
|
|
||||||
*/
|
|
||||||
TYPE_ILLUST("illust",
|
|
||||||
new RankingMode[]{
|
|
||||||
RankingMode.MODE_DAILY,
|
|
||||||
RankingMode.MODE_MONTHLY,
|
|
||||||
RankingMode.MODE_WEEKLY,
|
|
||||||
RankingMode.MODE_ROOKIE,
|
|
||||||
RankingMode.MODE_DAILY_R18,
|
|
||||||
RankingMode.MODE_WEEKLY_R18,
|
|
||||||
}
|
|
||||||
),
|
|
||||||
/**
|
|
||||||
* 动图
|
|
||||||
* 支持的时间类型:每天, 每周
|
|
||||||
*/
|
|
||||||
TYPE_UGOIRA("ugoira",
|
|
||||||
new RankingMode[]{
|
|
||||||
RankingMode.MODE_DAILY,
|
|
||||||
RankingMode.MODE_WEEKLY,
|
|
||||||
RankingMode.MODE_DAILY_R18,
|
|
||||||
RankingMode.MODE_WEEKLY_R18
|
|
||||||
}
|
|
||||||
),
|
|
||||||
/**
|
|
||||||
* 漫画
|
|
||||||
* 支持的时间类型: 每天, 每周, 每月, 新人
|
|
||||||
*/
|
|
||||||
TYPE_MANGA("manga",
|
|
||||||
new RankingMode[]{
|
|
||||||
RankingMode.MODE_DAILY,
|
|
||||||
RankingMode.MODE_MONTHLY,
|
|
||||||
RankingMode.MODE_WEEKLY,
|
|
||||||
RankingMode.MODE_ROOKIE,
|
|
||||||
RankingMode.MODE_DAILY_R18,
|
|
||||||
RankingMode.MODE_WEEKLY_R18,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
;
|
|
||||||
|
|
||||||
String typeName;
|
|
||||||
|
|
||||||
private final RankingMode[] supportedMode;
|
|
||||||
|
|
||||||
RankingContentType(String typeName, RankingMode[] supportedMode){
|
|
||||||
this.typeName = typeName;
|
|
||||||
this.supportedMode = supportedMode;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 检查指定RankingMode是否支持
|
|
||||||
* @param mode 要检查的RankingMode项
|
|
||||||
* @return 如果支持返回true
|
|
||||||
*/
|
|
||||||
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
|
|
||||||
public boolean isSupportedMode(RankingMode mode) {
|
|
||||||
return Arrays.binarySearch(supportedMode, mode) >= 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -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()) {
|
||||||
|
75
src/main/java/net/lamgc/cgj/pixiv/RankingContentType.java
Normal file
75
src/main/java/net/lamgc/cgj/pixiv/RankingContentType.java
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
58
src/main/java/net/lamgc/cgj/pixiv/RankingMode.java
Normal file
58
src/main/java/net/lamgc/cgj/pixiv/RankingMode.java
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
84
src/main/java/net/lamgc/cgj/util/PixivUtils.java
Normal file
84
src/main/java/net/lamgc/cgj/util/PixivUtils.java
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
package net.lamgc.cgj.util;
|
||||||
|
|
||||||
|
import com.google.common.base.Strings;
|
||||||
|
import net.lamgc.cgj.pixiv.PixivSearchLinkBuilder;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pixiv工具类
|
||||||
|
*/
|
||||||
|
public final class PixivUtils {
|
||||||
|
|
||||||
|
private final static Logger log = LoggerFactory.getLogger(PixivUtils.class);
|
||||||
|
|
||||||
|
private PixivUtils() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 快速构造一个PixivSearchLinkBuilder
|
||||||
|
* @param content 搜索内容
|
||||||
|
* @param type 搜索类型
|
||||||
|
* @param area 搜索范围
|
||||||
|
* @param includeKeywords 包含关键词
|
||||||
|
* @param excludeKeywords 排除关键词
|
||||||
|
* @param contentOption 内容级别选项
|
||||||
|
* @param pageIndex 搜索页数
|
||||||
|
* @return 返回PixivSearchLinkBuilder对象
|
||||||
|
* @see PixivSearchLinkBuilder
|
||||||
|
*/
|
||||||
|
public static PixivSearchLinkBuilder buildSearchLinkBuilderFromString(
|
||||||
|
String content,
|
||||||
|
String type,
|
||||||
|
String area,
|
||||||
|
String includeKeywords,
|
||||||
|
String excludeKeywords,
|
||||||
|
String contentOption,
|
||||||
|
int pageIndex
|
||||||
|
) {
|
||||||
|
PixivSearchLinkBuilder searchBuilder = new PixivSearchLinkBuilder(Strings.isNullOrEmpty(content) ? "" : content);
|
||||||
|
if (type != null) {
|
||||||
|
try {
|
||||||
|
searchBuilder.setSearchType(PixivSearchLinkBuilder.SearchType.valueOf(type.trim().toUpperCase()));
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
log.warn("不支持的SearchType: {}", type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (area != null) {
|
||||||
|
try {
|
||||||
|
searchBuilder.setSearchArea(PixivSearchLinkBuilder.SearchArea.valueOf(area.trim().toUpperCase()));
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
log.warn("不支持的SearchArea: {}", area);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (contentOption != null) {
|
||||||
|
try {
|
||||||
|
searchBuilder.setSearchContentOption(
|
||||||
|
PixivSearchLinkBuilder.SearchContentOption.valueOf(contentOption.trim().toUpperCase()));
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
log.warn("不支持的SearchContentOption: {}", contentOption);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Strings.isNullOrEmpty(includeKeywords)) {
|
||||||
|
for (String keyword : includeKeywords.split(";")) {
|
||||||
|
searchBuilder.removeExcludeKeyword(keyword.trim());
|
||||||
|
searchBuilder.addIncludeKeyword(keyword.trim());
|
||||||
|
log.trace("已添加关键字: {}", keyword);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!Strings.isNullOrEmpty(excludeKeywords)) {
|
||||||
|
for (String keyword : excludeKeywords.split(";")) {
|
||||||
|
searchBuilder.removeIncludeKeyword(keyword.trim());
|
||||||
|
searchBuilder.addExcludeKeyword(keyword.trim());
|
||||||
|
log.trace("已添加排除关键字: {}", keyword);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(pageIndex > 0) {
|
||||||
|
searchBuilder.setPage(pageIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
return searchBuilder;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,2 +0,0 @@
|
|||||||
server.port=8081
|
|
||||||
server.tomcat.max-threads=1
|
|
12
src/main/resources/application.yml
Normal file
12
src/main/resources/application.yml
Normal 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
|
@ -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即可
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -133,7 +133,7 @@ public class PixivDownloadTest {
|
|||||||
zos.setLevel(9);
|
zos.setLevel(9);
|
||||||
log.info("正在调用方法...");
|
log.info("正在调用方法...");
|
||||||
try {
|
try {
|
||||||
pixivDownload.getRankingAsInputStream(null, PixivURL.RankingMode.MODE_DAILY_R18, queryDate, 500, PixivDownload.PageQuality.ORIGINAL, (rank, link, rankInfo, inputStream) -> {
|
pixivDownload.getRankingAsInputStream(null, RankingMode.MODE_DAILY_R18, queryDate, 500, PixivDownload.PageQuality.ORIGINAL, (rank, link, rankInfo, inputStream) -> {
|
||||||
try {
|
try {
|
||||||
ZipEntry entry = new ZipEntry("Rank" + rank + "-" + link.substring(link.lastIndexOf("/") + 1));
|
ZipEntry entry = new ZipEntry("Rank" + rank + "-" + link.substring(link.lastIndexOf("/") + 1));
|
||||||
entry.setComment(rankInfo.toString());
|
entry.setComment(rankInfo.toString());
|
||||||
|
Reference in New Issue
Block a user