mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-12-04 02:23:59 +00:00
Compare commits
288
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
922e762273 | ||
|
|
4c48e992da | ||
|
|
76aaa7d214 | ||
|
|
3047ba97a2 | ||
|
|
c894e38ffa | ||
|
|
72893efd83 | ||
|
|
5cec707d76 | ||
|
|
793733853b | ||
|
|
b0471904fa | ||
|
|
53e921aa80 | ||
|
|
f08dd36635 | ||
|
|
792d7210a7 | ||
|
|
fcf8f3d71f | ||
|
|
4361d96c52 | ||
|
|
971cdcd067 | ||
|
|
4b9339072a | ||
|
|
6b6394e61f | ||
|
|
ba1c429508 | ||
|
|
69ef9c5bbb | ||
|
|
e91c08548a | ||
|
|
e794b34982 | ||
|
|
0a631e75ea | ||
|
|
72194dddc9 | ||
|
|
0d5014ad40 | ||
|
|
1d7836c1bd | ||
|
|
6ed8ae2e28 | ||
|
|
b5a0155dd0 | ||
|
|
8f372e5dd0 | ||
|
|
e9bfe14488 | ||
|
|
cbd10962c0 | ||
|
|
2bb66cfc82 | ||
|
|
fbfb760b3a | ||
|
|
ef03956944 | ||
|
|
542d246aab | ||
|
|
feff1b88c1 | ||
|
|
a7d41b0107 | ||
|
|
24c22fad7f | ||
|
|
a86b26d668 | ||
|
|
5781100905 | ||
|
|
04ba9a0e2c | ||
|
|
3825527519 | ||
|
|
531f431faa | ||
|
|
44b023d919 | ||
|
|
5681d3b805 | ||
|
|
8c07c6e657 | ||
|
|
25888661ad | ||
|
|
b6922b152f | ||
|
|
572c5a61fc | ||
|
|
dec6cf496f | ||
|
|
98a043daf9 | ||
|
|
12d0f6bfbb | ||
|
|
9d2fd09331 | ||
|
|
d692416a2e | ||
|
|
e9be9b3345 | ||
|
|
6acb774c87 | ||
|
|
511515cae4 | ||
|
|
1ab9df7826 | ||
|
|
ab8b687837 | ||
|
|
7616bf3144 | ||
|
|
01d7956de5 | ||
|
|
78e53c076e | ||
|
|
4d985cc96f | ||
|
|
13ccdb8adf | ||
|
|
ac1afcd35f | ||
|
|
0c678a4124 | ||
|
|
f77800602d | ||
|
|
79ab829952 | ||
|
|
2181ef38df | ||
|
|
e09c9f76a7 | ||
|
|
7adb938357 | ||
|
|
efb800d88e | ||
|
|
422d5b845b | ||
|
|
054e9cc1ec | ||
|
|
f3da45bb16 | ||
|
|
273dbae5e7 | ||
|
|
e103003b7a | ||
|
|
e853365fe4 | ||
|
|
b5f7d9694b | ||
|
|
f75d9f687b | ||
|
|
703bfa3061 | ||
|
|
6c709fde65 | ||
|
|
449fd741ac | ||
|
|
c18b8d80e1 | ||
|
|
06ba0aff52 | ||
|
|
74e401d99c | ||
|
|
4995bca901 | ||
|
|
7299fd8762 | ||
|
|
efbadde4ed | ||
|
|
d1fa787bef | ||
|
|
c282fcb109 | ||
|
|
4995173de2 | ||
|
|
1c1068beba | ||
|
|
4a5240fcbc | ||
|
|
0f34672e33 | ||
|
|
ecd365767a | ||
|
|
f358140974 | ||
|
|
541c21f963 | ||
|
|
bdd253383d | ||
|
|
0fb53d5159 | ||
|
|
b9ff408bdd | ||
|
|
aeb4394cf8 | ||
|
|
8d419d3265 | ||
|
|
b70e30796f | ||
|
|
d3ef521773 | ||
|
|
2969c92d3d | ||
|
|
2fde421169 | ||
|
|
3494271150 | ||
|
|
675d930f86 | ||
|
|
5e20ed5050 | ||
|
|
91f4fcaa76 | ||
|
|
0754fe20f1 | ||
|
|
034fd20d3b | ||
|
|
363c603bbb | ||
|
|
24bf98bca9 | ||
|
|
275f6b9e6d | ||
|
|
5db9e422f4 | ||
|
|
705b6ba4b7 | ||
|
|
0edc057347 | ||
|
|
6ae5d998e6 | ||
|
|
cbb442ceb6 | ||
|
|
0103841fb5 | ||
|
|
b6b7f0d8b7 | ||
|
|
46c6827eda | ||
|
|
1ef6e120a8 | ||
|
|
65d518373d | ||
|
|
bca4da4b6c | ||
|
|
0fd78defcb | ||
|
|
452fd0ea2c | ||
|
|
dd8f2efb37 | ||
|
|
0feb8e798a | ||
|
|
d55d8edd2f | ||
|
|
451496f102 | ||
|
|
6d6351bd58 | ||
|
|
1a5fc8d1ef | ||
|
|
a44f30f7e5 | ||
|
|
f9ebd34de3 | ||
|
|
b47db300a6 | ||
|
|
d19d8573f9 | ||
|
|
799e120069 | ||
|
|
13f83e8795 | ||
|
|
7b5900aae4 | ||
|
|
e36c0bbe45 | ||
|
|
af723aed3a | ||
|
|
0978186679 | ||
|
|
17460ff271 | ||
|
|
f81b3852ee | ||
|
|
37abebf8f8 | ||
|
|
79fab8c0d6 | ||
|
|
9b70fb2778 | ||
|
|
bd2868748f | ||
|
|
1f47bf13b5 | ||
|
|
7d8b33afe0 | ||
|
|
367f7c78a4 | ||
|
|
1bd23ec4ae | ||
|
|
3461532679 | ||
|
|
4cfcdfa1f8 | ||
|
|
ac2f526a1c | ||
|
|
cfb624e9e0 | ||
|
|
e1bf45b5c8 | ||
|
|
e2dc611aa4 | ||
|
|
77c953626f | ||
|
|
0e14c9a925 | ||
|
|
a4e8585e2c | ||
|
|
cf7d64916e | ||
|
|
4ac80bbfe8 | ||
|
|
cfe8352d45 | ||
|
|
4a0fe61d30 | ||
|
|
c62e109aff | ||
|
|
ff400d3be3 | ||
|
|
1d243b8f1b | ||
|
|
732a7f86fe | ||
|
|
3c428f6a6d | ||
|
|
bff17f2d4e | ||
|
|
df600eaada | ||
|
|
dd4027c931 | ||
|
|
d1569195e4 | ||
|
|
d6e88f0c53 | ||
|
|
2a9fa81e56 | ||
|
|
5eed1fdfa0 | ||
|
|
cf7fc4f502 | ||
|
|
0ea31d631a | ||
|
|
74840ab63f | ||
|
|
31f33339f1 | ||
|
|
c0a0d0dc47 | ||
|
|
0cd77ee9b9 | ||
|
|
741d7aa8ca | ||
|
|
d06a80dc73 | ||
|
|
86b9c43b8b | ||
|
|
206981d4b4 | ||
|
|
7d5831b5f4 | ||
|
|
7ca63985bd | ||
|
|
06416a4e5f | ||
|
|
88739e8d1a | ||
|
|
ffaba4f496 | ||
|
|
c4f94a2bc7 | ||
|
|
49a3918244 | ||
|
|
caddff567f | ||
|
|
aed9e9f10d | ||
|
|
6557b49383 | ||
|
|
082cc4c743 | ||
|
|
e261ebe698 | ||
|
|
5a0dc69186 | ||
|
|
29d8bf3ea4 | ||
|
|
07a330cfd4 | ||
|
|
aa30571709 | ||
|
|
2bb9912cf5 | ||
|
|
8f77d9fe98 | ||
|
|
9cb32b3e8f | ||
|
|
080206925f | ||
|
|
54d2a8189c | ||
|
|
377bc12cf9 | ||
|
|
da715c8a8f | ||
|
|
fa4028296f | ||
|
|
dc629a3126 | ||
|
|
746c7ad5b3 | ||
|
|
aef1b9ab11 | ||
|
|
79c9eb3dda | ||
|
|
5a08ed68c2 | ||
|
|
e5a623c5a8 | ||
|
|
4586138bf1 | ||
|
|
1dddec110e | ||
|
|
46e9999e4c | ||
|
|
a664ae3a56 | ||
|
|
9bcdcb2cb7 | ||
|
|
0b8592559a | ||
|
|
c0b18be5ab | ||
|
|
46b2eb1ccd | ||
|
|
d323376bed | ||
|
|
838c86ae15 | ||
|
|
42925c857c | ||
|
|
ba981d281f | ||
|
|
4159b884de | ||
|
|
36b38421e5 | ||
|
|
b77c8a80e9 | ||
|
|
886dcd039f | ||
|
|
d99885d396 | ||
|
|
942de9c430 | ||
|
|
ae3ff9ecbb | ||
|
|
bcc4315ea9 | ||
|
|
2f7304ab2d | ||
|
|
0df01ba3d5 | ||
|
|
710e454fd0 | ||
|
|
c46dfa00a0 | ||
|
|
9a3ea05023 | ||
|
|
66d7a62d3a | ||
|
|
f1b6cd3e18 | ||
|
|
189d1477a8 | ||
|
|
9c3945f45a | ||
|
|
77c7d6c5d6 | ||
|
|
ab3009e9cc | ||
|
|
1c2291f9cf | ||
|
|
efb135ee48 | ||
|
|
0699c4a127 | ||
|
|
33cef5f8e1 | ||
|
|
32d467b6d9 | ||
|
|
6dfa770137 | ||
|
|
0dfee8ab22 | ||
|
|
85fe910f25 | ||
|
|
6c60b0116f | ||
|
|
8dfcf510f6 | ||
|
|
be1ed3d46d | ||
|
|
1fca578c07 | ||
|
|
a83665ac44 | ||
|
|
21e8a370c3 | ||
|
|
3dd4dd139b | ||
|
|
afe2046bc8 | ||
|
|
6d24388690 | ||
|
|
0b024a849a | ||
|
|
8745dc3567 | ||
|
|
1f4c7019d4 | ||
|
|
255e7b2fb5 | ||
|
|
7419e536cf | ||
|
|
74df000287 | ||
|
|
2e0127d609 | ||
|
|
2b9168e8df | ||
|
|
7bb3cf7c51 | ||
|
|
2ce5058be0 | ||
|
|
a5fc41f152 | ||
|
|
3245a27156 | ||
|
|
ce0fbf65aa | ||
|
|
eb87c3d865 | ||
|
|
990a90e461 | ||
|
|
45cb255a4d | ||
|
|
5e8b8a3575 | ||
|
|
c317e53c24 | ||
|
|
29b59d8450 | ||
|
|
97b7e2f86e | ||
|
|
2f55294b58 |
No files matched your search
@@ -0,0 +1,8 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
|
contact_links:
|
||||||
|
- name: 使用文档
|
||||||
|
url: https://nfd-parser.github.io/
|
||||||
|
about: 部署、接口和配置说明
|
||||||
|
- name: 已发布版本
|
||||||
|
url: https://github.com/qaiu/netdisk-fast-download/releases
|
||||||
|
about: 先看最新版本和更新说明,再反馈旧版本里已经修过的问题
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
name: 功能建议
|
||||||
|
description: 新功能或改进建议。不需要填写报错、日志或分享链接。
|
||||||
|
title: "[建议] "
|
||||||
|
labels:
|
||||||
|
- enhancement
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
这里只讨论建议。解析失败或程序跑不起来,请分别使用对应模板。
|
||||||
|
|
||||||
|
如果要举例,只用可公开的测试分享,不要附带账号、令牌或私人文件。
|
||||||
|
- type: checkboxes
|
||||||
|
id: checks
|
||||||
|
attributes:
|
||||||
|
label: 提交前
|
||||||
|
options:
|
||||||
|
- label: 我查过现有 issue,没有找到相同建议
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: problem
|
||||||
|
attributes:
|
||||||
|
label: 想解决的问题
|
||||||
|
placeholder: 现在做什么不方便
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: proposal
|
||||||
|
attributes:
|
||||||
|
label: 建议怎么做
|
||||||
|
placeholder: 希望增加或改变什么
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: alternatives
|
||||||
|
attributes:
|
||||||
|
label: 还可以怎么做
|
||||||
|
description: 没有就留空。
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
name: 解析失败
|
||||||
|
description: 某个分享链接解析失败、列目录失败,或直链无法下载
|
||||||
|
title: "[解析失败] "
|
||||||
|
labels:
|
||||||
|
- bug
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
只提交可以公开的测试分享。私人文件、含个人信息的分享不要发到这里。
|
||||||
|
|
||||||
|
不要粘贴 Cookie、Authorization、refresh_token、access token、网盘账号密码、后台密码,或未打码的配置。提取码、访问密码和账号密码不是一回事:下面只接受分享本身的提取码或访问密码。
|
||||||
|
- type: checkboxes
|
||||||
|
id: checks
|
||||||
|
attributes:
|
||||||
|
label: 提交前
|
||||||
|
options:
|
||||||
|
- label: 我查过现有 issue,没有找到相同问题
|
||||||
|
required: true
|
||||||
|
- label: 我看过当前版本和更新说明,这不是已经修好的问题
|
||||||
|
required: true
|
||||||
|
- label: 分享可以公开,且没有附带令牌、Cookie、账号密码或未脱敏配置
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
id: version
|
||||||
|
attributes:
|
||||||
|
label: 版本号
|
||||||
|
description: 页面上的版本,或发布包名里的版本,例如 0.4.15。
|
||||||
|
placeholder: "0.4.15"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: pan
|
||||||
|
attributes:
|
||||||
|
label: 网盘类型
|
||||||
|
options:
|
||||||
|
- 蓝奏云
|
||||||
|
- 蓝奏云优享
|
||||||
|
- 城通网盘
|
||||||
|
- 永硕 E 盘
|
||||||
|
- 123云盘
|
||||||
|
- 夸克网盘
|
||||||
|
- UC网盘
|
||||||
|
- 小飞机盘
|
||||||
|
- 其他(在现象里补充名称)
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: deploy
|
||||||
|
attributes:
|
||||||
|
label: 部署方式
|
||||||
|
options:
|
||||||
|
- 本机发布包
|
||||||
|
- Docker
|
||||||
|
- 自行编译
|
||||||
|
- 公共站点
|
||||||
|
- 其他
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: kind
|
||||||
|
attributes:
|
||||||
|
label: 分享内容
|
||||||
|
options:
|
||||||
|
- 单文件
|
||||||
|
- 目录
|
||||||
|
- 不确定
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: access
|
||||||
|
attributes:
|
||||||
|
label: 分享是否带密码
|
||||||
|
description: 提取码是分享链接自带的短码。不要填写网盘登录密码。
|
||||||
|
options:
|
||||||
|
- 无密码
|
||||||
|
- 只有提取码
|
||||||
|
- 有访问密码
|
||||||
|
- 不确定
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
id: passcode
|
||||||
|
attributes:
|
||||||
|
label: 提取码或访问密码
|
||||||
|
description: 没有就留空。这里不是账号密码。
|
||||||
|
placeholder: "例如 abcd"
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: input
|
||||||
|
id: share-url
|
||||||
|
attributes:
|
||||||
|
label: 可公开的完整分享链接
|
||||||
|
description: 用专门准备的测试分享。没有可公开链接时留空,并在下一项说明原因。
|
||||||
|
placeholder: "https://"
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: textarea
|
||||||
|
id: no-share-reason
|
||||||
|
attributes:
|
||||||
|
label: 不能提供测试分享的原因
|
||||||
|
description: 已经填写链接就留空。
|
||||||
|
placeholder: 例如分享含私人文件,只能描述现象
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: checkboxes
|
||||||
|
id: share-or-reason
|
||||||
|
attributes:
|
||||||
|
label: 链接
|
||||||
|
options:
|
||||||
|
- label: 我填写了可公开的完整分享链接,或已经说明不能提供的原因
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: official
|
||||||
|
attributes:
|
||||||
|
label: 官方网页是否可用
|
||||||
|
options:
|
||||||
|
- 可以打开,并且能下载
|
||||||
|
- 可以打开,但不能下载
|
||||||
|
- 打不开或提示失效
|
||||||
|
- 还没在官方网页试过
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: expected
|
||||||
|
attributes:
|
||||||
|
label: 预期结果
|
||||||
|
placeholder: 应解析出直链,或列出目录中的文件
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: actual
|
||||||
|
attributes:
|
||||||
|
label: 实际结果
|
||||||
|
description: 写页面或接口返回的原文。不要贴令牌。
|
||||||
|
placeholder: 例如提示分享不存在,或直链返回 403
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: steps
|
||||||
|
attributes:
|
||||||
|
label: 复现步骤
|
||||||
|
placeholder: |
|
||||||
|
1. 使用上述版本和部署方式
|
||||||
|
2. 解析这个分享
|
||||||
|
3. 看到上述结果
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: 脱敏后的报错日志
|
||||||
|
description: 没有日志就写「无」。删除 Cookie、Authorization、token、密码和未脱敏配置后再粘贴。
|
||||||
|
render: shell
|
||||||
|
placeholder: 无
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
name: 部署或运行问题
|
||||||
|
description: 程序无法启动、页面打不开、配置或运行报错。不是某一个分享解析失败。
|
||||||
|
title: "[运行问题] "
|
||||||
|
labels:
|
||||||
|
- bug
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
单个分享解析失败请改用「解析失败」。
|
||||||
|
|
||||||
|
不要粘贴 Cookie、Authorization、refresh_token、access token、网盘或后台密码、个人信息,以及未打码的配置。
|
||||||
|
- type: checkboxes
|
||||||
|
id: checks
|
||||||
|
attributes:
|
||||||
|
label: 提交前
|
||||||
|
options:
|
||||||
|
- label: 我查过现有 issue,没有找到相同问题
|
||||||
|
required: true
|
||||||
|
- label: 我看过当前版本和更新说明
|
||||||
|
required: true
|
||||||
|
- label: 日志和配置已经去掉令牌、密码和个人信息
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
id: version
|
||||||
|
attributes:
|
||||||
|
label: 版本号
|
||||||
|
description: 例如 0.4.15。不确定就写获取方式。
|
||||||
|
placeholder: "0.4.15"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: deploy
|
||||||
|
attributes:
|
||||||
|
label: 部署方式
|
||||||
|
options:
|
||||||
|
- 本机发布包(Linux)
|
||||||
|
- 本机发布包(Windows)
|
||||||
|
- Docker
|
||||||
|
- 自行编译
|
||||||
|
- 其他
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
id: environment
|
||||||
|
attributes:
|
||||||
|
label: 系统环境
|
||||||
|
description: 操作系统、架构,以及是否用了代理。没有就写「未记录」。
|
||||||
|
placeholder: "例如 Ubuntu 22.04 x86_64"
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
- type: textarea
|
||||||
|
id: expected
|
||||||
|
attributes:
|
||||||
|
label: 预期结果
|
||||||
|
placeholder: 服务应正常启动,页面可以打开
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: actual
|
||||||
|
attributes:
|
||||||
|
label: 实际结果
|
||||||
|
placeholder: 启动后立即退出,或页面无法访问
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: steps
|
||||||
|
attributes:
|
||||||
|
label: 复现步骤
|
||||||
|
placeholder: |
|
||||||
|
1. 下载并解压对应版本
|
||||||
|
2. 按文档启动
|
||||||
|
3. 看到上述结果
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: 脱敏后的报错日志
|
||||||
|
description: 没有日志就写「无」。不要包含令牌、密码或完整私有配置。
|
||||||
|
render: shell
|
||||||
|
placeholder: 无
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
## v0.4.15
|
||||||
|
|
||||||
|
- 浏览器与服务端以相同的 UTF-8 密钥字节处理临时认证,兼容 16、24 和 32 字节的密钥。
|
||||||
|
- 临时认证不再使用发行包里的公共密钥。未手动配置的服务实例每次启动生成随机密钥,只记录来源和指纹。保留旧发行包配置的实例也会自动迁移。
|
||||||
|
- 捐赠池默认关闭。显式启用后,受支持的网盘使用服务端选号,不再向前端提供捐赠账号。已保存的捐赠记录不会删除。
|
||||||
|
- 清理网页和文档中的公共密钥。需要网页个人认证、外部客户端或多实例共享密钥的自建站,须显式配置和安全分发 `server.authEncryptKey`。
|
||||||
|
|
||||||
|
### 升级提醒
|
||||||
|
|
||||||
|
旧公共密钥生成的 `auth` 参数不再兼容。升级后请核对部署配置,并视部署情况清理过往解析缓存和轮换捐赠凭据。
|
||||||
+244
-37
@@ -1,24 +1,17 @@
|
|||||||
# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
|
name: Java CI(Maven 构建 + Docker 镜像 + 原生环境打包)
|
||||||
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven
|
|
||||||
|
|
||||||
# This workflow uses actions that are not certified by GitHub.
|
|
||||||
# They are provided by a third-party and are governed by
|
|
||||||
# separate terms of service, privacy policy, and support
|
|
||||||
# documentation.
|
|
||||||
|
|
||||||
name: Java CI with Maven
|
|
||||||
|
|
||||||
# The API requires write permission on the repository to submit dependencies
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
packages: write
|
packages: write
|
||||||
|
|
||||||
on:
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- '*' # 只有推送tag时才会触发构建
|
- 'v*'
|
||||||
|
# '*' 不匹配含 / 的分支名(如 cursor/xxx),会让功能分支推送也发布 :latest 镜像
|
||||||
branches-ignore:
|
branches-ignore:
|
||||||
- '*' # 排除所有分支的提交
|
- '**'
|
||||||
paths-ignore:
|
paths-ignore:
|
||||||
- 'bin/**'
|
- 'bin/**'
|
||||||
- '.github/**'
|
- '.github/**'
|
||||||
@@ -32,70 +25,284 @@ on:
|
|||||||
- "main"
|
- "main"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
# ================================================================
|
||||||
|
# 阶段一:构建前端 + Maven 打包(只执行一次,产物共享)
|
||||||
|
# ================================================================
|
||||||
build:
|
build:
|
||||||
|
name: 编译构建
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
- uses: actions/setup-node@v4
|
- name: 设置 Node.js 18
|
||||||
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '18'
|
node-version: '18'
|
||||||
|
|
||||||
- name: Set up JDK 17
|
- name: 设置 JDK 17
|
||||||
uses: actions/setup-java@v3
|
uses: actions/setup-java@v3
|
||||||
with:
|
with:
|
||||||
java-version: '17'
|
java-version: '17'
|
||||||
distribution: 'temurin'
|
distribution: 'temurin'
|
||||||
cache: maven
|
cache: maven
|
||||||
|
|
||||||
- name: Build Frontend
|
- name: 构建前端
|
||||||
run: cd web-front && yarn install && yarn run build
|
run: cd web-front && yarn install && yarn run build
|
||||||
|
|
||||||
- name: Build with Maven
|
- name: Maven 编译打包
|
||||||
run: mvn -B package -DskipTests --file pom.xml
|
run: mvn -B package -DskipTests --file pom.xml
|
||||||
|
|
||||||
# Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive
|
- name: Base64 兼容性回归测试
|
||||||
- name: Update dependency graph
|
if: github.event_name == 'pull_request'
|
||||||
|
run: >-
|
||||||
|
mvn -B test -DskipTests=false
|
||||||
|
-Dtest=Base64DecoderTest,HttpProxyBase64Test,Base64CompatibilityTest
|
||||||
|
-Dsurefire.failIfNoSpecifiedTests=false
|
||||||
|
-DargLine=-XX:-UseBASE64Intrinsics
|
||||||
|
--file pom.xml
|
||||||
|
|
||||||
|
- name: Base64 SIMD 兼容性回归测试
|
||||||
|
if: github.event_name == 'pull_request'
|
||||||
|
run: >-
|
||||||
|
mvn -B test -DskipTests=false
|
||||||
|
-Dtest=Base64DecoderTest,HttpProxyBase64Test,Base64CompatibilityTest
|
||||||
|
-Dsurefire.failIfNoSpecifiedTests=false
|
||||||
|
"-DargLine=--add-modules=jdk.incubator.vector -XX:-UseBASE64Intrinsics -Dnfd.test.requireVector=true"
|
||||||
|
--file pom.xml
|
||||||
|
|
||||||
|
- name: 更新依赖图谱
|
||||||
uses: advanced-security/maven-dependency-submission-action@v3
|
uses: advanced-security/maven-dependency-submission-action@v3
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name != 'pull_request'
|
||||||
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
ignore-maven-wrapper: true
|
ignore-maven-wrapper: true
|
||||||
|
|
||||||
# - uses: release-drafter/release-drafter@v5
|
- name: 分享应用打包目录(供原生包和 Docker 复用)
|
||||||
# env:
|
if: github.event_name != 'pull_request'
|
||||||
# GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
|
|
||||||
|
|
||||||
- name: Upload Artifact
|
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
|
name: app-package
|
||||||
|
path: web-service/target/package/
|
||||||
|
|
||||||
|
- name: 分享 bin-zip(供 Docker 复用)
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: app-bin-zip
|
||||||
path: web-service/target/netdisk-fast-download-bin.zip
|
path: web-service/target/netdisk-fast-download-bin.zip
|
||||||
|
|
||||||
- name: Login to GitHub Container Registry
|
# ================================================================
|
||||||
if: github.event_name != 'pull_request'
|
# 阶段二-A:Docker 镜像构建(并行)
|
||||||
|
# ================================================================
|
||||||
|
docker:
|
||||||
|
name: Docker 镜像
|
||||||
|
needs: build
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: 下载 bin-zip 产物
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: app-bin-zip
|
||||||
|
path: web-service/target/
|
||||||
|
|
||||||
|
- name: 登录 GitHub 容器仓库
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: 设置 QEMU(多平台构建支持)
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
|
- name: 设置 Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
- name: Extract git tag
|
- name: 生成 Docker 标签
|
||||||
id: tag
|
id: docker_tag
|
||||||
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
GIT_TAG=$(git tag --points-at HEAD | head -n 1)
|
tag="$(printf '%s' "${GITHUB_REF_NAME}" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9_.-]+/-/g; s/^-+//; s/-+$//')"
|
||||||
echo "tag=$GIT_TAG" >> $GITHUB_OUTPUT
|
if [ -z "$tag" ]; then
|
||||||
|
tag="snapshot"
|
||||||
|
fi
|
||||||
|
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Build and push Docker image
|
- name: 构建并推送 Docker 镜像
|
||||||
if: github.event_name != 'pull_request'
|
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v5
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
push: true
|
push: true
|
||||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||||
tags: |
|
tags: |
|
||||||
ghcr.io/qaiu/netdisk-fast-download:${{ steps.tag.outputs.tag }}
|
ghcr.io/${{ github.repository }}:${{ steps.docker_tag.outputs.tag }}
|
||||||
ghcr.io/qaiu/netdisk-fast-download:latest
|
ghcr.io/${{ github.repository }}:latest
|
||||||
|
|
||||||
|
|
||||||
|
# ================================================================
|
||||||
|
# 阶段二-B:原生环境打包 Linux + Windows(并行)
|
||||||
|
# ================================================================
|
||||||
|
native-package:
|
||||||
|
name: 原生环境打包 → ${{ matrix.artifact-name }}
|
||||||
|
needs: build
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- os: ubuntu-latest
|
||||||
|
artifact-name: netdisk-fast-download-linux-amd64
|
||||||
|
- os: windows-latest
|
||||||
|
artifact-name: netdisk-fast-download-windows-amd64
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: 设置 JDK 17
|
||||||
|
uses: actions/setup-java@v3
|
||||||
|
with:
|
||||||
|
java-version: '17'
|
||||||
|
distribution: 'temurin'
|
||||||
|
|
||||||
|
- name: 下载 Maven 构建产物
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: app-package
|
||||||
|
path: web-service/target/package
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 选择 JDK 模块
|
||||||
|
# ============================================================
|
||||||
|
- name: 选择完整 JDK 模块集合
|
||||||
|
run: |
|
||||||
|
# 123 网盘/自定义 JS 解析器会通过 javax.script、Nashorn 和 SPI/反射加载模块,
|
||||||
|
# jdeps 无法稳定识别这些运行时依赖。这里优先保证原生包可运行,使用完整
|
||||||
|
# JDK 模块集合生成运行时,避免 Windows 精简 JRE 缺 java.scripting/jdk.dynalink 等模块。
|
||||||
|
printf 'JDK_MODULES=ALL-MODULE-PATH\n' >> $GITHUB_ENV
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# jlink 生成完整模块 JRE
|
||||||
|
# ============================================================
|
||||||
|
- name: 生成完整模块 JRE(jlink)
|
||||||
|
run: |
|
||||||
|
jlink \
|
||||||
|
--module-path "$JAVA_HOME/jmods" \
|
||||||
|
--add-modules "$JDK_MODULES" \
|
||||||
|
--output "native-package/netdisk-fast-download/jre" \
|
||||||
|
--strip-debug \
|
||||||
|
--compress=2 \
|
||||||
|
--no-header-files \
|
||||||
|
--no-man-pages
|
||||||
|
|
||||||
|
echo "JRE size:"
|
||||||
|
du -sh native-package/netdisk-fast-download/jre || true
|
||||||
|
|
||||||
|
# Windows: 确保 MSVC 运行时 DLL 到位
|
||||||
|
if [[ "$RUNNER_OS" == "Windows" ]]; then
|
||||||
|
JRE_BIN="native-package/netdisk-fast-download/jre/bin"
|
||||||
|
for dll in vcruntime140.dll msvcp140.dll vcruntime140_1.dll; do
|
||||||
|
if [ ! -f "$JRE_BIN/$dll" ] && [ -f "$JAVA_HOME/bin/$dll" ]; then
|
||||||
|
echo "jlink 未包含 $dll,从 JDK 补拷"
|
||||||
|
cp "$JAVA_HOME/bin/$dll" "$JRE_BIN/"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
echo "=== JRE bin 目录 DLL 清单 ==="
|
||||||
|
ls -la "$JRE_BIN"/*.dll 2>/dev/null || echo "(无 .dll 文件)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== 关键 JDK 模块校验 ==="
|
||||||
|
"native-package/netdisk-fast-download/jre/bin/java" --list-modules | grep -q '^java.scripting@'
|
||||||
|
"native-package/netdisk-fast-download/jre/bin/java" --list-modules | grep -q '^jdk.dynalink@'
|
||||||
|
"native-package/netdisk-fast-download/jre/bin/java" --list-modules | grep -q '^jdk.unsupported@'
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 组装包目录
|
||||||
|
# ============================================================
|
||||||
|
- name: 组装包目录
|
||||||
|
run: |
|
||||||
|
PKG="native-package/netdisk-fast-download"
|
||||||
|
SRC="web-service/target/package"
|
||||||
|
|
||||||
|
cp "$SRC/netdisk-fast-download.jar" "$PKG/"
|
||||||
|
cp -r "$SRC/lib" "$PKG/"
|
||||||
|
cp -r "$SRC/resources" "$PKG/"
|
||||||
|
cp -r "$SRC/webroot" "$PKG/"
|
||||||
|
|
||||||
|
mkdir -p "$PKG/db"
|
||||||
|
mkdir -p "$PKG/logs"
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 生成启动脚本
|
||||||
|
# ============================================================
|
||||||
|
- name: 生成启动脚本(Linux)
|
||||||
|
run: |
|
||||||
|
PKG="native-package/netdisk-fast-download"
|
||||||
|
echo '#!/bin/bash' > "$PKG/run.sh"
|
||||||
|
echo 'DIR="$(cd "$(dirname "$0")" && pwd)"' >> "$PKG/run.sh"
|
||||||
|
echo 'cd "$DIR" || exit 1' >> "$PKG/run.sh"
|
||||||
|
echo 'exec "$DIR/jre/bin/java" -Xmx512M -Dfile.encoding=utf-8 -jar "$DIR/netdisk-fast-download.jar" "$@"' >> "$PKG/run.sh"
|
||||||
|
chmod +x "$PKG/run.sh"
|
||||||
|
|
||||||
|
- name: 生成启动脚本(Windows)
|
||||||
|
run: |
|
||||||
|
PKG="native-package/netdisk-fast-download"
|
||||||
|
echo '@echo off' > "$PKG/run.bat"
|
||||||
|
echo 'chcp 65001 > nul' >> "$PKG/run.bat"
|
||||||
|
echo 'pushd %~dp0' >> "$PKG/run.bat"
|
||||||
|
echo '"%~dp0jre\bin\java.exe" -Xmx512M -Dfile.encoding=utf-8 -jar "%~dp0netdisk-fast-download.jar" %*' >> "$PKG/run.bat"
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 打包为 zip
|
||||||
|
# ============================================================
|
||||||
|
- name: 打包 ZIP(Linux)
|
||||||
|
if: runner.os == 'Linux'
|
||||||
|
run: |
|
||||||
|
cd native-package
|
||||||
|
zip -r "../${{ matrix.artifact-name }}.zip" netdisk-fast-download/
|
||||||
|
|
||||||
|
- name: 打包 ZIP(Windows)
|
||||||
|
if: runner.os == 'Windows'
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
Compress-Archive -Path native-package/netdisk-fast-download -DestinationPath "${{ matrix.artifact-name }}.zip"
|
||||||
|
|
||||||
|
# ============================================================
|
||||||
|
# 上传产物
|
||||||
|
# ============================================================
|
||||||
|
- name: 上传原生安装包
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: ${{ matrix.artifact-name }}
|
||||||
|
path: ${{ matrix.artifact-name }}.zip
|
||||||
|
|
||||||
|
# ================================================================
|
||||||
|
# 阶段三:创建 GitHub Release(只跑一次,避免矩阵任务重复拼接更新日志)
|
||||||
|
# ================================================================
|
||||||
|
publish-release:
|
||||||
|
name: 发布 GitHub Release
|
||||||
|
needs: native-package
|
||||||
|
if: github.event_name != 'pull_request' && github.ref_type == 'tag'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: 下载原生安装包
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
pattern: netdisk-fast-download-*
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: 创建 Release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
files: |
|
||||||
|
netdisk-fast-download-linux-amd64.zip
|
||||||
|
netdisk-fast-download-windows-amd64.zip
|
||||||
|
tag_name: ${{ github.ref_name }}
|
||||||
|
body_path: .github/release-notes.md
|
||||||
|
generate_release_notes: true
|
||||||
|
fail_on_unmatched_files: true
|
||||||
@@ -31,6 +31,7 @@ target/
|
|||||||
sdkTest.log
|
sdkTest.log
|
||||||
app.yml
|
app.yml
|
||||||
app-local.yml
|
app-local.yml
|
||||||
|
secret.yml
|
||||||
|
|
||||||
|
|
||||||
#some local files
|
#some local files
|
||||||
@@ -91,3 +92,4 @@ yarn-error.log*
|
|||||||
**/${project.build.directory}/
|
**/${project.build.directory}/
|
||||||
**/${project.basedir}/target/
|
**/${project.basedir}/target/
|
||||||
**/${basedir}/target/
|
**/${basedir}/target/
|
||||||
|
.spec-workflow/
|
||||||
+10
-4
@@ -1,4 +1,5 @@
|
|||||||
FROM eclipse-temurin:17-jre
|
ARG JAVA_RUNTIME_IMAGE=eclipse-temurin:17-jre
|
||||||
|
FROM ${JAVA_RUNTIME_IMAGE}
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -10,8 +11,13 @@ COPY ./web-service/target/netdisk-fast-download-bin.zip .
|
|||||||
RUN unzip netdisk-fast-download-bin.zip && \
|
RUN unzip netdisk-fast-download-bin.zip && \
|
||||||
mv netdisk-fast-download/* ./ && \
|
mv netdisk-fast-download/* ./ && \
|
||||||
rm netdisk-fast-download-bin.zip && \
|
rm netdisk-fast-download-bin.zip && \
|
||||||
chmod +x run.sh
|
chmod +x run.sh && \
|
||||||
|
mkdir -p db logs
|
||||||
|
|
||||||
EXPOSE 6400 6401
|
COPY ./docker-entrypoint.sh /docker-entrypoint.sh
|
||||||
|
RUN chmod +x /docker-entrypoint.sh
|
||||||
|
|
||||||
ENTRYPOINT ["sh", "run.sh"]
|
EXPOSE 6401
|
||||||
|
|
||||||
|
RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser
|
||||||
|
ENTRYPOINT ["/docker-entrypoint.sh"]
|
||||||
@@ -1,29 +1,32 @@
|
|||||||
# 一款网盘分享链接云解析快速下载服务
|
# 一款网盘分享链接云解析快速下载服务
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> 如果在线解析失败,可以试试 [NFD Client](https://github.com/qaiu/nfd-client-parser),在本机解析网盘分享链接。[下载安装包](https://github.com/qaiu/nfd-client-parser/releases/latest)
|
||||||
|
|
||||||
QQ交流群:1017480890
|
QQ交流群:1017480890
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/qaiu/netdisk-fast-download/actions/workflows/maven.yml"><img src="https://img.shields.io/github/actions/workflow/status/qaiu/netdisk-fast-download/maven.yml?branch=v0.1.9b8a&style=flat"></a>
|
<a href="https://github.com/qaiu/netdisk-fast-download/actions/workflows/maven.yml"><img src="https://img.shields.io/github/actions/workflow/status/qaiu/netdisk-fast-download/build.yml?branch=main&style=flat"></a>
|
||||||
<a href="https://www.oracle.com/cn/java/technologies/downloads"><img src="https://img.shields.io/badge/jdk-%3E%3D17-blue"></a>
|
<a href="https://www.oracle.com/cn/java/technologies/downloads"><img src="https://img.shields.io/badge/jdk-%3E%3D17-blue"></a>
|
||||||
<a href="https://vertx-china.github.io"><img src="https://img.shields.io/badge/vert.x-4.5.22-blue?style=flat"></a>
|
<a href="https://vertx-china.github.io"><img src="https://img.shields.io/badge/vert.x-4.5.27-blue?style=flat"></a>
|
||||||
<a href="https://raw.githubusercontent.com/qaiu/netdisk-fast-download/master/LICENSE"><img src="https://img.shields.io/github/license/qaiu/netdisk-fast-download?style=flat"></a>
|
<a href="https://raw.githubusercontent.com/qaiu/netdisk-fast-download/master/LICENSE"><img src="https://img.shields.io/github/license/qaiu/netdisk-fast-download?style=flat"></a>
|
||||||
<a href="https://github.com/qaiu/netdisk-fast-download/releases/"><img src="https://img.shields.io/github/v/release/qaiu/netdisk-fast-download?style=flat"></a>
|
<a href="https://github.com/qaiu/netdisk-fast-download/releases/"><img src="https://img.shields.io/github/v/release/qaiu/netdisk-fast-download?style=flat"></a>
|
||||||
|
<a href="https://github.com/QAIU/netdisk-fast-download">
|
||||||
|
<img src="https://img.shields.io/github/stars/QAIU/netdisk-fast-download?style=flat&logo=github" alt="GitHub Stars">
|
||||||
|
</a>
|
||||||
|
<a href="https://atomgit.com/QAIU/netdisk-fast-download"><img src="https://atomgit.com/QAIU/netdisk-fast-download/star/badge.svg" alt="AtomGit"></a>
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://trendshift.io/repositories/12101" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12101" alt="qaiu%2Fnetdisk-fast-download | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
<a href="https://trendshift.io/repositories/12101" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12101" alt="qaiu%2Fnetdisk-fast-download | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div align="center" style="display:flex; justify-content:center; gap:10px; align-items:flex-start;">
|
|
||||||
<img
|
|
||||||
src="https://github.com/user-attachments/assets/bf266d0a-aaf8-4772-9231-e38a4b7bb6cb"
|
|
||||||
alt="image1"
|
|
||||||
style="width:300px; max-width:300px; flex:none;"
|
|
||||||
>
|
|
||||||
<img
|
|
||||||
src="https://github.com/user-attachments/assets/bb7a85f0-c256-4b4a-a11b-3ceb55afc302"
|
|
||||||
alt="image2"
|
|
||||||
style="width:300px; max-width:300px; flex:none;"
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
> netdisk-fast-download网盘直链解析可以把云盘分享链接转为直链,可广泛应用于各类下载站,资源站,个人博客,图床,APP下载更新,视频点播等领域。支持市面各大主流云盘的文件分享以及文件夹分享链接,已支持蓝奏云/蓝奏云优享/奶牛快传/移动云云空间/小飞机盘/亿方云/123云盘/Cloudreve等,支持加密分享,以及部分网盘文件夹分享。
|

|
||||||
|
|
||||||
|
|
||||||
|
> 本平台所有音乐解析工具不再维护,请移步[Sonder播放器](https://sodecode.qaiu.top)
|
||||||
|
> 需要百度、迅雷的完整支持请使用[专业版](https://189.qaiu.top)。夸克网盘、UC网盘已包含在开源版。
|
||||||
|
|
||||||
|
## 介绍
|
||||||
|
> netdisk-fast-download网盘直链解析可以把云盘分享链接转为直链,可广泛应用于各类下载站,资源站,个人博客,图床,APP下载更新,视频点播等领域。支持市面各大主流云盘的文件分享以及文件夹分享链接,已支持蓝奏云/蓝奏云优享/移动云云空间/小飞机盘/亿方云/123云盘/夸克网盘/UC网盘/永硕E盘/Cloudreve等,支持加密分享,以及部分网盘文件夹分享。
|
||||||
|
|
||||||
[官方文档](https://nfd-parser.github.io/)
|
[官方文档](https://nfd-parser.github.io/)
|
||||||
[API接入](https://nfdparser.apifox.cn/)
|
[API接入](https://nfdparser.apifox.cn/)
|
||||||
@@ -31,25 +34,31 @@ QQ交流群:1017480890
|
|||||||
[公益解析,lz0站](https://lz0.qaiu.top)
|
[公益解析,lz0站](https://lz0.qaiu.top)
|
||||||
[专业版](https://189.qaiu.top)
|
[专业版](https://189.qaiu.top)
|
||||||
|
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
命令行下载分享文件:
|
|
||||||
```shell
|
|
||||||
curl -LOJ "https://lz.qaiu.top/parser?url=https://share.feijipan.com/s/Tk1F2kGQ&pwd=1234"
|
|
||||||
```
|
|
||||||
或者使用wget:
|
|
||||||
```shell
|
|
||||||
wget -O bilibili.mp4 "https://lz.qaiu.top/parser?url=https://share.feijipan.com/s/Tk1F2kGQ&pwd=1234"
|
|
||||||
```
|
|
||||||
或者使用浏览器[直接访问](https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fparser%3Furl%3Dhttps%3A%2F%2Fshare.feijipan.com%2Fs%2FTk1F2kGQ&name=bilibili.mp4&ext=mp4):
|
|
||||||
```
|
|
||||||
### 调用演示站下载:
|
|
||||||
https://lz.qaiu.top/parser?url=https://share.feijipan.com/s/Tk1F2kGQ&pwd=1234
|
|
||||||
### 调用演示站预览:
|
|
||||||
https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fparser%3Furl%3Dhttps%3A%2F%2Fshare.feijipan.com%2Fs%2FTk1F2kGQ&name=bilibili.mp4&ext=mp4
|
|
||||||
|
|
||||||
|
以带提取码的分享链接为例(提取码 `1234`),链接中含 `#`、`&`,作为 `url` 参数传入前必须做 URL 编码:
|
||||||
|
|
||||||
|
`https://www.ecpan.cn/web/#/yunpanProxy?path=%2F%23%2Fdrive%2Foutside&data=70017ece572737b12b30709b7f029308eJD0&isShare=1`
|
||||||
|
|
||||||
|
**命令行下载**
|
||||||
|
|
||||||
|
```shell
|
||||||
|
# curl
|
||||||
|
curl -LOJ "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%23%2FyunpanProxy%3Fpath%3D%252F%2523%252Fdrive%252Foutside%26data%3D70017ece572737b12b30709b7f029308eJD0%26isShare%3D1&pwd=1234"
|
||||||
|
|
||||||
|
# wget
|
||||||
|
wget -O v01 "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%23%2FyunpanProxy%3Fpath%3D%252F%2523%252Fdrive%252Foutside%26data%3D70017ece572737b12b30709b7f029308eJD0%26isShare%3D1&pwd=1234"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**短链方式**(key 取分享链接的 `data` 参数,提取码用 `@` 拼接)
|
||||||
|
|
||||||
|
| 用途 | 地址 |
|
||||||
|
| --- | --- |
|
||||||
|
| 下载 | `https://lz.qaiu.top/ec/70017ece572737b12b30709b7f029308eJD0@1234` |
|
||||||
|
| 在线预览 | [点击访问](https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fec%2F70017ece572737b12b30709b7f029308eJD0%401234&name=v01&ext=mp4) |
|
||||||
|
|
||||||
|
> 无提取码时去掉 `&pwd=1234` / `@1234` 即可;预览页 `src` 需编码(`@` → `%40`),用短链可避免二次编码。
|
||||||
|
|
||||||
**解析器模块文档:** [parser/README.md](parser/README.md)
|
**解析器模块文档:** [parser/README.md](parser/README.md)
|
||||||
|
|
||||||
**JavaScript解析器文档:** [JavaScript解析器开发指南](parser/doc/JAVASCRIPT_PARSER_GUIDE.md) | [自定义解析器扩展指南](parser/doc/CUSTOM_PARSER_GUIDE.md) | [快速开始](parser/doc/CUSTOM_PARSER_QUICKSTART.md)
|
**JavaScript解析器文档:** [JavaScript解析器开发指南](parser/doc/JAVASCRIPT_PARSER_GUIDE.md) | [自定义解析器扩展指南](parser/doc/CUSTOM_PARSER_GUIDE.md) | [快速开始](parser/doc/CUSTOM_PARSER_QUICKSTART.md)
|
||||||
@@ -59,10 +68,9 @@ https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.
|
|||||||
|
|
||||||
**注意⚠️小飞机解析有IP限制,多数云服务商的大陆IP会被拦截(可以自行配置代理),和本程序无关**
|
**注意⚠️小飞机解析有IP限制,多数云服务商的大陆IP会被拦截(可以自行配置代理),和本程序无关**
|
||||||
**注意⚠️收到很多用户反馈,小飞机近期封号频繁,请尽可能选择其他网盘分享**
|
**注意⚠️收到很多用户反馈,小飞机近期封号频繁,请尽可能选择其他网盘分享**
|
||||||
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提issues,请先检查分享是否有效。**
|
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提 issues,请先检查分享是否有效。**反馈时使用 [问题模板](https://github.com/qaiu/netdisk-fast-download/issues/new/choose),只提供可公开的测试分享,不要粘贴 Cookie、令牌或账号密码。
|
||||||
|
|
||||||
## 网盘支持情况:
|
## 网盘支持情况:
|
||||||
> 20230905 奶牛云直链做了防盗链,需加入请求头:Referer: https://cowtransfer.com/
|
|
||||||
> 20230824 123云盘解析大文件(>100MB)失效,需要登录
|
> 20230824 123云盘解析大文件(>100MB)失效,需要登录
|
||||||
> 20230722 UC网盘解析失效,需要登录
|
> 20230722 UC网盘解析失效,需要登录
|
||||||
|
|
||||||
@@ -73,13 +81,16 @@ https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.
|
|||||||
- [移动云云空间-ec](https://www.ecpan.cn/web)
|
- [移动云云空间-ec](https://www.ecpan.cn/web)
|
||||||
- [小飞机网盘-fj](https://www.feijipan.com/)
|
- [小飞机网盘-fj](https://www.feijipan.com/)
|
||||||
- [亿方云-fc](https://www.fangcloud.com/)
|
- [亿方云-fc](https://www.fangcloud.com/)
|
||||||
- [123云盘-ye](https://www.123pan.com/)
|
- [123云盘-ye](https://www.123pan.com/) ⚠️仅建议本地部署使用。公共云解析没有共享 123 账号;下载返回 5112 / 请登录后下载时,在本机配置 `auths.ye.authorization`(Windows 可直接用 run.bat)
|
||||||
- ~[115网盘(失效)-p115](https://115.com/)~
|
- ~[115网盘(失效)-p115](https://115.com/)~
|
||||||
- [文叔叔-ws](https://www.wenshushu.cn/)
|
- [文叔叔-ws](https://www.wenshushu.cn/)
|
||||||
|
- [夸克网盘-qk](https://pan.quark.cn/)
|
||||||
|
- [UC网盘-uc](https://fast.uc.cn/)
|
||||||
- [联想乐云-le](https://lecloud.lenovo.com/)
|
- [联想乐云-le](https://lecloud.lenovo.com/)
|
||||||
- [QQ邮箱云盘-qqw](https://mail.qq.com/)
|
- [QQ邮箱云盘-qqw](https://mail.qq.com/)
|
||||||
- [QQ闪传-qqsc](https://nutty.qq.com/nutty/ssr/26797.html)
|
- [QQ闪传-qqsc](https://nutty.qq.com/nutty/ssr/26797.html)
|
||||||
- [城通网盘-ct](https://www.ctfile.com)
|
- [城通网盘-ct](https://www.ctfile.com)
|
||||||
|
- [永硕E盘-ys](https://www.ysepan.com/)(空间分享,如 `https://xxx.ysepan.com/`,密码为空间访问密码;多文件请用文件列表接口)
|
||||||
- [网易云音乐分享链接-mnes](https://music.163.com)
|
- [网易云音乐分享链接-mnes](https://music.163.com)
|
||||||
- [酷狗音乐分享链接-mkgs](https://www.kugou.com)
|
- [酷狗音乐分享链接-mkgs](https://www.kugou.com)
|
||||||
- [酷我音乐分享链接-mkws](https://kuwo.cn)
|
- [酷我音乐分享链接-mkws](https://kuwo.cn)
|
||||||
@@ -95,6 +106,13 @@ https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.
|
|||||||
- Onedrive-pod
|
- Onedrive-pod
|
||||||
- Dropbox-pdp
|
- Dropbox-pdp
|
||||||
- iCloud-pic
|
- iCloud-pic
|
||||||
|
### 专业版提供
|
||||||
|
- 百度网盘开放平台-bd
|
||||||
|
- 迅雷云盘开放平台-xl
|
||||||
|
- [光鸭云盘开放平台-gy](https://www.guangyapan.com)
|
||||||
|
- [移动云盘-p139](https://yun.139.com/)
|
||||||
|
- [联通云盘-pwo](https://pan.wo.cn/)
|
||||||
|
- [天翼云盘-p189](https://cloud.189.cn/)
|
||||||
|
|
||||||
## API接口
|
## API接口
|
||||||
|
|
||||||
@@ -129,6 +147,7 @@ GET /json/parser?url={分享链接}&pwd={密码}
|
|||||||
```
|
```
|
||||||
GET /json/{网盘标识}/{分享key}@{密码}
|
GET /json/{网盘标识}/{分享key}@{密码}
|
||||||
```
|
```
|
||||||
|
注意: 移动云云空间的 `分享key` 取分享链接中的 `data` 参数值
|
||||||
|
|
||||||
#### 3. 文件夹解析(v0.1.8fixed3+)
|
#### 3. 文件夹解析(v0.1.8fixed3+)
|
||||||
|
|
||||||
@@ -144,14 +163,13 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
|
|||||||
- `your_host` 替换为您的域名或 IP
|
- `your_host` 替换为您的域名或 IP
|
||||||
|
|
||||||
### 认证参数(v0.2.1+)
|
### 认证参数(v0.2.1+)
|
||||||
[可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
|
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。可通过 `auth` 参数传递认证信息:
|
||||||
部分网盘(如夸克、UC)需要登录后的 Cookie 才能解析和下载。可通过 `auth` 参数传递认证信息:
|
|
||||||
|
|
||||||
**参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码
|
**参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码
|
||||||
|
|
||||||
**加密方式**:
|
**加密方式**:
|
||||||
- 算法:AES/ECB/PKCS5Padding
|
- 算法:AES/ECB/PKCS5Padding
|
||||||
- 密钥:`nfd_auth_key2026`(16字节)
|
- 密钥:由自建服务显式配置并通过安全渠道交给可信客户端(无公共默认值)
|
||||||
- 流程:JSON → AES加密 → Base64 → URL编码
|
- 流程:JSON → AES加密 → Base64 → URL编码
|
||||||
|
|
||||||
**JSON 结构**:
|
**JSON 结构**:
|
||||||
@@ -169,34 +187,72 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
|
|||||||
**网盘认证要求**:
|
**网盘认证要求**:
|
||||||
| 网盘 | 认证要求 | 说明 |
|
| 网盘 | 认证要求 | 说明 |
|
||||||
|------|---------|------|
|
|------|---------|------|
|
||||||
| 夸克网盘(QK) | **必须** | 必须配置 Cookie 才能解析 |
|
| 夸克网盘(QK) | 不超过 10MiB 可走原解析 | 不大于 `10 * 1024 * 1024` 字节(含等于该值)保持原来的分享解析。更大的文件仅在会员接口确认未过期 SVIP/VIP 时使用该账号直链;否则使用探测通过的 H5 文件地址并附上真实文件名。普通或过期 Cookie 不算会员 |
|
||||||
| UC网盘(UC) | **必须** | 必须配置 Cookie 才能解析 |
|
| UC网盘(UC) | **不能免登录** | 小文件仍要 Cookie。超过 10MiB 时同样只认未过期 SVIP/VIP 的账号直链;没有时才尝试 H5 文件地址。H5 没有可下载文件就返回明确错误,不会把 UC 当成免登录 |
|
||||||
| 小飞机网盘(FJ) | 可选 | 大文件(>100MB)需要认证 |
|
| 小飞机网盘(FJ) | 可选 | 大文件(>100MB)需要认证 |
|
||||||
| 蓝奏优享(IZ) | 可选 | 大文件需要认证 |
|
| 蓝奏优享(IZ) | 可选 | 大文件需要认证 |
|
||||||
|
| 123网盘(YE) | 下载通常需要 | 分享列表经常可以不登录读取。下载接口常见 5112 / 请登录后下载 / 您需要注册登录或付费后下载,请在**本机**配置 `auths.ye.authorization`(与 `token` 等价)或账号密码。公共云解析没有共享 123 账号。约 10MB 小文件有时可以直链,大文件和风控必须用你自己的账号。短链:`ye:分享key@提取码`;`#` 片段会去掉;`yun.123pan.com`、`www.123pan.com`、`*.share.123pan.cn` 同一类 |
|
||||||
|
|
||||||
**使用示例**:
|
**使用示例**:
|
||||||
```
|
```
|
||||||
GET /parser?url={分享链接}&pwd={密码}&auth={加密后的认证参数}
|
GET /parser?url={分享链接}&pwd={密码}&auth={加密后的认证参数}
|
||||||
```
|
```
|
||||||
|
|
||||||
> 💡 提示:Web 界面已内置认证配置功能,可自动处理加密过程,无需手动构造参数。
|
> 💡 提示:自建站的可信客户端可在网页中填写其显式配置的服务认证密钥;网页不会获取或保存服务端密钥。
|
||||||
> [可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
|
> 不要在不受信任的站点输入服务密钥或网盘凭据。
|
||||||
|
|
||||||
|
#### 升级与捐赠开关
|
||||||
|
|
||||||
|
- 没有手动配置密钥(包括升级后仍保留旧发布包默认配置)的实例,在每次启动时自动生成进程随机密钥。启动日志只记录来源和指纹,不输出原文。重启后,之前用进程密钥生成的认证参数会失效。
|
||||||
|
- 要让可信浏览器、外部工具或多实例使用同一密钥,显式配置 `server.authEncryptKey`,通过安全渠道分发;不要使用旧发布包默认值。
|
||||||
|
- 捐赠默认关闭。仅设置 `server.enableDonatedAccounts: true` 且启用数据库后,才允许提交和服务端选用捐赠账号。关闭不删除已有记录。旧的浏览器取号接口已移除。仅 123 云盘、小飞机和蓝奏优享可使用服务端捐赠池;需要在下载响应携带账号请求头的网盘暂不开放。
|
||||||
|
|
||||||
#### 密钥作用说明
|
#### 密钥作用说明
|
||||||
|
|
||||||
- `server.authEncryptKey`
|
- `server.authEncryptKey`
|
||||||
- 作用:用于 `auth` 参数的 AES 加解密
|
- 作用:用于 `auth` 参数的 AES 加解密
|
||||||
- 要求:16位(AES-128)
|
- 要求:16、24 或 32 个 UTF-8 字节
|
||||||
|
|
||||||
- `server.donatedAccountFailureTokenSignKey`
|
- `server.donatedAccountFailureTokenSignKey`
|
||||||
- 作用:用于“捐赠账号失败计数 token”的 HMAC 签名/验签
|
- 作用:用于“捐赠账号失败计数 token”的 HMAC 签名/验签
|
||||||
- 目的:防止客户端伪造失败计数请求
|
- 目的:防止客户端伪造失败计数请求
|
||||||
- 建议:使用高强度随机字符串,且不要与 `authEncryptKey` 相同
|
- 建议:使用高强度随机字符串,且不要与 `authEncryptKey` 相同
|
||||||
|
|
||||||
### 特殊说明
|
#### `auth` 临时认证参数 与 `auths` 静态配置认证 的区别
|
||||||
|
|
||||||
- 移动云云空间的 `分享key` 取分享链接中的 `data` 参数值
|
本项目存在两种互相独立的认证配置方式,作用范围不同,不要混淆:
|
||||||
- 移动云云空间、小飞机网盘的加密分享可忽略密码参数
|
|
||||||
|
| 方式 | 配置位置 | 生效范围 | 适用场景 |
|
||||||
|
|------|---------|---------|---------|
|
||||||
|
| `auth` 临时认证参数 | 请求 URL 上的 `auth` 查询参数 | **仅当次请求**,优先级高于 app-dev.yml 中的静态配置 | 调用方按用户临时提供的账号/Cookie/token 解析,不同请求可携带不同认证信息 |
|
||||||
|
| `auths` 静态配置认证 | `app-dev.yml` 的 `auths.<网盘标识>` 节点 | **服务端长期生效**,所有未携带 `auth` 参数的请求都会复用 | 部署方自己长期配置一份账号,供所有请求默认使用 |
|
||||||
|
|
||||||
|
以 123网盘(`ye`)为例,`app-dev.yml` 中支持以下几种写法(三选一即可):
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
auths:
|
||||||
|
ye:
|
||||||
|
username: 你的123网盘账号
|
||||||
|
password: 你的123网盘密码
|
||||||
|
```
|
||||||
|
```yaml
|
||||||
|
auths:
|
||||||
|
ye:
|
||||||
|
token: 已登录后获取的 Authorization/AccessToken
|
||||||
|
```
|
||||||
|
```yaml
|
||||||
|
auths:
|
||||||
|
ye:
|
||||||
|
authorization: 已登录后获取的 Authorization/AccessToken # 与 token 等价,二选一
|
||||||
|
```
|
||||||
|
|
||||||
|
> ⚠️ 注意:YAML 中 key 后面不写值(如 `authorization:` 空着)等同于没配置,不会生效,必须填入真实的账号密码或 token 内容。
|
||||||
|
>
|
||||||
|
> 若 123 云盘账号密码登录触发验证码或风控,解析会直接失败并提示改用 Authorization,不会尝试验证码。请改填上面的 `authorization` / `token`(浏览器 localStorage 的 `authorToken`,或请求头 `authorization` / Cookie `sso-token` 里的 JWT)。
|
||||||
|
>
|
||||||
|
> 公共解析站(例如别人搭的在线解析)不能替你登录 123。看到「请登录后下载」「5112」「您需要注册登录或付费后下载」时,把服务跑在自己的机器上并填入自己的 Authorization。这是 123 的登录和风控要求。链接写法:`/d/ye/分享key@提取码`;浏览器地址栏里 `#` 后面的片段不参与解析;`yun.123pan.com` 与 `www.123pan.com`、`数字.share.123pan.cn` 是同一种分享。
|
||||||
|
|
||||||
|
如果只是临时调用一次,不想改动服务端配置,也可以用上面提到的 `auth` 参数临时传递(`authType` 可选 `password`/`accesstoken`/`authorization`),无需重启服务,仅本次请求生效。
|
||||||
|
|
||||||
### 示例
|
### 示例
|
||||||
|
|
||||||
@@ -273,9 +329,12 @@ json返回数据格式示例:
|
|||||||
"timestamp": 1736489219402
|
"timestamp": 1736489219402
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
#### 3. 文件夹解析(仅支持蓝奏云/蓝奏优享/小飞机网盘)
|
#### 3. 文件夹解析(支持蓝奏云/蓝奏优享/小飞机/永硕E盘等)
|
||||||
/v2/getFileList?url=分享链接&pwd=分享密码
|
/v2/getFileList?url=分享链接&pwd=分享密码
|
||||||
|
|
||||||
|
永硕E盘(`ys`)空间链接先返回目录列表,再带 `dirId` 获取目录内文件:
|
||||||
|
`/v2/getFileList?url=https://xxx.ysepan.com/&pwd=空间密码&dirId=目录编号`
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"code": 200,
|
"code": 200,
|
||||||
@@ -329,13 +388,19 @@ json返回数据格式示例:
|
|||||||
| 移动云云空间(个人版) | √ | √(密码可忽略) | 5G(个人) | 不限大小 |
|
| 移动云云空间(个人版) | √ | √(密码可忽略) | 5G(个人) | 不限大小 |
|
||||||
| 小飞机网盘 | √ | √ | 10G | 不限大小 |
|
| 小飞机网盘 | √ | √ | 10G | 不限大小 |
|
||||||
| 360亿方云 | √ | √ | 100G(须实名) | 不限大小 |
|
| 360亿方云 | √ | √ | 100G(须实名) | 不限大小 |
|
||||||
| 123云盘 | √ | √ | 2T | 100G(>100M需要登录) |
|
| 123云盘 | 小文件有时可以 | √ | 2T | 大文件/风控需要本机登录 |
|
||||||
| 文叔叔 | √ | √ | 10G | 5GB |
|
| 文叔叔 | √ | √ | 10G | 5GB |
|
||||||
|
| 永硕E盘 | √ | √(空间密码) | 视套餐 | 视套餐 |
|
||||||
| WPS云文档 | √ | X | 5G(免费) | 10M(免费)/2G(会员) |
|
| WPS云文档 | √ | X | 5G(免费) | 10M(免费)/2G(会员) |
|
||||||
| 夸克网盘 | x | √ | 10G | 不限大小 |
|
| 夸克网盘 | ≤10MiB 原解析 | √ | 10G | 更大文件要有效 SVIP/VIP,或可用的 H5 文件地址 |
|
||||||
| UC网盘 | x | √ | 10G | 不限大小 |
|
| UC网盘 | x | √ | 10G | 不能免登录;大文件规则同夸克 |
|
||||||
| 飞书云盘 | √ | X | 15G | 不限大小 |
|
| 飞书云盘 | √ | X | 15G | 不限大小 |
|
||||||
|
|
||||||
|
免登录边界(阈值由网盘决定,不是本项目写死的):
|
||||||
|
|
||||||
|
- **夸克 / UC**:单文件体积阈值是 `10 * 1024 * 1024` 字节(10MiB)。小于或等于该值保持原来的解析。严格大于该值时,先请求会员接口,只把 `member_type` 为 `SUPER_VIP`、`EXP_SVIP`、`Z_VIP`、`VIP`、`EXP_VIP` 且 `exp_at` 仍在未来的账号当作有效 SVIP/VIP,并走原来的账号直链。缺少档位、普通账号、已过期或只有 Cookie 都不会当成会员。没有有效会员时,才使用 H5 预览返回的 `https://dl-c-*.drive.quark.cn` 或 `https://dl-c-*.drive.uc.cn` 文件地址,并加上真实 `filename`(含中文)。预览网页、HTML、JSON、m3u8 不会当作下载成功。UC 不能免登录。目录列表不变。百度大约 100MB 以内有直链,属于专业版,这次没有改解析器。
|
||||||
|
- **123**:分享目录经常可以不登录看。下载则经常要登录。请本机配置 Authorization,不要依赖公共云解析的共享账号。约 10MB 的小文件有时能直链。
|
||||||
|
|
||||||
# 打包部署
|
# 打包部署
|
||||||
|
|
||||||
## JDK下载(lz.qaiu.top提供直链云解析服务)
|
## JDK下载(lz.qaiu.top提供直链云解析服务)
|
||||||
@@ -414,8 +479,8 @@ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtow
|
|||||||
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
|
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
|
||||||
```shell
|
```shell
|
||||||
cd ~
|
cd ~
|
||||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.1.9b7/netdisk-fast-download-bin.zip
|
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.15/netdisk-fast-download-linux-amd64.zip
|
||||||
unzip netdisk-fast-download-bin.zip
|
unzip netdisk-fast-download.zip
|
||||||
cd netdisk-fast-download
|
cd netdisk-fast-download
|
||||||
bash service-install.sh
|
bash service-install.sh
|
||||||
```
|
```
|
||||||
@@ -471,7 +536,7 @@ nfd-proxy搭建http代理服务器
|
|||||||
参考https://github.com/nfd-parser/nfd-proxy
|
参考https://github.com/nfd-parser/nfd-proxy
|
||||||
|
|
||||||
### 认证信息配置说明
|
### 认证信息配置说明
|
||||||
部分网盘(如123)解析大文件时需要登录认证,可以在配置文件中添加认证信息。
|
夸克不超过 10MiB 可以不登录;更大的文件要本机未过期的 SVIP/VIP Cookie,或上游确实返回了可下载的 H5 文件地址。UC 不能免登录。123 的下载在公共解析站上基本都要你自己的 Authorization,云端没有共用账号。
|
||||||
|
|
||||||
修改配置文件:
|
修改配置文件:
|
||||||
app-dev.yml
|
app-dev.yml
|
||||||
@@ -479,14 +544,24 @@ app-dev.yml
|
|||||||
```yaml
|
```yaml
|
||||||
### 解析认证相关
|
### 解析认证相关
|
||||||
auths:
|
auths:
|
||||||
# 123:配置用户名密码
|
# 夸克 / UC 大于 10MiB(10 * 1024 * 1024 字节)时才会查询会员接口。
|
||||||
|
# 只有未过期的 SVIP/VIP 才使用该账号直链;不要把普通 Cookie 写成会员。
|
||||||
|
# qk:
|
||||||
|
# cookie: 浏览器里夸克网盘的 Cookie
|
||||||
|
# uc:
|
||||||
|
# cookie: 浏览器里 UC 网盘的 Cookie
|
||||||
|
# 123:优先填 authorization。账号密码若触发验证码会失败,本项目不处理验证码。
|
||||||
ye:
|
ye:
|
||||||
username: 你的用户名
|
username: 你的用户名
|
||||||
password: 你的密码
|
password: 你的密码
|
||||||
|
# authorization: 浏览器登录后的 authorToken / sso-token
|
||||||
|
# 城通免密和带密码分享都先匿名解析。仅当仍被 Turnstile 拦住时才需要登录令牌。
|
||||||
|
# 登录 https://pan.ctfile.com 后,从 Session Storage 复制 refresh_token。
|
||||||
|
# ct:
|
||||||
|
# refresh_token: 登录后的 refresh_token
|
||||||
|
# token: 可选,当前 access token
|
||||||
```
|
```
|
||||||
|
|
||||||
**注意:** 目前仅支持 123(ye)的认证配置。
|
|
||||||
|
|
||||||
|
|
||||||
**技术栈:**
|
**技术栈:**
|
||||||
Jdk17+Vert.x4
|
Jdk17+Vert.x4
|
||||||
@@ -495,22 +570,52 @@ Core模块集成Vert.x实现类似spring的注解式路由API
|
|||||||
|
|
||||||
## Star History
|
## Star History
|
||||||
|
|
||||||
[](https://star-history.com/#qaiu/netdisk-fast-download&Date)
|
<a href="https://www.star-history.com/?repos=qaiu%2Fnetdisk-fast-download&type=date&legend=bottom-right">
|
||||||
|
<picture>
|
||||||
## **免责声明**
|
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=qaiu/netdisk-fast-download&type=date&theme=dark&legend=bottom-right&sealed_token=dfQO_dJcTqcPkEnM7SfxRyHoFbV5Ah4LxoEhdlheMn4T2YLEV_WETxFZexeAbWN5OmNyYuycWan2d42PAFbw0CuU4oCTKgehfErFJ9eVl2CyVpP_4xrdQw" />
|
||||||
- 用户在使用本项目时,应自行承担风险,并确保其行为符合当地法律法规。开发者不对用户因使用本项目而导致的任何后果负责。
|
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=qaiu/netdisk-fast-download&type=date&legend=bottom-right&sealed_token=dfQO_dJcTqcPkEnM7SfxRyHoFbV5Ah4LxoEhdlheMn4T2YLEV_WETxFZexeAbWN5OmNyYuycWan2d42PAFbw0CuU4oCTKgehfErFJ9eVl2CyVpP_4xrdQw" />
|
||||||
|
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=qaiu/netdisk-fast-download&type=date&legend=bottom-right&sealed_token=dfQO_dJcTqcPkEnM7SfxRyHoFbV5Ah4LxoEhdlheMn4T2YLEV_WETxFZexeAbWN5OmNyYuycWan2d42PAFbw0CuU4oCTKgehfErFJ9eVl2CyVpP_4xrdQw" />
|
||||||
## 支持该项目
|
</picture>
|
||||||
开源不易,用爱发电,本项目长期维护如果觉得有帮助, 可以请作者喝杯咖啡, 感谢支持
|
|
||||||
|
|
||||||
本项目的服务器由林枫云提供赞助<br>
|
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
|
||||||
|
## **声明**
|
||||||
|
|
||||||
|
- 本项目**仅供个人学习与技术交流使用**,请勿用于商业用途或大规模滥用。
|
||||||
|
- 所用接口均来自各网盘**官方开放平台**、官方公开接口及**已知开源项目**,仅解析用户主动提供的分享链接,**不涉及破解或绕过版权保护**。
|
||||||
|
- 本项目**相当于自动化程序代替用户发起请求**,**不会提升或绕过任何会员权限**,也**不会突破网盘的限速策略**;我们**鼓励用户开通官方 VIP/SVIP**以获得更好的下载与加速体验。
|
||||||
|
- 使用者应遵守各网盘服务商的**用户协议与使用条款**,以及所在地区的**法律法规**,违反所产生的后果自行承担。
|
||||||
|
- **高频调用可能触发网盘风控**,导致**账号限流、封禁**或**来源 IP 被屏蔽**,请合理控制请求频率,避免高并发与批量请求。
|
||||||
|
- 网盘接口调整、风控策略变更等因素可能导致功能失效,本项目**不对可用性与稳定性作任何担保**。
|
||||||
|
- 开发者**不对**使用本项目产生的**任何直接或间接损失**(账号封禁、数据丢失、法律纠纷等)**承担责任**。
|
||||||
|
- 开发者保留**随时修改本免责声明**的权利,恕不另行通知。
|
||||||
|
- **下载、部署或使用本项目,即视为您已阅读并接受上述全部条款。**
|
||||||
|
|
||||||
|
|
||||||
|
## 赞助该项目
|
||||||
|
开源不易,用爱发电。本项目长期维护,如果觉得有帮助,欢迎赞助开发者,感谢支持。
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://blog.qaiu.top/archives/da-shang-zhuan-yong"><img alt="微信" src="https://api.iconify.design/simple-icons/wechat.svg?color=%2307C160" width="44" height="44"></a>
|
||||||
|
|
||||||
|
<a href="https://blog.qaiu.top/archives/da-shang-zhuan-yong"><img alt="支付宝" src="https://api.iconify.design/simple-icons/alipay.svg?color=%231677FF" width="44" height="44"></a>
|
||||||
|
|
||||||
|
<a href="https://paypal.me/futianshun"><img alt="PayPal" src="https://api.iconify.design/simple-icons/paypal.svg?color=%2300457C" width="44" height="44"></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
本项目的服务器由林枫云提供赞助
|
||||||
|
|
||||||
<a href="https://www.dkdun.cn/aff/WDBRYKGH" target="_blank">
|
<a href="https://www.dkdun.cn/aff/WDBRYKGH" target="_blank">
|
||||||
<img src="https://www.dkdun.cn/themes/web/www/upload/local68c2dbb2ab148.png" width="200">
|
<img src="https://www.dkdun.cn/themes/web/www/upload/local68c2dbb2ab148.png" width="200">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
|
||||||
|
|
||||||
|
|
||||||
|
### 代理资源支持
|
||||||
|
|
||||||
|
<a href="https://proxy-seller.com/?partner=5799A39425654D33">
|
||||||
|
<img src="https://raw.githubusercontent.com/wujunwei928/parse-video-py/main/resources/proxy-seller-logo.png" alt="Proxy-Seller" width="120">
|
||||||
|
</a>
|
||||||
|
|
||||||
|
感谢 [Proxy-Seller](https://proxy-seller.com/?partner=5799A39425654D33) 提供代理 IP 支持,其香港 IP 可用于本项目。
|
||||||
|
|
||||||
|
[Proxy-Seller 优惠链接](https://proxy-seller.com/?partner=5799A39425654D33) · 专属折扣码:`BJSBDD_664959`
|
||||||
+107
@@ -0,0 +1,107 @@
|
|||||||
|
[English](#security-policy) | [简体中文](#安全政策)
|
||||||
|
|
||||||
|
# Security Policy
|
||||||
|
|
||||||
|
Thank you for helping keep netdisk-fast-download (NFD) and its users safe.
|
||||||
|
|
||||||
|
## Supported Versions
|
||||||
|
|
||||||
|
Security fixes are provided for the latest stable release. Older releases are not actively maintained and generally do not receive security backports. Users are strongly encouraged to upgrade to the latest stable release.
|
||||||
|
|
||||||
|
| Version | Supported |
|
||||||
|
| --- | --- |
|
||||||
|
| Latest stable release | ✅ |
|
||||||
|
| Older releases | ❌ |
|
||||||
|
|
||||||
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
Please report suspected security vulnerabilities privately through [GitHub Private Vulnerability Reporting](https://github.com/qaiu/netdisk-fast-download/security/advisories/new). Do not disclose unpatched vulnerabilities in public Issues, Pull Requests, Discussions, or other public channels.
|
||||||
|
|
||||||
|
Please include the following information where possible:
|
||||||
|
|
||||||
|
- Affected version or commit
|
||||||
|
- Vulnerability description, affected component, and potential impact
|
||||||
|
- Reproduction steps or a minimal proof of concept
|
||||||
|
- Relevant configuration, logs, and deployment details, with sensitive information redacted
|
||||||
|
|
||||||
|
Do not include real credentials, authentication keys, API tokens, or personal data in your report. Test only systems you own or are authorized to test.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This policy applies to security vulnerabilities in the official NFD project, including authentication, authorization, credential handling, and other security-sensitive functionality.
|
||||||
|
|
||||||
|
Ordinary bugs, upstream API changes, and compatibility issues without a security impact should be reported through [GitHub Issues](https://github.com/qaiu/netdisk-fast-download/issues). Issues caused solely by third-party services, unofficial modifications, or unsafe deployment configurations are generally outside the scope of this policy. However, vulnerabilities in NFD's default configuration or its handling of third-party services remain in scope.
|
||||||
|
|
||||||
|
## Security Response and Disclosure
|
||||||
|
|
||||||
|
Security reports are handled on a best-effort basis, taking into account severity, impact, and maintainer availability. We aim to assess reports, develop appropriate fixes or mitigations, and coordinate public disclosure with reporters where possible. No fixed response or remediation timeframe is guaranteed.
|
||||||
|
|
||||||
|
## Security Best Practices
|
||||||
|
|
||||||
|
- Keep NFD and its dependencies up to date.
|
||||||
|
- Use HTTPS and restrict access to sensitive administrative interfaces.
|
||||||
|
- Protect authentication keys, API tokens, and cloud-drive credentials; never expose them in public logs, frontend bundles, or diagnostic reports.
|
||||||
|
- Enable only the services and optional features you need.
|
||||||
|
- Revoke or rotate potentially compromised credentials promptly.
|
||||||
|
|
||||||
|
## Security Advisories
|
||||||
|
|
||||||
|
For published vulnerabilities, affected versions, fixes, and mitigation guidance, see [GitHub Security Advisories](https://github.com/qaiu/netdisk-fast-download/security/advisories) and [Release Notes](https://github.com/qaiu/netdisk-fast-download/releases).
|
||||||
|
|
||||||
|
## Acknowledgments
|
||||||
|
|
||||||
|
We appreciate everyone who responsibly reports vulnerabilities and helps improve the security of NFD.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# 安全政策
|
||||||
|
|
||||||
|
感谢你帮助维护 netdisk-fast-download(NFD)及其用户的安全。
|
||||||
|
|
||||||
|
## 支持的版本
|
||||||
|
|
||||||
|
安全修复面向最新稳定版本。历史版本不再主动维护,原则上不提供安全补丁回移。强烈建议用户及时升级至最新稳定版本。
|
||||||
|
|
||||||
|
| 版本 | 是否支持 |
|
||||||
|
| --- | --- |
|
||||||
|
| 最新稳定版 | ✅ |
|
||||||
|
| 历史版本 | ❌ |
|
||||||
|
|
||||||
|
## 漏洞报告
|
||||||
|
|
||||||
|
请通过 [GitHub 私密漏洞报告](https://github.com/qaiu/netdisk-fast-download/security/advisories/new) 渠道提交疑似安全漏洞。请勿在公开 Issue、Pull Request、Discussion 或其他公开渠道披露尚未修复的漏洞。
|
||||||
|
|
||||||
|
请尽可能提供以下信息:
|
||||||
|
|
||||||
|
- 受影响的版本或提交
|
||||||
|
- 漏洞描述、受影响组件及潜在影响
|
||||||
|
- 复现步骤或最小概念验证
|
||||||
|
- 相关配置、日志及部署信息(请先脱敏)
|
||||||
|
|
||||||
|
请勿在报告中包含真实账号凭据、认证密钥、API 令牌或个人数据。请仅在自己拥有或已获得授权的环境中进行安全测试。
|
||||||
|
|
||||||
|
## 适用范围
|
||||||
|
|
||||||
|
本政策适用于 NFD 官方项目中的安全漏洞,包括身份认证、访问控制、凭据处理及其他涉及安全的功能。
|
||||||
|
|
||||||
|
不涉及安全影响的普通缺陷、上游接口变更及兼容性问题,请通过 [GitHub Issues](https://github.com/qaiu/netdisk-fast-download/issues) 反馈。仅由第三方服务、非官方修改或不安全部署配置引起的问题,原则上不属于本政策的适用范围。但 NFD 默认配置或第三方服务处理逻辑中存在的安全漏洞仍在适用范围内。
|
||||||
|
|
||||||
|
## 安全响应与披露
|
||||||
|
|
||||||
|
维护者将根据漏洞严重程度、影响范围及可用时间尽力处理安全报告,包括漏洞评估、制定修复或缓解措施,并尽可能与报告人协调公开披露。不承诺固定的响应或修复时限。
|
||||||
|
|
||||||
|
## 安全最佳实践
|
||||||
|
|
||||||
|
- 及时更新 NFD 及其依赖组件。
|
||||||
|
- 使用 HTTPS,并限制敏感管理接口的访问权限。
|
||||||
|
- 妥善保管认证密钥、API 令牌及网盘凭据,切勿通过公开日志、前端构建产物或诊断报告泄露。
|
||||||
|
- 仅启用实际需要的服务及可选功能。
|
||||||
|
- 及时撤销或轮换可能泄露的凭据。
|
||||||
|
|
||||||
|
## 安全公告
|
||||||
|
|
||||||
|
已公开的漏洞、影响版本、修复及缓解措施,请参阅 [GitHub 安全公告](https://github.com/qaiu/netdisk-fast-download/security/advisories) 和 [版本发布说明](https://github.com/qaiu/netdisk-fast-download/releases)。
|
||||||
|
|
||||||
|
## 致谢
|
||||||
|
|
||||||
|
感谢所有负责任地报告漏洞并帮助提升 NFD 安全性的研究人员与社区成员。
|
||||||
Regular → Executable
+5
-2
@@ -1,6 +1,9 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# set -x
|
# set -x
|
||||||
LAUNCH_JAR="netdisk-fast-download.jar"
|
LAUNCH_JAR="netdisk-fast-download.jar"
|
||||||
nohup java -Xmx512M -jar "$LAUNCH_JAR" "$@" >startup.log 2>&1 &
|
VECTOR_MODULE_OPT=
|
||||||
tail -f startup.log
|
if java --list-modules 2>/dev/null | grep -q '^jdk.incubator.vector@'; then
|
||||||
|
VECTOR_MODULE_OPT=--add-modules=jdk.incubator.vector
|
||||||
|
fi
|
||||||
|
exec java ${VECTOR_MODULE_OPT} -Xmx${JVM_XMX:-512M} ${JVM_OPTS} -jar "$LAUNCH_JAR" "$@"
|
||||||
|
|
||||||
@@ -65,7 +65,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.postgresql</groupId>
|
<groupId>org.postgresql</groupId>
|
||||||
<artifactId>postgresql</artifactId>
|
<artifactId>postgresql</artifactId>
|
||||||
<version>42.7.3</version>
|
<version>42.7.13</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ public class CreateDatabase {
|
|||||||
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + dbName + " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
|
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + dbName + " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
|
||||||
LOGGER.info(">>>>>>>>>>> 数据库'{}'创建成功 <<<<<<<<<<<<", dbName);
|
LOGGER.info(">>>>>>>>>>> 数据库'{}'创建成功 <<<<<<<<<<<<", dbName);
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("创建数据库失败", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,35 +24,39 @@ import java.util.*;
|
|||||||
* @author <a href="https://qaiu.top">QAIU</a>
|
* @author <a href="https://qaiu.top">QAIU</a>
|
||||||
*/
|
*/
|
||||||
public class CreateTable {
|
public class CreateTable {
|
||||||
public static Map<Class<?>, String> javaProperty2SqlColumnMap = new HashMap<>() {{
|
public static final Map<Class<?>, String> javaProperty2SqlColumnMap;
|
||||||
|
static {
|
||||||
|
Map<Class<?>, String> map = new HashMap<>();
|
||||||
// Java类型到SQL类型的映射
|
// Java类型到SQL类型的映射
|
||||||
put(Integer.class, "INT");
|
map.put(Integer.class, "INT");
|
||||||
put(Short.class, "SMALLINT");
|
map.put(Short.class, "SMALLINT");
|
||||||
put(Byte.class, "TINYINT");
|
map.put(Byte.class, "TINYINT");
|
||||||
put(Long.class, "BIGINT");
|
map.put(Long.class, "BIGINT");
|
||||||
put(java.math.BigDecimal.class, "DECIMAL");
|
map.put(java.math.BigDecimal.class, "DECIMAL");
|
||||||
put(Double.class, "DOUBLE");
|
map.put(Double.class, "DOUBLE");
|
||||||
put(Float.class, "REAL");
|
map.put(Float.class, "REAL");
|
||||||
put(Boolean.class, "BOOLEAN");
|
map.put(Boolean.class, "BOOLEAN");
|
||||||
put(String.class, "VARCHAR");
|
map.put(String.class, "VARCHAR");
|
||||||
put(Date.class, "TIMESTAMP");
|
map.put(Date.class, "TIMESTAMP");
|
||||||
put(java.time.LocalDateTime.class, "TIMESTAMP");
|
map.put(java.time.LocalDateTime.class, "TIMESTAMP");
|
||||||
put(java.sql.Timestamp.class, "TIMESTAMP");
|
map.put(java.sql.Timestamp.class, "TIMESTAMP");
|
||||||
put(java.sql.Date.class, "DATE");
|
map.put(java.sql.Date.class, "DATE");
|
||||||
put(java.sql.Time.class, "TIME");
|
map.put(java.sql.Time.class, "TIME");
|
||||||
|
|
||||||
// 基本数据类型
|
// 基本数据类型
|
||||||
put(int.class, "INT");
|
map.put(int.class, "INT");
|
||||||
put(short.class, "SMALLINT");
|
map.put(short.class, "SMALLINT");
|
||||||
put(byte.class, "TINYINT");
|
map.put(byte.class, "TINYINT");
|
||||||
put(long.class, "BIGINT");
|
map.put(long.class, "BIGINT");
|
||||||
put(double.class, "DOUBLE");
|
map.put(double.class, "DOUBLE");
|
||||||
put(float.class, "REAL");
|
map.put(float.class, "REAL");
|
||||||
put(boolean.class, "BOOLEAN");
|
map.put(boolean.class, "BOOLEAN");
|
||||||
}};
|
|
||||||
|
javaProperty2SqlColumnMap = Collections.unmodifiableMap(map);
|
||||||
|
}
|
||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(CreateTable.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(CreateTable.class);
|
||||||
public static String UNIQUE_PREFIX = "idx_";
|
public static final String UNIQUE_PREFIX = "idx_";
|
||||||
|
|
||||||
private static Case getCase(Class<?> clz) {
|
private static Case getCase(Class<?> clz) {
|
||||||
return switch (clz.getName()) {
|
return switch (clz.getName()) {
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import org.slf4j.LoggerFactory;
|
|||||||
*
|
*
|
||||||
* @author <a href="https://qaiu.top">QAIU</a>
|
* @author <a href="https://qaiu.top">QAIU</a>
|
||||||
*/
|
*/
|
||||||
public class JDBCPoolInit {
|
public class JDBCPoolInit implements AutoCloseable {
|
||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(JDBCPoolInit.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(JDBCPoolInit.class);
|
||||||
|
|
||||||
@@ -101,4 +101,16 @@ public class JDBCPoolInit {
|
|||||||
synchronized public JDBCPool getPool() {
|
synchronized public JDBCPool getPool() {
|
||||||
return pool;
|
return pool;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭连接池,释放数据库资源
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public synchronized void close() {
|
||||||
|
if (pool != null) {
|
||||||
|
pool.close();
|
||||||
|
LOGGER.info("数据库连接池已关闭: URL={}", url);
|
||||||
|
pool = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -16,9 +16,13 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.lang.management.ManagementFactory;
|
import java.lang.management.ManagementFactory;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
import java.util.Calendar;
|
import java.util.Calendar;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
import java.util.concurrent.locks.LockSupport;
|
import java.util.concurrent.locks.LockSupport;
|
||||||
|
|
||||||
import static cn.qaiu.vx.core.util.ConfigConstant.*;
|
import static cn.qaiu.vx.core.util.ConfigConstant.*;
|
||||||
@@ -43,11 +47,25 @@ public final class Deploy {
|
|||||||
private Handler<JsonObject> handle;
|
private Handler<JsonObject> handle;
|
||||||
|
|
||||||
private Thread mainThread;
|
private Thread mainThread;
|
||||||
|
private final List<Runnable> preShutdownTasks = new CopyOnWriteArrayList<>();
|
||||||
|
private final List<Runnable> postShutdownTasks = new CopyOnWriteArrayList<>();
|
||||||
|
|
||||||
public static Deploy instance() {
|
public static Deploy instance() {
|
||||||
return INSTANCE;
|
return INSTANCE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void addPreShutdownTask(Runnable task) {
|
||||||
|
if (task != null) {
|
||||||
|
preShutdownTasks.add(task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addPostShutdownTask(Runnable task) {
|
||||||
|
if (task != null) {
|
||||||
|
postShutdownTasks.add(task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param args 启动参数
|
* @param args 启动参数
|
||||||
@@ -62,10 +80,19 @@ public final class Deploy {
|
|||||||
path.append("-").append(args[0].replace("app-",""));
|
path.append("-").append(args[0].replace("app-",""));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 读取yml配置
|
// 读取yml配置,优先当前目录,其次 resources/ 子目录
|
||||||
|
String configFile = path + ".yml";
|
||||||
|
if (!Files.exists(Path.of(configFile)) && Files.exists(Path.of("resources", configFile))) {
|
||||||
|
path.insert(0, "resources/");
|
||||||
|
LOGGER.info("从 resources/ 目录加载配置: {}", path + ".yml");
|
||||||
|
}
|
||||||
ConfigUtil.readYamlConfig(path.toString(), tempVertx)
|
ConfigUtil.readYamlConfig(path.toString(), tempVertx)
|
||||||
.onSuccess(this::readConf)
|
.onSuccess(this::readConf)
|
||||||
.onFailure(Throwable::printStackTrace);
|
.onFailure(err -> {
|
||||||
|
LOGGER.error("读取配置文件失败: {}", err.getMessage(), err);
|
||||||
|
LockSupport.unpark(mainThread);
|
||||||
|
System.exit(-1);
|
||||||
|
});
|
||||||
LockSupport.park();
|
LockSupport.park();
|
||||||
deployVerticle();
|
deployVerticle();
|
||||||
}
|
}
|
||||||
@@ -122,9 +149,16 @@ public final class Deploy {
|
|||||||
customConfig = globalConfig.getJsonObject(CUSTOM);
|
customConfig = globalConfig.getJsonObject(CUSTOM);
|
||||||
|
|
||||||
JsonObject vertxConfig = globalConfig.getJsonObject(VERTX);
|
JsonObject vertxConfig = globalConfig.getJsonObject(VERTX);
|
||||||
Integer vertxConfigELPS = vertxConfig.getInteger(EVENT_LOOP_POOL_SIZE);
|
JsonObject vertxOptionsConfig = vertxConfig.copy();
|
||||||
var vertxOptions = vertxConfigELPS == 0 ?
|
if (vertxOptionsConfig.getInteger(EVENT_LOOP_POOL_SIZE, 0) == 0) {
|
||||||
new VertxOptions() : new VertxOptions(vertxConfig);
|
vertxOptionsConfig.remove(EVENT_LOOP_POOL_SIZE);
|
||||||
|
}
|
||||||
|
if (vertxOptionsConfig.getInteger("workerPoolSize", 0) == 0) {
|
||||||
|
vertxOptionsConfig.remove("workerPoolSize");
|
||||||
|
}
|
||||||
|
Integer vertxConfigELPS = vertxConfig.getInteger(EVENT_LOOP_POOL_SIZE, 0);
|
||||||
|
var vertxOptions = vertxOptionsConfig.isEmpty() ?
|
||||||
|
new VertxOptions() : new VertxOptions(vertxOptionsConfig);
|
||||||
|
|
||||||
// vertxOptions.setAddressResolverOptions(
|
// vertxOptions.setAddressResolverOptions(
|
||||||
// new AddressResolverOptions().
|
// new AddressResolverOptions().
|
||||||
@@ -137,30 +171,46 @@ public final class Deploy {
|
|||||||
vertxOptions.getWorkerPoolSize());
|
vertxOptions.getWorkerPoolSize());
|
||||||
var vertx = Vertx.vertx(vertxOptions);
|
var vertx = Vertx.vertx(vertxOptions);
|
||||||
VertxHolder.init(vertx);
|
VertxHolder.init(vertx);
|
||||||
|
|
||||||
|
// 注册 ShutdownHook,确保进程退出时优雅关闭资源
|
||||||
|
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||||
|
LOGGER.info("JVM shutting down...");
|
||||||
|
runShutdownTasks("before Vert.x close", preShutdownTasks);
|
||||||
|
try {
|
||||||
|
LOGGER.info("Closing Vert.x...");
|
||||||
|
vertx.close().toCompletionStage().toCompletableFuture().get(10, java.util.concurrent.TimeUnit.SECONDS);
|
||||||
|
LOGGER.info("Vert.x closed successfully");
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.warn("Vert.x close error or timeout", e);
|
||||||
|
} finally {
|
||||||
|
runShutdownTasks("after Vert.x close", postShutdownTasks);
|
||||||
|
}
|
||||||
|
}));
|
||||||
//配置保存在共享数据中
|
//配置保存在共享数据中
|
||||||
var sharedData = vertx.sharedData();
|
var sharedData = vertx.sharedData();
|
||||||
LocalMap<String, Object> localMap = sharedData.getLocalMap(LOCAL);
|
LocalMap<String, Object> localMap = sharedData.getLocalMap(LOCAL);
|
||||||
localMap.put(GLOBAL_CONFIG, globalConfig);
|
localMap.put(GLOBAL_CONFIG, globalConfig);
|
||||||
localMap.put(CUSTOM_CONFIG, customConfig);
|
localMap.put(CUSTOM_CONFIG, customConfig);
|
||||||
localMap.put(SERVER, globalConfig.getJsonObject(SERVER));
|
localMap.put(SERVER, globalConfig.getJsonObject(SERVER));
|
||||||
var future0 = vertx.createSharedWorkerExecutor("other-handle")
|
WorkerExecutor otherHandleExecutor = vertx.createSharedWorkerExecutor("other-handle");
|
||||||
.executeBlocking(() -> {
|
var future0 = otherHandleExecutor.executeBlocking(() -> {
|
||||||
handle.handle(globalConfig);
|
handle.handle(globalConfig);
|
||||||
return "Other handle complete";
|
return "Other handle complete";
|
||||||
});
|
});
|
||||||
|
|
||||||
future0.onSuccess(res -> {
|
future0.onSuccess(res -> {
|
||||||
|
otherHandleExecutor.close();
|
||||||
LOGGER.info(res);
|
LOGGER.info(res);
|
||||||
// 部署 路由、异步service、反向代理 服务
|
// 部署 路由、异步service、反向代理 服务
|
||||||
var future1 = vertx.deployVerticle(RouterVerticle.class, getWorkDeploymentOptions("Router"));
|
var future1 = vertx.deployVerticle(RouterVerticle.class, getWorkDeploymentOptions("Router"));
|
||||||
var future2 = vertx.deployVerticle(ServiceVerticle.class, getWorkDeploymentOptions("Service"));
|
var future2 = vertx.deployVerticle(ServiceVerticle.class, getWorkDeploymentOptions("Service"));
|
||||||
var future3 = vertx.deployVerticle(ReverseProxyVerticle.class, getWorkDeploymentOptions("proxy"));
|
var future3 = vertx.deployVerticle(ReverseProxyVerticle.class, getWorkDeploymentOptions("proxy", 1));
|
||||||
|
|
||||||
|
|
||||||
JsonObject jsonObject = ((JsonObject) localMap.get(GLOBAL_CONFIG)).getJsonObject("proxy-server");
|
JsonObject jsonObject = ((JsonObject) localMap.get(GLOBAL_CONFIG)).getJsonObject("proxy-server");
|
||||||
if (jsonObject != null) {
|
if (jsonObject != null) {
|
||||||
genPwd(jsonObject);
|
genPwd(jsonObject);
|
||||||
var future4 = vertx.deployVerticle(HttpProxyVerticle.class, getWorkDeploymentOptions("proxy"));
|
var future4 = vertx.deployVerticle(HttpProxyVerticle.class, getWorkDeploymentOptions("proxy", 1));
|
||||||
future4.onSuccess(LOGGER::info);
|
future4.onSuccess(LOGGER::info);
|
||||||
future4.onFailure(e -> LOGGER.error("Other handle error", e));
|
future4.onFailure(e -> LOGGER.error("Other handle error", e));
|
||||||
Future.all(future1, future2, future3, future4)
|
Future.all(future1, future2, future3, future4)
|
||||||
@@ -172,7 +222,10 @@ public final class Deploy {
|
|||||||
.onFailure(this::deployVerticalFailed);
|
.onFailure(this::deployVerticalFailed);
|
||||||
}
|
}
|
||||||
|
|
||||||
}).onFailure(e -> LOGGER.error("Other handle error", e));
|
}).onFailure(e -> {
|
||||||
|
otherHandleExecutor.close();
|
||||||
|
LOGGER.error("Other handle error", e);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void genPwd(JsonObject jsonObject) {
|
private static void genPwd(JsonObject jsonObject) {
|
||||||
@@ -189,6 +242,21 @@ public final class Deploy {
|
|||||||
jsonObject.getString("password"));
|
jsonObject.getString("password"));
|
||||||
LOGGER.info("==============server info================");
|
LOGGER.info("==============server info================");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void runShutdownTasks(String stage, List<Runnable> tasks) {
|
||||||
|
if (tasks.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
LOGGER.info("Running {} shutdown tasks: {}", stage, tasks.size());
|
||||||
|
for (Runnable task : tasks) {
|
||||||
|
try {
|
||||||
|
task.run();
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.warn("Shutdown task failed at stage {}", stage, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 部署失败
|
* 部署失败
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -1,14 +1,20 @@
|
|||||||
package cn.qaiu.vx.core.base;
|
package cn.qaiu.vx.core.base;
|
||||||
|
|
||||||
|
import cn.qaiu.vx.core.annotaions.HandleSortFilter;
|
||||||
import cn.qaiu.vx.core.interceptor.AfterInterceptor;
|
import cn.qaiu.vx.core.interceptor.AfterInterceptor;
|
||||||
import cn.qaiu.vx.core.model.JsonResult;
|
import cn.qaiu.vx.core.model.JsonResult;
|
||||||
import cn.qaiu.vx.core.util.CommonUtil;
|
|
||||||
import cn.qaiu.vx.core.util.ReflectionUtil;
|
import cn.qaiu.vx.core.util.ReflectionUtil;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import io.vertx.ext.web.RoutingContext;
|
import io.vertx.ext.web.RoutingContext;
|
||||||
import org.reflections.Reflections;
|
import org.reflections.Reflections;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import static cn.qaiu.vx.core.util.ResponseUtil.*;
|
import static cn.qaiu.vx.core.util.ResponseUtil.*;
|
||||||
|
|
||||||
@@ -22,9 +28,10 @@ public interface BaseHttpApi {
|
|||||||
|
|
||||||
// 需要扫描注册的Router路径
|
// 需要扫描注册的Router路径
|
||||||
Reflections reflections = ReflectionUtil.getReflections();
|
Reflections reflections = ReflectionUtil.getReflections();
|
||||||
|
Logger LOGGER = LoggerFactory.getLogger(BaseHttpApi.class);
|
||||||
|
|
||||||
default void doFireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject) {
|
default void doFireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject) {
|
||||||
if (!ctx.response().ended()) {
|
if (!isResponseDone(ctx)) {
|
||||||
fireJsonObjectResponse(ctx, jsonObject);
|
fireJsonObjectResponse(ctx, jsonObject);
|
||||||
}
|
}
|
||||||
handleAfterInterceptor(ctx, jsonObject);
|
handleAfterInterceptor(ctx, jsonObject);
|
||||||
@@ -32,14 +39,14 @@ public interface BaseHttpApi {
|
|||||||
|
|
||||||
|
|
||||||
default <T> void doFireJsonResultResponse(RoutingContext ctx, JsonResult<T> jsonResult) {
|
default <T> void doFireJsonResultResponse(RoutingContext ctx, JsonResult<T> jsonResult) {
|
||||||
if (!ctx.response().ended()) {
|
if (!isResponseDone(ctx)) {
|
||||||
fireJsonResultResponse(ctx, jsonResult);
|
fireJsonResultResponse(ctx, jsonResult);
|
||||||
}
|
}
|
||||||
handleAfterInterceptor(ctx, jsonResult.toJsonObject());
|
handleAfterInterceptor(ctx, jsonResult.toJsonObject());
|
||||||
}
|
}
|
||||||
|
|
||||||
default void doFireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject, int statusCode) {
|
default void doFireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject, int statusCode) {
|
||||||
if (!ctx.response().ended()) {
|
if (!isResponseDone(ctx)) {
|
||||||
fireJsonObjectResponse(ctx, jsonObject, statusCode);
|
fireJsonObjectResponse(ctx, jsonObject, statusCode);
|
||||||
}
|
}
|
||||||
handleAfterInterceptor(ctx, jsonObject);
|
handleAfterInterceptor(ctx, jsonObject);
|
||||||
@@ -47,30 +54,78 @@ public interface BaseHttpApi {
|
|||||||
|
|
||||||
|
|
||||||
default <T> void doFireJsonResultResponse(RoutingContext ctx, JsonResult<T> jsonResult, int statusCode) {
|
default <T> void doFireJsonResultResponse(RoutingContext ctx, JsonResult<T> jsonResult, int statusCode) {
|
||||||
if (!ctx.response().ended()) {
|
if (!isResponseDone(ctx)) {
|
||||||
fireJsonResultResponse(ctx, jsonResult, statusCode);
|
fireJsonResultResponse(ctx, jsonResult, statusCode);
|
||||||
}
|
}
|
||||||
handleAfterInterceptor(ctx, jsonResult.toJsonObject());
|
handleAfterInterceptor(ctx, jsonResult.toJsonObject());
|
||||||
}
|
}
|
||||||
|
|
||||||
default Set<AfterInterceptor> getAfterInterceptor() {
|
default Set<AfterInterceptor> getAfterInterceptor() {
|
||||||
|
return AfterInterceptorHolder.INSTANCES;
|
||||||
|
}
|
||||||
|
|
||||||
Set<Class<? extends AfterInterceptor>> afterInterceptorClassSet =
|
class AfterInterceptorHolder {
|
||||||
reflections.getSubTypesOf(AfterInterceptor.class);
|
private static final Set<AfterInterceptor> INSTANCES = loadAfterInterceptors();
|
||||||
if (afterInterceptorClassSet == null) {
|
|
||||||
return null;
|
private static Set<AfterInterceptor> loadAfterInterceptors() {
|
||||||
|
Set<Class<? extends AfterInterceptor>> afterInterceptorClassSet =
|
||||||
|
reflections.getSubTypesOf(AfterInterceptor.class);
|
||||||
|
if (afterInterceptorClassSet == null || afterInterceptorClassSet.isEmpty()) {
|
||||||
|
return Collections.emptySet();
|
||||||
|
}
|
||||||
|
return afterInterceptorClassSet.stream()
|
||||||
|
.filter(AfterInterceptorHolder::isEnabled)
|
||||||
|
.sorted(AfterInterceptorHolder::compareOrder)
|
||||||
|
.map(AfterInterceptorHolder::newInterceptor)
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.collect(Collectors.collectingAndThen(
|
||||||
|
Collectors.toCollection(LinkedHashSet::new),
|
||||||
|
Collections::unmodifiableSet));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isEnabled(Class<? extends AfterInterceptor> clazz) {
|
||||||
|
HandleSortFilter sort = clazz.getAnnotation(HandleSortFilter.class);
|
||||||
|
return sort == null || sort.value() >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int compareOrder(Class<? extends AfterInterceptor> left, Class<? extends AfterInterceptor> right) {
|
||||||
|
return Integer.compare(order(left), order(right));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int order(Class<? extends AfterInterceptor> clazz) {
|
||||||
|
HandleSortFilter sort = clazz.getAnnotation(HandleSortFilter.class);
|
||||||
|
return sort == null ? 0 : sort.value();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AfterInterceptor newInterceptor(Class<? extends AfterInterceptor> clazz) {
|
||||||
|
try {
|
||||||
|
return ReflectionUtil.newWithNoParam(clazz);
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.warn("AfterInterceptor 初始化失败,已跳过: {}", clazz.getName(), e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return CommonUtil.sortClassSet(afterInterceptorClassSet);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
default void handleAfterInterceptor(RoutingContext ctx, JsonObject jsonObject) {
|
default void handleAfterInterceptor(RoutingContext ctx, JsonObject jsonObject) {
|
||||||
Set<AfterInterceptor> afterInterceptor = getAfterInterceptor();
|
if (ctx.response().closed()) {
|
||||||
if (afterInterceptor != null) {
|
return;
|
||||||
afterInterceptor.forEach(ai -> ai.handle(ctx, jsonObject));
|
|
||||||
}
|
}
|
||||||
if (!ctx.response().ended()) {
|
Set<AfterInterceptor> afterInterceptor = getAfterInterceptor();
|
||||||
|
afterInterceptor.forEach(ai -> {
|
||||||
|
try {
|
||||||
|
ai.handle(ctx, jsonObject);
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.warn("AfterInterceptor 执行失败: {}", ai.getClass().getName(), e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (!isResponseDone(ctx)) {
|
||||||
fireTextResponse(ctx, "handleAfterInterceptor: response not end");
|
fireTextResponse(ctx, "handleAfterInterceptor: response not end");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
default boolean isResponseDone(RoutingContext ctx) {
|
||||||
|
return ctx.response().ended() || ctx.response().closed();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -34,6 +34,7 @@ import java.lang.reflect.InvocationTargetException;
|
|||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
@@ -96,7 +97,9 @@ public class RouterHandlerFactory implements BaseHttpApi {
|
|||||||
mainRouter.route().handler(CorsHandler.create().addRelativeOrigin(".*").allowCredentials(true).allowedMethods(httpMethods));
|
mainRouter.route().handler(CorsHandler.create().addRelativeOrigin(".*").allowCredentials(true).allowedMethods(httpMethods));
|
||||||
|
|
||||||
// 配置文件上传路径
|
// 配置文件上传路径
|
||||||
mainRouter.route().handler(BodyHandler.create().setUploadsDirectory("uploads"));
|
mainRouter.route().handler(BodyHandler.create()
|
||||||
|
.setUploadsDirectory("uploads")
|
||||||
|
.setBodyLimit(2L * 1024 * 1024));
|
||||||
|
|
||||||
// 拦截器
|
// 拦截器
|
||||||
Set<Handler<RoutingContext>> interceptorSet = getInterceptorSet();
|
Set<Handler<RoutingContext>> interceptorSet = getInterceptorSet();
|
||||||
@@ -127,8 +130,9 @@ public class RouterHandlerFactory implements BaseHttpApi {
|
|||||||
// 错误请求处理
|
// 错误请求处理
|
||||||
mainRouter.errorHandler(405, ctx -> doFireJsonResultResponse(ctx, JsonResult
|
mainRouter.errorHandler(405, ctx -> doFireJsonResultResponse(ctx, JsonResult
|
||||||
.error("Method Not Allowed", 405)));
|
.error("Method Not Allowed", 405)));
|
||||||
mainRouter.errorHandler(404, ctx -> ctx.response().setStatusCode(404).setChunked(true)
|
mainRouter.errorHandler(404, ctx -> {
|
||||||
.end("Internal server error: 404 not found"));
|
ctx.response().setStatusCode(404).end("404 not found");
|
||||||
|
});
|
||||||
|
|
||||||
return mainRouter;
|
return mainRouter;
|
||||||
}
|
}
|
||||||
@@ -174,13 +178,14 @@ public class RouterHandlerFactory implements BaseHttpApi {
|
|||||||
route.handler(TimeoutHandler.create(SharedDataUtil.getCustomConfig().getInteger(ROUTE_TIME_OUT)));
|
route.handler(TimeoutHandler.create(SharedDataUtil.getCustomConfig().getInteger(ROUTE_TIME_OUT)));
|
||||||
route.handler(ResponseTimeHandler.create());
|
route.handler(ResponseTimeHandler.create());
|
||||||
route.handler(ctx -> handlerMethod(instance, method, ctx)).failureHandler(ctx -> {
|
route.handler(ctx -> handlerMethod(instance, method, ctx)).failureHandler(ctx -> {
|
||||||
if (ctx.response().ended()) return;
|
if (isResponseDone(ctx)) return;
|
||||||
// 超时处理器状态码503
|
// 超时处理器状态码503
|
||||||
if (ctx.statusCode() == 503 || ctx.failure() == null) {
|
if (ctx.statusCode() == 503 || ctx.failure() == null) {
|
||||||
doFireJsonResultResponse(ctx, JsonResult.error("未知异常, 请联系管理员"), 503);
|
doFireJsonResultResponse(ctx, JsonResult.error("未知异常, 请联系管理员"), 503);
|
||||||
} else {
|
} else {
|
||||||
ctx.failure().printStackTrace();
|
LOGGER.error("路由处理失败", ctx.failure());
|
||||||
doFireJsonResultResponse(ctx, JsonResult.error(ctx.failure().getMessage()), 500);
|
String msg = ctx.failure() != null ? ctx.failure().getMessage() : "未知异常";
|
||||||
|
doFireJsonResultResponse(ctx, JsonResult.error(msg), 500);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else if (method.isAnnotationPresent(SockRouteMapper.class)) {
|
} else if (method.isAnnotationPresent(SockRouteMapper.class)) {
|
||||||
@@ -198,7 +203,7 @@ public class RouterHandlerFactory implements BaseHttpApi {
|
|||||||
try {
|
try {
|
||||||
ReflectionUtil.invokeWithArguments(method, instance, sock);
|
ReflectionUtil.invokeWithArguments(method, instance, sock);
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("WebSocket处理异常", e);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (url.endsWith("*")) {
|
if (url.endsWith("*")) {
|
||||||
@@ -322,7 +327,7 @@ public class RouterHandlerFactory implements BaseHttpApi {
|
|||||||
parameterValueList.put(k, entity);
|
parameterValueList.put(k, entity);
|
||||||
}
|
}
|
||||||
} catch (ClassNotFoundException e) {
|
} catch (ClassNotFoundException e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("实体类绑定异常: {}", typeName, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -365,7 +370,7 @@ public class RouterHandlerFactory implements BaseHttpApi {
|
|||||||
Object entity = ParamUtil.multiMapToEntity(queryParams, aClass);
|
Object entity = ParamUtil.multiMapToEntity(queryParams, aClass);
|
||||||
parameterValueList.put(k, entity);
|
parameterValueList.put(k, entity);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("参数绑定异常: {}", v.getRight().getName(), e);
|
||||||
}
|
}
|
||||||
} else if (parameterValueList.get(k) == null
|
} else if (parameterValueList.get(k) == null
|
||||||
&& JsonObject.class.getName().equals(v.getRight().getName())) {
|
&& JsonObject.class.getName().equals(v.getRight().getName())) {
|
||||||
@@ -392,38 +397,43 @@ public class RouterHandlerFactory implements BaseHttpApi {
|
|||||||
|
|
||||||
if (data instanceof JsonResult jsonResult) {
|
if (data instanceof JsonResult jsonResult) {
|
||||||
doFireJsonResultResponse(ctx, (JsonResult<?>) data, jsonResult.getCode());
|
doFireJsonResultResponse(ctx, (JsonResult<?>) data, jsonResult.getCode());
|
||||||
}
|
} else if (data instanceof JsonObject) {
|
||||||
if (data instanceof JsonObject) {
|
|
||||||
doFireJsonObjectResponse(ctx, ((JsonObject) data));
|
doFireJsonObjectResponse(ctx, ((JsonObject) data));
|
||||||
} else if (data instanceof Future) { // 处理异步响应
|
} else if (data instanceof Future) { // 处理异步响应
|
||||||
((Future<?>) data).onSuccess(res -> {
|
Future<?> responseFuture = (Future<?>) data;
|
||||||
if (res instanceof JsonResult jsonResult) {
|
AtomicReference<RoutingContext> ctxRef = new AtomicReference<>(ctx);
|
||||||
doFireJsonResultResponse(ctx, jsonResult, jsonResult.getCode());
|
ctx.addEndHandler(v -> ctxRef.set(null));
|
||||||
|
responseFuture.onComplete(ar -> {
|
||||||
|
RoutingContext responseCtx = ctxRef.getAndSet(null);
|
||||||
|
if (responseCtx == null || isResponseDone(responseCtx)) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
if (res instanceof JsonObject) {
|
if (ar.succeeded()) {
|
||||||
doFireJsonObjectResponse(ctx, ((JsonObject) res));
|
Object res = ar.result();
|
||||||
} else if (res != null) {
|
if (res instanceof JsonResult jsonResult) {
|
||||||
doFireJsonResultResponse(ctx, JsonResult.data(res));
|
doFireJsonResultResponse(responseCtx, jsonResult, jsonResult.getCode());
|
||||||
|
} else if (res instanceof JsonObject) {
|
||||||
|
doFireJsonObjectResponse(responseCtx, ((JsonObject) res));
|
||||||
|
} else if (res != null) {
|
||||||
|
doFireJsonResultResponse(responseCtx, JsonResult.data(res));
|
||||||
|
} else {
|
||||||
|
doFireJsonResultResponse(responseCtx, JsonResult.data(null));
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
doFireJsonResultResponse(ctx, JsonResult.data(null));
|
Throwable e = ar.cause();
|
||||||
|
LOGGER.error("请求处理失败", e);
|
||||||
|
String msg = e != null && e.getMessage() != null ? e.getMessage() : "服务器内部错误";
|
||||||
|
doFireJsonResultResponse(responseCtx, JsonResult.error(msg), 500);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
}).onFailure(e -> doFireJsonResultResponse(ctx, JsonResult.error(e.getMessage()), 500));
|
|
||||||
} else {
|
} else {
|
||||||
doFireJsonResultResponse(ctx, JsonResult.data(data));
|
doFireJsonResultResponse(ctx, JsonResult.data(data));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("请求处理异常", e);
|
||||||
String err = e.getMessage();
|
String msg = e.getMessage() != null ? e.getMessage() : "服务器内部错误";
|
||||||
if (e.getCause() != null) {
|
doFireJsonResultResponse(ctx, JsonResult.error(msg), 500);
|
||||||
if (e.getCause() instanceof InvocationTargetException) {
|
|
||||||
err = ((InvocationTargetException) e.getCause()).getTargetException().getMessage();
|
|
||||||
} else {
|
|
||||||
err = e.getCause().getMessage();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
doFireJsonResultResponse(ctx, JsonResult.error(err), 500);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ import java.util.LinkedHashSet;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,6 +31,16 @@ public class CommonUtil {
|
|||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtil.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtil.class);
|
||||||
|
|
||||||
|
/** 正则表达式缓存,避免每次调用重新编译 */
|
||||||
|
private static final ConcurrentHashMap<String, Pattern> PATTERN_CACHE = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取预编译的 Pattern(带缓存)
|
||||||
|
*/
|
||||||
|
private static Pattern getCachedPattern(String regex) {
|
||||||
|
return PATTERN_CACHE.computeIfAbsent(regex, Pattern::compile);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 匹配正则list
|
* 匹配正则list
|
||||||
*
|
*
|
||||||
@@ -39,7 +51,7 @@ public class CommonUtil {
|
|||||||
public static boolean matchRegList(List<?> regList, String destStr) {
|
public static boolean matchRegList(List<?> regList, String destStr) {
|
||||||
// 判断是否忽略
|
// 判断是否忽略
|
||||||
for (Object ignores : regList) {
|
for (Object ignores : regList) {
|
||||||
if (destStr.matches(ignores.toString())) {
|
if (getCachedPattern(ignores.toString()).matcher(destStr).matches()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -147,13 +159,20 @@ public class CommonUtil {
|
|||||||
public static String getAppVersion() {
|
public static String getAppVersion() {
|
||||||
if (null == appVersion) {
|
if (null == appVersion) {
|
||||||
Properties properties = new Properties();
|
Properties properties = new Properties();
|
||||||
try {
|
try (var is = CommonUtil.class.getClassLoader().getResourceAsStream("app.properties")) {
|
||||||
properties.load(CommonUtil.class.getClassLoader().getResourceAsStream("app.properties"));
|
if (is != null) {
|
||||||
if (!properties.isEmpty()) {
|
properties.load(is);
|
||||||
appVersion = properties.getProperty("app.version") + "build" + properties.getProperty("build");
|
String version = properties.getProperty("app.version");
|
||||||
|
String build = properties.getProperty("build");
|
||||||
|
if (version != null && !version.contains("${")) {
|
||||||
|
appVersion = version + "build" + (build == null || build.contains("${") ? "" : build);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("读取app.properties失败", e);
|
||||||
|
}
|
||||||
|
if (appVersion == null) {
|
||||||
|
appVersion = "unknown";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return appVersion;
|
return appVersion;
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import io.vertx.core.json.JsonObject;
|
|||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 异步读取配置工具类
|
* 异步读取配置工具类
|
||||||
@@ -62,12 +64,35 @@ public class ConfigUtil {
|
|||||||
// 异步获取配置
|
// 异步获取配置
|
||||||
// 成功直接完成 promise
|
// 成功直接完成 promise
|
||||||
retriever.getConfig()
|
retriever.getConfig()
|
||||||
.onSuccess(promise::complete)
|
.onSuccess(config -> {
|
||||||
.onFailure(err -> {
|
promise.complete(config);
|
||||||
// 配置读取失败,直接返回失败 Future
|
|
||||||
promise.fail(new RuntimeException(
|
|
||||||
"读取配置文件失败: " + path, err));
|
|
||||||
retriever.close();
|
retriever.close();
|
||||||
|
})
|
||||||
|
.onFailure(err -> {
|
||||||
|
retriever.close();
|
||||||
|
// 读取失败时,尝试从 resources/ 子目录读取(兼容 Docker 卷挂载场景)
|
||||||
|
String resourcesPath = "resources/" + path;
|
||||||
|
if (!path.startsWith("resources/") && Files.exists(Path.of(resourcesPath))) {
|
||||||
|
ConfigStoreOptions fallbackStore = new ConfigStoreOptions()
|
||||||
|
.setType("file")
|
||||||
|
.setFormat(format)
|
||||||
|
.setConfig(new JsonObject().put("path", resourcesPath));
|
||||||
|
ConfigRetriever fallbackRetriever = ConfigRetriever
|
||||||
|
.create(vertx, new ConfigRetrieverOptions().addStore(fallbackStore));
|
||||||
|
fallbackRetriever.getConfig()
|
||||||
|
.onSuccess(config -> {
|
||||||
|
promise.complete(config);
|
||||||
|
fallbackRetriever.close();
|
||||||
|
})
|
||||||
|
.onFailure(e2 -> {
|
||||||
|
promise.fail(new RuntimeException(
|
||||||
|
"读取配置文件失败: " + path + " (也尝试了 " + resourcesPath + ")", e2));
|
||||||
|
fallbackRetriever.close();
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
promise.fail(new RuntimeException(
|
||||||
|
"读取配置文件失败: " + path, err));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
|
|||||||
@@ -4,17 +4,41 @@ import io.vertx.core.Future;
|
|||||||
import io.vertx.core.Promise;
|
import io.vertx.core.Promise;
|
||||||
|
|
||||||
import java.util.concurrent.ExecutionException;
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
|
||||||
public class FutureUtils {
|
public class FutureUtils {
|
||||||
|
|
||||||
public static <T> T getResult(Future<T> future) {
|
/** 默认同步等待超时时间(秒) */
|
||||||
try {
|
private static final long DEFAULT_TIMEOUT_SECONDS = 120;
|
||||||
return future.toCompletionStage().toCompletableFuture().get();
|
|
||||||
} catch (InterruptedException | ExecutionException e) {
|
public static <T> T getResult(Future<T> future) {
|
||||||
throw new RuntimeException(e);
|
try {
|
||||||
}
|
return future.toCompletionStage().toCompletableFuture()
|
||||||
}
|
.get(DEFAULT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new RuntimeException("线程被中断", e);
|
||||||
|
} catch (TimeoutException e) {
|
||||||
|
throw new RuntimeException("等待Future超时(" + DEFAULT_TIMEOUT_SECONDS + "秒)", e);
|
||||||
|
} catch (ExecutionException e) {
|
||||||
|
Throwable cause = e.getCause();
|
||||||
|
throw new RuntimeException(cause != null ? cause : e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static <T> T getResult(Promise<T> promise) {
|
public static <T> T getResult(Promise<T> promise) {
|
||||||
return promise.future().toCompletionStage().toCompletableFuture().join();
|
try {
|
||||||
|
return promise.future().toCompletionStage().toCompletableFuture()
|
||||||
|
.get(DEFAULT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new RuntimeException("线程被中断", e);
|
||||||
|
} catch (TimeoutException e) {
|
||||||
|
throw new RuntimeException("等待Promise超时(" + DEFAULT_TIMEOUT_SECONDS + "秒)", e);
|
||||||
|
} catch (ExecutionException e) {
|
||||||
|
Throwable cause = e.getCause();
|
||||||
|
throw new RuntimeException(cause != null ? cause : e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package cn.qaiu.vx.core.util;
|
package cn.qaiu.vx.core.util;
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* vertx 上下文外的本地容器 为不在vertx线程的方法传递数据
|
* vertx 上下文外的本地容器 为不在vertx线程的方法传递数据
|
||||||
@@ -10,11 +10,10 @@ import java.util.Map;
|
|||||||
* @author <a href="https://qaiu.top">QAIU</a>
|
* @author <a href="https://qaiu.top">QAIU</a>
|
||||||
*/
|
*/
|
||||||
public class LocalConstant {
|
public class LocalConstant {
|
||||||
private static final Map<String, Object> LOCAL_CONST = new HashMap<>();
|
private static final Map<String, Object> LOCAL_CONST = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
public static Map<String, Object> put(String k, Object v) {
|
public static Map<String, Object> put(String k, Object v) {
|
||||||
if (LOCAL_CONST.containsKey(k)) return LOCAL_CONST;
|
LOCAL_CONST.putIfAbsent(k, v);
|
||||||
LOCAL_CONST.put(k, v);
|
|
||||||
return LOCAL_CONST;
|
return LOCAL_CONST;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -36,16 +36,20 @@ public final class ParamUtil {
|
|||||||
|
|
||||||
public static MultiMap paramsToMap(String paramString) {
|
public static MultiMap paramsToMap(String paramString) {
|
||||||
MultiMap entries = MultiMap.caseInsensitiveMultiMap();
|
MultiMap entries = MultiMap.caseInsensitiveMultiMap();
|
||||||
if (paramString == null) return entries;
|
if (paramString == null || paramString.isEmpty()) return entries;
|
||||||
String[] params = paramString.split("&");
|
String[] params = paramString.split("&");
|
||||||
if (params.length == 0) return entries;
|
if (params.length == 0) return entries;
|
||||||
for (String param : params) {
|
for (String param : params) {
|
||||||
String[] kv = param.split("=");
|
if (param == null || param.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String[] kv = param.split("=", 2);
|
||||||
if (kv.length == 2) {
|
if (kv.length == 2) {
|
||||||
entries.set(kv[0], kv[1]);
|
entries.set(kv[0], kv[1]);
|
||||||
} else {
|
} else if (kv.length == 1) {
|
||||||
entries.set(kv[0], "");
|
entries.set(kv[0], "");
|
||||||
}
|
}
|
||||||
|
// kv.length == 0 时(空字符串),跳过
|
||||||
}
|
}
|
||||||
return entries;
|
return entries;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,10 @@ import java.lang.reflect.Method;
|
|||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.text.ParseException;
|
import java.text.ParseException;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import static cn.qaiu.vx.core.util.ConfigConstant.BASE_LOCATIONS;
|
import static cn.qaiu.vx.core.util.ConfigConstant.BASE_LOCATIONS;
|
||||||
|
|
||||||
@@ -36,9 +40,17 @@ import static cn.qaiu.vx.core.util.ConfigConstant.BASE_LOCATIONS;
|
|||||||
*/
|
*/
|
||||||
public final class ReflectionUtil {
|
public final class ReflectionUtil {
|
||||||
|
|
||||||
|
private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);
|
||||||
|
|
||||||
// 缓存Reflections实例,避免重复扫描(每次扫描约35K+值,耗时1-3秒,占用大量内存)
|
// 缓存Reflections实例,避免重复扫描(每次扫描约35K+值,耗时1-3秒,占用大量内存)
|
||||||
private static final Map<String, Reflections> REFLECTIONS_CACHE = new java.util.concurrent.ConcurrentHashMap<>();
|
private static final Map<String, Reflections> REFLECTIONS_CACHE = new java.util.concurrent.ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
// 预编译的类型匹配正则,避免每次请求重新编译
|
||||||
|
private static final Pattern BASIC_TYPE_PATTERN = Pattern.compile(
|
||||||
|
"^java\\.lang\\.((Boolean)|(Character)|(Byte)|(Short)|(Integer)|(Long)|(Float)|(Double)|(String))$");
|
||||||
|
private static final Pattern BASIC_TYPE_ARRAY_PATTERN = Pattern.compile(
|
||||||
|
"^(boolean|char|byte|short|int|long|float|double|String)\\[]$");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 以默认配置的基础包路径获取反射器
|
* 以默认配置的基础包路径获取反射器
|
||||||
*
|
*
|
||||||
@@ -128,7 +140,7 @@ public final class ReflectionUtil {
|
|||||||
parameterTypes[j - k]));
|
parameterTypes[j - k]));
|
||||||
}
|
}
|
||||||
} catch (NotFoundException e) {
|
} catch (NotFoundException e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("获取方法参数失败", e);
|
||||||
}
|
}
|
||||||
return paramMap;
|
return paramMap;
|
||||||
}
|
}
|
||||||
@@ -183,7 +195,7 @@ public final class ReflectionUtil {
|
|||||||
try {
|
try {
|
||||||
return DateUtils.parseDate(value, fmt);
|
return DateUtils.parseDate(value, fmt);
|
||||||
} catch (ParseException e) {
|
} catch (ParseException e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("日期解析失败: {}", value, e);
|
||||||
throw new RuntimeException("无法将格式化日期");
|
throw new RuntimeException("无法将格式化日期");
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -215,7 +227,7 @@ public final class ReflectionUtil {
|
|||||||
}
|
}
|
||||||
return arr;
|
return arr;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("数组类型转换失败: {}", value, e);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -229,8 +241,7 @@ public final class ReflectionUtil {
|
|||||||
if (ctClass.isPrimitive() || "java.util.Date".equals(ctClass.getName())) {
|
if (ctClass.isPrimitive() || "java.util.Date".equals(ctClass.getName())) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return ctClass.getName().matches("^java\\.lang\\.((Boolean)|(Character)|(Byte)|(Short)|(Integer)|(Long)|" +
|
return BASIC_TYPE_PATTERN.matcher(ctClass.getName()).matches();
|
||||||
"(Float)|(Double)|(String))$");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -241,7 +252,7 @@ public final class ReflectionUtil {
|
|||||||
public static boolean isBasicTypeArray(CtClass ctClass) {
|
public static boolean isBasicTypeArray(CtClass ctClass) {
|
||||||
if (!ctClass.isArray()) {
|
if (!ctClass.isArray()) {
|
||||||
return false;
|
return false;
|
||||||
} else return (ctClass.getName().matches("^(boolen|char|byte|short|int|long|float|double|String)\\[]$"));
|
} else return BASIC_TYPE_ARRAY_PATTERN.matcher(ctClass.getName()).matches();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -12,14 +12,21 @@ import static io.vertx.core.http.HttpHeaders.CONTENT_TYPE;
|
|||||||
public class ResponseUtil {
|
public class ResponseUtil {
|
||||||
|
|
||||||
public static void redirect(HttpServerResponse response, String url) {
|
public static void redirect(HttpServerResponse response, String url) {
|
||||||
|
if (response.ended() || response.closed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
response.putHeader(CONTENT_TYPE, "text/html; charset=utf-8")
|
response.putHeader(CONTENT_TYPE, "text/html; charset=utf-8")
|
||||||
.putHeader("Referrer-Policy", "no-referrer")
|
.putHeader("Referrer-Policy", "no-referrer")
|
||||||
.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
|
.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void redirect(HttpServerResponse response, String url, Promise<?> promise) {
|
public static void redirect(HttpServerResponse response, String url, Promise<?> promise) {
|
||||||
redirect(response, url);
|
try {
|
||||||
promise.complete();
|
redirect(response, url);
|
||||||
|
promise.tryComplete();
|
||||||
|
} catch (Throwable t) {
|
||||||
|
promise.tryFail(t);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void fireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject) {
|
public static void fireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject) {
|
||||||
@@ -31,12 +38,18 @@ public class ResponseUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void fireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject, int statusCode) {
|
public static void fireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject, int statusCode) {
|
||||||
|
if (ctx.response().ended() || ctx.response().closed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
ctx.response().putHeader(CONTENT_TYPE, "application/json; charset=utf-8")
|
ctx.response().putHeader(CONTENT_TYPE, "application/json; charset=utf-8")
|
||||||
.setStatusCode(statusCode)
|
.setStatusCode(statusCode)
|
||||||
.end(jsonObject.encode());
|
.end(jsonObject.encode());
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void fireJsonObjectResponse(HttpServerResponse ctx, JsonObject jsonObject, int statusCode) {
|
public static void fireJsonObjectResponse(HttpServerResponse ctx, JsonObject jsonObject, int statusCode) {
|
||||||
|
if (ctx.ended() || ctx.closed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
ctx.putHeader(CONTENT_TYPE, "application/json; charset=utf-8")
|
ctx.putHeader(CONTENT_TYPE, "application/json; charset=utf-8")
|
||||||
.setStatusCode(statusCode)
|
.setStatusCode(statusCode)
|
||||||
.end(jsonObject.encode());
|
.end(jsonObject.encode());
|
||||||
@@ -55,10 +68,16 @@ public class ResponseUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void fireTextResponse(RoutingContext ctx, String text) {
|
public static void fireTextResponse(RoutingContext ctx, String text) {
|
||||||
|
if (ctx.response().ended() || ctx.response().closed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
ctx.response().putHeader(CONTENT_TYPE, "text/html; charset=utf-8").end(text);
|
ctx.response().putHeader(CONTENT_TYPE, "text/html; charset=utf-8").end(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void sendError(RoutingContext ctx, int statusCode) {
|
public static void sendError(RoutingContext ctx, int statusCode) {
|
||||||
|
if (ctx.response().ended() || ctx.response().closed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
ctx.response().setStatusCode(statusCode).end();
|
ctx.response().setStatusCode(statusCode).end();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,6 @@ package cn.qaiu.vx.core.util;
|
|||||||
import io.vertx.core.json.JsonArray;
|
import io.vertx.core.json.JsonArray;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import io.vertx.core.shareddata.LocalMap;
|
import io.vertx.core.shareddata.LocalMap;
|
||||||
import io.vertx.core.shareddata.SharedData;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* vertx 共享数据
|
* vertx 共享数据
|
||||||
@@ -13,10 +12,8 @@ import io.vertx.core.shareddata.SharedData;
|
|||||||
*/
|
*/
|
||||||
public class SharedDataUtil {
|
public class SharedDataUtil {
|
||||||
|
|
||||||
private static final SharedData sharedData = VertxHolder.getVertxInstance().sharedData();
|
public static io.vertx.core.shareddata.SharedData shareData() {
|
||||||
|
return VertxHolder.getVertxInstance().sharedData();
|
||||||
public static SharedData shareData() {
|
|
||||||
return sharedData;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static LocalMap<String, Object> getLocalMap(String key) {
|
public static LocalMap<String, Object> getLocalMap(String key) {
|
||||||
@@ -24,7 +21,7 @@ public class SharedDataUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static <T> LocalMap<String, T> getLocalMapWithCast(String key) {
|
public static <T> LocalMap<String, T> getLocalMapWithCast(String key) {
|
||||||
return sharedData.getLocalMap(key);
|
return shareData().getLocalMap(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static JsonObject getJsonConfig(String key) {
|
public static JsonObject getJsonConfig(String key) {
|
||||||
|
|||||||
@@ -1,16 +1,22 @@
|
|||||||
package cn.qaiu.vx.core.verticle;
|
package cn.qaiu.vx.core.verticle;
|
||||||
|
|
||||||
import io.vertx.core.AbstractVerticle;
|
import io.vertx.core.AbstractVerticle;
|
||||||
|
import io.vertx.core.Future;
|
||||||
|
import io.vertx.core.Promise;
|
||||||
import io.vertx.core.http.*;
|
import io.vertx.core.http.*;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import io.vertx.core.net.NetClient;
|
import io.vertx.core.net.NetClient;
|
||||||
import io.vertx.core.net.NetClientOptions;
|
import io.vertx.core.net.NetClientOptions;
|
||||||
|
import io.vertx.core.net.NetSocket;
|
||||||
import io.vertx.core.net.ProxyOptions;
|
import io.vertx.core.net.ProxyOptions;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
|
|
||||||
import static cn.qaiu.vx.core.util.ConfigConstant.GLOBAL_CONFIG;
|
import static cn.qaiu.vx.core.util.ConfigConstant.GLOBAL_CONFIG;
|
||||||
@@ -22,15 +28,32 @@ import static cn.qaiu.vx.core.util.ConfigConstant.LOCAL;
|
|||||||
public class HttpProxyVerticle extends AbstractVerticle {
|
public class HttpProxyVerticle extends AbstractVerticle {
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(HttpProxyVerticle.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(HttpProxyVerticle.class);
|
||||||
|
|
||||||
|
static byte[] decodeProxyAuthorization(String encoded) {
|
||||||
|
var source = new ByteArrayInputStream(encoded.getBytes(StandardCharsets.ISO_8859_1));
|
||||||
|
// The streaming decoder uses scalar Java code and does not call the bulk intrinsic.
|
||||||
|
try (var decoder = Base64.getDecoder().wrap(source)) {
|
||||||
|
byte[] decoded = decoder.readAllBytes();
|
||||||
|
if (source.available() != 0) {
|
||||||
|
throw new IllegalArgumentException("Unexpected data after Base64 padding");
|
||||||
|
}
|
||||||
|
return decoded;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new IllegalArgumentException("Invalid Base64 proxy credentials", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private HttpClient httpClient;
|
private HttpClient httpClient;
|
||||||
private NetClient netClient;
|
private NetClient netClient;
|
||||||
|
private HttpServer httpServer;
|
||||||
|
private volatile boolean stopping = false;
|
||||||
|
|
||||||
private JsonObject proxyPreConf;
|
private JsonObject proxyPreConf;
|
||||||
private JsonObject proxyServerConf;
|
private JsonObject proxyServerConf;
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start() {
|
public void start(io.vertx.core.Promise<Void> startPromise) {
|
||||||
|
stopping = false;
|
||||||
proxyServerConf = ((JsonObject)vertx.sharedData().getLocalMap(LOCAL).get(GLOBAL_CONFIG)).getJsonObject("proxy-server");
|
proxyServerConf = ((JsonObject)vertx.sharedData().getLocalMap(LOCAL).get(GLOBAL_CONFIG)).getJsonObject("proxy-server");
|
||||||
proxyPreConf = ((JsonObject)vertx.sharedData().getLocalMap(LOCAL).get(GLOBAL_CONFIG)).getJsonObject("proxy-pre");
|
proxyPreConf = ((JsonObject)vertx.sharedData().getLocalMap(LOCAL).get(GLOBAL_CONFIG)).getJsonObject("proxy-pre");
|
||||||
Integer serverPort = proxyServerConf.getInteger("port");
|
Integer serverPort = proxyServerConf.getInteger("port");
|
||||||
@@ -41,7 +64,12 @@ public class HttpProxyVerticle extends AbstractVerticle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 初始化 HTTP 客户端,用于向目标服务器发送 HTTP 请求
|
// 初始化 HTTP 客户端,用于向目标服务器发送 HTTP 请求
|
||||||
HttpClientOptions httpClientOptions = new HttpClientOptions();
|
HttpClientOptions httpClientOptions = new HttpClientOptions()
|
||||||
|
.setMaxPoolSize(64)
|
||||||
|
.setMaxWaitQueueSize(256)
|
||||||
|
.setConnectTimeout(15000)
|
||||||
|
.setIdleTimeout(60)
|
||||||
|
.setKeepAlive(true);
|
||||||
if (proxyOptions != null) {
|
if (proxyOptions != null) {
|
||||||
httpClientOptions.setProxyOptions(proxyOptions);
|
httpClientOptions.setProxyOptions(proxyOptions);
|
||||||
}
|
}
|
||||||
@@ -54,14 +82,14 @@ public class HttpProxyVerticle extends AbstractVerticle {
|
|||||||
httpServerOptions.setClientAuth(ClientAuth.REQUIRED);
|
httpServerOptions.setClientAuth(ClientAuth.REQUIRED);
|
||||||
}
|
}
|
||||||
|
|
||||||
HttpServer server = vertx.createHttpServer();
|
httpServer = vertx.createHttpServer(httpServerOptions);
|
||||||
server.requestHandler(this::handleClientRequest);
|
httpServer.requestHandler(this::handleClientRequest);
|
||||||
|
|
||||||
// 初始化 NetClient,用于在 CONNECT 请求中建立 TCP 连接隧道
|
// 初始化 NetClient,用于在 CONNECT 请求中建立 TCP 连接隧道
|
||||||
NetClientOptions netClientOptions = new NetClientOptions();
|
NetClientOptions netClientOptions = new NetClientOptions();
|
||||||
|
|
||||||
if (proxyOptions != null) {
|
if (proxyOptions != null) {
|
||||||
httpClientOptions.setProxyOptions(proxyOptions);
|
netClientOptions.setProxyOptions(proxyOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
netClient = vertx.createNetClient(netClientOptions
|
netClient = vertx.createNetClient(netClientOptions
|
||||||
@@ -69,16 +97,22 @@ public class HttpProxyVerticle extends AbstractVerticle {
|
|||||||
.setTrustAll(true));
|
.setTrustAll(true));
|
||||||
|
|
||||||
// 启动 HTTP 代理服务器
|
// 启动 HTTP 代理服务器
|
||||||
server.listen(serverPort)
|
httpServer.listen(serverPort)
|
||||||
.onSuccess(res-> LOGGER.info("HTTP Proxy server started on port {}", serverPort))
|
.onSuccess(res -> {
|
||||||
.onFailure(err-> LOGGER.error("Failed to start HTTP Proxy server: " + err.getMessage()));
|
LOGGER.info("HTTP Proxy server started on port {}", serverPort);
|
||||||
|
startPromise.complete();
|
||||||
|
})
|
||||||
|
.onFailure(err -> {
|
||||||
|
LOGGER.error("Failed to start HTTP Proxy server: " + err.getMessage(), err);
|
||||||
|
closeClients().onComplete(close -> startPromise.fail(err));
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 处理 HTTP CONNECT 请求,用于代理 HTTPS 流量
|
// 处理 HTTP CONNECT 请求,用于代理 HTTPS 流量
|
||||||
private void handleConnectRequest(HttpServerRequest clientRequest) {
|
private void handleConnectRequest(HttpServerRequest clientRequest) {
|
||||||
String[] uriParts = clientRequest.uri().split(":");
|
String[] uriParts = clientRequest.uri().split(":");
|
||||||
if (uriParts.length != 2) {
|
if (uriParts.length != 2) {
|
||||||
clientRequest.response().setStatusCode(400).end("Bad Request: Invalid URI format");
|
failClientResponse(clientRequest.response(), 400, "Bad Request: Invalid URI format");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,57 +122,82 @@ public class HttpProxyVerticle extends AbstractVerticle {
|
|||||||
try {
|
try {
|
||||||
targetPort = Integer.parseInt(uriParts[1]);
|
targetPort = Integer.parseInt(uriParts[1]);
|
||||||
} catch (NumberFormatException e) {
|
} catch (NumberFormatException e) {
|
||||||
clientRequest.response().setStatusCode(400).end("Bad Request: Invalid port");
|
failClientResponse(clientRequest.response(), 400, "Bad Request: Invalid port");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
clientRequest.pause();
|
clientRequest.pause();
|
||||||
// 通过 NetClient 连接目标服务器并创建隧道
|
// 通过 NetClient 连接目标服务器并创建隧道
|
||||||
netClient.connect(targetPort, targetHost)
|
try {
|
||||||
.onSuccess(targetSocket -> {
|
netClient.connect(targetPort, targetHost)
|
||||||
// Upgrade client connection to NetSocket and implement bidirectional data flow
|
.onSuccess(targetSocket -> {
|
||||||
clientRequest.toNetSocket()
|
// Upgrade client connection to NetSocket and implement bidirectional data flow
|
||||||
.onSuccess(clientSocket -> {
|
clientRequest.toNetSocket()
|
||||||
// Set up bidirectional data forwarding
|
.onSuccess(clientSocket -> {
|
||||||
clientSocket.handler(targetSocket::write);
|
clientSocket.pipeTo(targetSocket)
|
||||||
targetSocket.handler(clientSocket::write);
|
.onFailure(err -> {
|
||||||
|
LOGGER.debug("CONNECT client -> target pipe closed", err);
|
||||||
|
closeTunnelSockets(clientSocket, targetSocket);
|
||||||
|
});
|
||||||
|
targetSocket.pipeTo(clientSocket)
|
||||||
|
.onFailure(err -> {
|
||||||
|
LOGGER.debug("CONNECT target -> client pipe closed", err);
|
||||||
|
closeTunnelSockets(clientSocket, targetSocket);
|
||||||
|
});
|
||||||
|
|
||||||
// Close the other socket when one side closes
|
// Close the other socket when one side closes
|
||||||
clientSocket.closeHandler(v -> targetSocket.close());
|
clientSocket.closeHandler(v -> targetSocket.close());
|
||||||
targetSocket.closeHandler(v -> clientSocket.close());
|
targetSocket.closeHandler(v -> clientSocket.close());
|
||||||
})
|
})
|
||||||
.onFailure(clientSocketAttempt -> {
|
.onFailure(clientSocketAttempt -> {
|
||||||
System.err.println("Failed to upgrade client connection to socket: " + clientSocketAttempt.getMessage());
|
System.err.println("Failed to upgrade client connection to socket: " + clientSocketAttempt.getMessage());
|
||||||
targetSocket.close();
|
targetSocket.close();
|
||||||
clientRequest.response().setStatusCode(500).end("Internal Server Error");
|
failClientRequestAndClose(clientRequest, 500, "Internal Server Error");
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.onFailure(connectionAttempt -> {
|
.onFailure(connectionAttempt -> {
|
||||||
System.err.println("Failed to connect to target: " + connectionAttempt.getMessage());
|
LOGGER.warn("Failed to connect to target: {}", connectionAttempt.getMessage());
|
||||||
clientRequest.response().setStatusCode(502).end("Bad Gateway: Unable to connect to target");
|
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Unable to connect to target");
|
||||||
});
|
});
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.warn("CONNECT 请求创建失败", e);
|
||||||
|
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Unable to connect to target");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 处理客户端的 HTTP 请求
|
// 处理客户端的 HTTP 请求
|
||||||
private void handleClientRequest(HttpServerRequest clientRequest) {
|
private void handleClientRequest(HttpServerRequest clientRequest) {
|
||||||
|
if (stopping) {
|
||||||
|
failClientResponse(clientRequest.response(), 503, "Service Unavailable");
|
||||||
|
return;
|
||||||
|
}
|
||||||
// 打印来源ip和访问目标URI
|
// 打印来源ip和访问目标URI
|
||||||
LOGGER.debug("source: {}, target: {}", clientRequest.remoteAddress().toString(), clientRequest.uri());
|
LOGGER.debug("source: {}, target: {}", clientRequest.remoteAddress().toString(), clientRequest.uri());
|
||||||
if (proxyServerConf.containsKey("username") &&
|
if (proxyServerConf.containsKey("username") &&
|
||||||
StringUtils.isNotBlank(proxyServerConf.getString("username"))) {
|
StringUtils.isNotBlank(proxyServerConf.getString("username"))) {
|
||||||
String s = clientRequest.headers().get("Proxy-Authorization");
|
String s = clientRequest.headers().get("Proxy-Authorization");
|
||||||
if (s == null) {
|
if (s == null) {
|
||||||
clientRequest.response().setStatusCode(403).end();
|
failClientResponse(clientRequest.response(), 403, null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String[] split = new String(Base64.getDecoder().decode(s.replace("Basic ", ""))).split(":");
|
String[] split;
|
||||||
if (split.length > 1) {
|
try {
|
||||||
// TODO
|
split = new String(decodeProxyAuthorization(s.replace("Basic ", ""))).split(":");
|
||||||
String username = proxyServerConf.getString("username");
|
} catch (IllegalArgumentException e) {
|
||||||
String password = proxyServerConf.getString("password");
|
LOGGER.warn("Proxy-Authorization header is not valid Base64");
|
||||||
if (!split[0].equals(username) || !split[1].equals(password)) {
|
failClientResponse(clientRequest.response(), 403, null);
|
||||||
LOGGER.info("-----auth failed------\nusername: {}\npassword: {}", username, password);
|
return;
|
||||||
clientRequest.response().setStatusCode(403).end();
|
}
|
||||||
return;
|
if (split.length <= 1) {
|
||||||
}
|
LOGGER.warn("Proxy-Authorization header format invalid: missing username:password separator");
|
||||||
|
failClientResponse(clientRequest.response(), 403, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String username = proxyServerConf.getString("username");
|
||||||
|
String password = proxyServerConf.getString("password");
|
||||||
|
if (!split[0].equals(username) || !split[1].equals(password)) {
|
||||||
|
LOGGER.info("-----auth failed------\nusername: {}", split[0]);
|
||||||
|
failClientResponse(clientRequest.response(), 403, null);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,40 +215,147 @@ public class HttpProxyVerticle extends AbstractVerticle {
|
|||||||
// 获取目标主机
|
// 获取目标主机
|
||||||
String hostHeader = clientRequest.getHeader("Host");
|
String hostHeader = clientRequest.getHeader("Host");
|
||||||
if (hostHeader == null) {
|
if (hostHeader == null) {
|
||||||
clientRequest.response().setStatusCode(400).end("Host header is missing");
|
failClientResponse(clientRequest.response(), 400, "Host header is missing");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
String targetHost = hostHeader.split(":")[0];
|
HostAndPort target;
|
||||||
int targetPort = extractPortFromUrl(clientRequest.uri()); // 默认为 HTTP 的端口
|
try {
|
||||||
clientRequest.pause(); // 暂停客户端请求的读取,避免数据丢失
|
target = parseHostHeader(hostHeader);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
failClientResponse(clientRequest.response(), 400, "Bad Request: Invalid Host header");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String targetHost = target.host();
|
||||||
|
int targetPort = extractPortFromUrl(clientRequest.uri(), target.port()); // 默认为 HTTP 的端口
|
||||||
|
if (targetPort <= 0) {
|
||||||
|
failClientResponse(clientRequest.response(), 400, "Bad Request: Invalid target port");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clientRequest.pause(); // 暂停客户端请求的读取,等上游请求创建完成
|
||||||
|
|
||||||
httpClient.request(clientRequest.method(), targetPort, targetHost, clientRequest.uri())
|
try {
|
||||||
.onSuccess(request -> {
|
httpClient.request(clientRequest.method(), targetPort, targetHost, clientRequest.uri())
|
||||||
clientRequest.resume(); // 恢复客户端请求的读取
|
.onSuccess(request -> {
|
||||||
|
// 逐个设置请求头
|
||||||
|
clientRequest.headers().forEach(header -> request.putHeader(header.getKey(), header.getValue()));
|
||||||
|
|
||||||
// 逐个设置请求头
|
request.response()
|
||||||
clientRequest.headers().forEach(header -> request.putHeader(header.getKey(), header.getValue()));
|
.onSuccess(response -> {
|
||||||
|
HttpServerResponse clientResponse = clientRequest.response();
|
||||||
|
if (clientResponse.ended() || clientResponse.closed()) {
|
||||||
|
response.resume();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
clientResponse.setStatusCode(response.statusCode());
|
||||||
|
clientResponse.headers().setAll(response.headers());
|
||||||
|
response.pipeTo(clientResponse)
|
||||||
|
.onFailure(err -> {
|
||||||
|
LOGGER.error("HTTP代理响应转发失败", err);
|
||||||
|
try {
|
||||||
|
response.request().reset();
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.debug("HTTP代理上游响应已关闭", e);
|
||||||
|
}
|
||||||
|
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Unable to reach target");
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.onFailure(err -> {
|
||||||
|
LOGGER.error("HTTP代理响应失败", err);
|
||||||
|
try {
|
||||||
|
request.reset();
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.debug("HTTP代理上游请求已关闭", e);
|
||||||
|
}
|
||||||
|
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Unable to reach target");
|
||||||
|
});
|
||||||
|
|
||||||
// 将客户端请求的 body 转发给目标服务器
|
clientRequest.pipeTo(request)
|
||||||
clientRequest.bodyHandler(body ->
|
.onFailure(err -> {
|
||||||
request.send(body)
|
LOGGER.error("HTTP代理请求转发失败", err);
|
||||||
.onSuccess(response -> {
|
try {
|
||||||
clientRequest.response().setStatusCode(response.statusCode());
|
request.reset();
|
||||||
clientRequest.response().headers().setAll(response.headers());
|
} catch (Exception e) {
|
||||||
response.body()
|
LOGGER.debug("HTTP代理上游请求已关闭", e);
|
||||||
.onSuccess(b -> clientRequest.response().end(b))
|
}
|
||||||
.onFailure(err -> clientRequest.response()
|
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Unable to reach target");
|
||||||
.setStatusCode(502).end("Bad Gateway: Unable to reach target"));
|
});
|
||||||
})
|
clientRequest.resume();
|
||||||
.onFailure(err -> clientRequest.response()
|
})
|
||||||
.setStatusCode(502).end("Bad Gateway: Unable to reach target"))
|
.onFailure(err -> {
|
||||||
);
|
LOGGER.error("HTTP请求失败", err);
|
||||||
})
|
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Request failed");
|
||||||
.onFailure(err -> {
|
});
|
||||||
err.printStackTrace();
|
} catch (Exception e) {
|
||||||
clientRequest.response().setStatusCode(502).end("Bad Gateway: Request failed");
|
LOGGER.error("HTTP请求创建失败", e);
|
||||||
});
|
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Request failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void failClientResponse(HttpServerResponse response, String message) {
|
||||||
|
failClientResponse(response, 502, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void failClientResponse(HttpServerResponse response, int statusCode, String message) {
|
||||||
|
if (response.ended() || response.closed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (!response.headWritten()) {
|
||||||
|
response.setStatusCode(statusCode);
|
||||||
|
if (message == null) {
|
||||||
|
response.end();
|
||||||
|
} else {
|
||||||
|
response.end(message);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
response.reset();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.debug("客户端响应已关闭,忽略代理错误响应", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void failClientRequestAndClose(HttpServerRequest request, int statusCode, String message) {
|
||||||
|
HttpServerResponse response = request.response();
|
||||||
|
if (response.ended() || response.closed()) {
|
||||||
|
closeClientConnection(request);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (!response.headWritten()) {
|
||||||
|
response.setStatusCode(statusCode);
|
||||||
|
Future<Void> endFuture = message == null ? response.end() : response.end(message);
|
||||||
|
endFuture.onComplete(v -> closeClientConnection(request));
|
||||||
|
} else {
|
||||||
|
response.reset();
|
||||||
|
closeClientConnection(request);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.debug("客户端响应已关闭,关闭代理连接", e);
|
||||||
|
closeClientConnection(request);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void closeClientConnection(HttpServerRequest request) {
|
||||||
|
try {
|
||||||
|
request.connection().close();
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.debug("关闭客户端代理连接失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void closeTunnelSockets(NetSocket clientSocket, NetSocket targetSocket) {
|
||||||
|
try {
|
||||||
|
clientSocket.close();
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.debug("关闭CONNECT客户端socket失败", e);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
targetSocket.close();
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.debug("关闭CONNECT目标socket失败", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -200,6 +366,10 @@ public class HttpProxyVerticle extends AbstractVerticle {
|
|||||||
* @return 提取的端口号,如果没有指定端口,则返回默认端口
|
* @return 提取的端口号,如果没有指定端口,则返回默认端口
|
||||||
*/
|
*/
|
||||||
public static int extractPortFromUrl(String urlString) {
|
public static int extractPortFromUrl(String urlString) {
|
||||||
|
return extractPortFromUrl(urlString, 80);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int extractPortFromUrl(String urlString, int defaultPort) {
|
||||||
try {
|
try {
|
||||||
URI uri = new URI(urlString);
|
URI uri = new URI(urlString);
|
||||||
int port = uri.getPort();
|
int port = uri.getPort();
|
||||||
@@ -208,27 +378,59 @@ public class HttpProxyVerticle extends AbstractVerticle {
|
|||||||
if ("https".equalsIgnoreCase(uri.getScheme())) {
|
if ("https".equalsIgnoreCase(uri.getScheme())) {
|
||||||
port = 443; // HTTPS 默认端口
|
port = 443; // HTTPS 默认端口
|
||||||
} else {
|
} else {
|
||||||
port = 80; // HTTP 默认端口
|
port = defaultPort; // HTTP 默认端口
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return port;
|
return port;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
LOGGER.error("提取端口失败: {}", urlString, e);
|
||||||
// 出现异常时返回 -1,表示提取失败
|
// 出现异常时返回 -1,表示提取失败
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private HostAndPort parseHostHeader(String hostHeader) {
|
||||||
|
if (hostHeader.startsWith("[")) {
|
||||||
|
int end = hostHeader.indexOf(']');
|
||||||
|
if (end > 0) {
|
||||||
|
String host = hostHeader.substring(1, end);
|
||||||
|
int port = 80;
|
||||||
|
if (hostHeader.length() > end + 2 && hostHeader.charAt(end + 1) == ':') {
|
||||||
|
port = Integer.parseInt(hostHeader.substring(end + 2));
|
||||||
|
}
|
||||||
|
return new HostAndPort(host, port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int lastColon = hostHeader.lastIndexOf(':');
|
||||||
|
if (lastColon > 0 && hostHeader.indexOf(':') == lastColon) {
|
||||||
|
return new HostAndPort(hostHeader.substring(0, lastColon), Integer.parseInt(hostHeader.substring(lastColon + 1)));
|
||||||
|
}
|
||||||
|
return new HostAndPort(hostHeader, 80);
|
||||||
|
}
|
||||||
|
|
||||||
|
private record HostAndPort(String host, int port) {
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void stop() {
|
public void stop(Promise<Void> stopPromise) {
|
||||||
// 停止 HTTP 客户端以释放资源
|
stopping = true;
|
||||||
if (httpClient != null) {
|
Future<Void> serverClose = httpServer == null ? Future.succeededFuture() : httpServer.close();
|
||||||
httpClient.close();
|
serverClose.onComplete(serverResult -> closeClients().onComplete(clientResult -> {
|
||||||
}
|
if (serverResult.failed()) {
|
||||||
if (netClient != null) {
|
stopPromise.fail(serverResult.cause());
|
||||||
netClient.close();
|
} else if (clientResult.failed()) {
|
||||||
}
|
stopPromise.fail(clientResult.cause());
|
||||||
|
} else {
|
||||||
|
stopPromise.complete();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Future<Void> closeClients() {
|
||||||
|
Future<Void> httpClientClose = httpClient == null ? Future.succeededFuture() : httpClient.close();
|
||||||
|
Future<Void> netClientClose = netClient == null ? Future.succeededFuture() : netClient.close();
|
||||||
|
return Future.all(httpClientClose, netClientClose).mapEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -46,7 +46,7 @@ public class PostExecVerticle extends AbstractVerticle {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
LOGGER.info("PostExecVerticle 开始执行...");
|
LOGGER.info("PostExecVerticle 开始执行...");
|
||||||
|
|
||||||
if (appRunImplementations != null && !appRunImplementations.isEmpty()) {
|
if (appRunImplementations != null && !appRunImplementations.isEmpty()) {
|
||||||
appRunImplementations.forEach(appRun -> {
|
appRunImplementations.forEach(appRun -> {
|
||||||
try {
|
try {
|
||||||
@@ -61,7 +61,7 @@ public class PostExecVerticle extends AbstractVerticle {
|
|||||||
} else {
|
} else {
|
||||||
LOGGER.info("未找到 AppRun 接口的实现类");
|
LOGGER.info("未找到 AppRun 接口的实现类");
|
||||||
}
|
}
|
||||||
|
|
||||||
LOGGER.info("PostExecVerticle 执行完成");
|
LOGGER.info("PostExecVerticle 执行完成");
|
||||||
startPromise.complete();
|
startPromise.complete();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,17 +3,20 @@ package cn.qaiu.vx.core.verticle;
|
|||||||
import cn.qaiu.vx.core.util.*;
|
import cn.qaiu.vx.core.util.*;
|
||||||
import io.vertx.core.AbstractVerticle;
|
import io.vertx.core.AbstractVerticle;
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
|
import io.vertx.core.Handler;
|
||||||
import io.vertx.core.Promise;
|
import io.vertx.core.Promise;
|
||||||
import io.vertx.core.http.HttpClient;
|
import io.vertx.core.http.HttpClient;
|
||||||
import io.vertx.core.http.HttpClientOptions;
|
import io.vertx.core.http.HttpClientOptions;
|
||||||
import io.vertx.core.http.HttpServer;
|
import io.vertx.core.http.HttpServer;
|
||||||
import io.vertx.core.http.HttpServerOptions;
|
import io.vertx.core.http.HttpServerOptions;
|
||||||
import io.vertx.core.http.HttpServerRequest;
|
import io.vertx.core.http.HttpServerRequest;
|
||||||
|
import io.vertx.core.http.HttpServerResponse;
|
||||||
import io.vertx.core.json.JsonArray;
|
import io.vertx.core.json.JsonArray;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import io.vertx.core.net.PemKeyCertOptions;
|
import io.vertx.core.net.PemKeyCertOptions;
|
||||||
import io.vertx.ext.web.Route;
|
import io.vertx.ext.web.Route;
|
||||||
import io.vertx.ext.web.Router;
|
import io.vertx.ext.web.Router;
|
||||||
|
import io.vertx.ext.web.RoutingContext;
|
||||||
import io.vertx.ext.web.handler.StaticHandler;
|
import io.vertx.ext.web.handler.StaticHandler;
|
||||||
import io.vertx.ext.web.proxy.handler.ProxyHandler;
|
import io.vertx.ext.web.proxy.handler.ProxyHandler;
|
||||||
import io.vertx.httpproxy.HttpProxy;
|
import io.vertx.httpproxy.HttpProxy;
|
||||||
@@ -27,7 +30,9 @@ import org.slf4j.LoggerFactory;
|
|||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.net.MalformedURLException;
|
import java.net.MalformedURLException;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
@@ -45,10 +50,6 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(ReverseProxyVerticle.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(ReverseProxyVerticle.class);
|
||||||
|
|
||||||
private static final String PATH_PROXY_CONFIG = SharedDataUtil
|
|
||||||
.getJsonConfig(ConfigConstant.GLOBAL_CONFIG)
|
|
||||||
.getString("proxyConf");
|
|
||||||
private static final Future<JsonObject> CONFIG = ConfigUtil.readYamlConfig(PATH_PROXY_CONFIG);
|
|
||||||
private static final String DEFAULT_PATH_404 = "webroot/err/page404.html";
|
private static final String DEFAULT_PATH_404 = "webroot/err/page404.html";
|
||||||
|
|
||||||
private static String serverName = "Vert.x-proxy-server"; //Server name in Http response header
|
private static String serverName = "Vert.x-proxy-server"; //Server name in Http response header
|
||||||
@@ -58,26 +59,40 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
/**
|
/**
|
||||||
* 【优化】HttpClient连接池,按host:port缓存复用,避免每个请求都创建新连接
|
* 【优化】HttpClient连接池,按host:port缓存复用,避免每个请求都创建新连接
|
||||||
*/
|
*/
|
||||||
private final Map<String, HttpClient> httpClientPool = new ConcurrentHashMap<>();
|
private final Map<String, HttpClientEntry> httpClientPool = new ConcurrentHashMap<>();
|
||||||
|
private final List<HttpServer> httpServers = new ArrayList<>();
|
||||||
|
private volatile boolean stopping = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接池条目。HttpProxy 会持有这里的 HttpClient 引用,不能在路由仍可用时关闭。
|
||||||
|
*/
|
||||||
|
private static class HttpClientEntry {
|
||||||
|
final HttpClient client;
|
||||||
|
|
||||||
|
HttpClientEntry(HttpClient client) {
|
||||||
|
this.client = client;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 【优化】高并发场景下的HttpClient配置
|
* 【优化】高并发场景下的HttpClient配置
|
||||||
*/
|
*/
|
||||||
private static final int MAX_POOL_SIZE = 100; // 最大连接池大小
|
private static final int MAX_POOL_SIZE = 32; // 最大连接池大小
|
||||||
private static final int MAX_WAIT_QUEUE_SIZE = 500; // 最大等待队列大小
|
private static final int MAX_WAIT_QUEUE_SIZE = 128; // 最大等待队列大小
|
||||||
private static final int CONNECT_TIMEOUT = 30000; // 连接超时30秒
|
private static final int CONNECT_TIMEOUT = 30000; // 连接超时30秒
|
||||||
private static final int IDLE_TIMEOUT = 60; // 空闲超时60秒
|
private static final int IDLE_TIMEOUT = 60; // 空闲超时60秒
|
||||||
private static final boolean KEEP_ALIVE = true; // 启用Keep-Alive
|
private static final boolean KEEP_ALIVE = true; // 启用Keep-Alive
|
||||||
private static final boolean PIPELINING = true; // 启用HTTP管线化
|
private static final boolean PIPELINING = false; // 代理场景关闭管线化,避免慢响应堆积
|
||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start(Promise<Void> startPromise) {
|
public void start(Promise<Void> startPromise) {
|
||||||
CONFIG.onSuccess(this::handleProxyConfList).onFailure(e -> {
|
stopping = false;
|
||||||
|
String pathProxyConfig = SharedDataUtil
|
||||||
|
.getJsonConfig(ConfigConstant.GLOBAL_CONFIG)
|
||||||
|
.getString("proxyConf");
|
||||||
|
ConfigUtil.readYamlConfig(pathProxyConfig).onSuccess(config -> startProxyServers(config).onComplete(startPromise)).onFailure(e -> {
|
||||||
LOGGER.info("web代理配置已禁用,当前仅支持API调用");
|
LOGGER.info("web代理配置已禁用,当前仅支持API调用");
|
||||||
|
startPromise.complete();
|
||||||
});
|
});
|
||||||
// createFileListener
|
|
||||||
startPromise.complete();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -85,16 +100,49 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void stop(Promise<Void> stopPromise) {
|
public void stop(Promise<Void> stopPromise) {
|
||||||
LOGGER.info("Stopping ReverseProxyVerticle, closing {} HttpClient connections...", httpClientPool.size());
|
stopping = true;
|
||||||
httpClientPool.values().forEach(client -> {
|
LOGGER.info("Stopping ReverseProxyVerticle, closing {} servers and {} HttpClient connections...",
|
||||||
|
httpServers.size(), httpClientPool.size());
|
||||||
|
|
||||||
|
List<Future<Void>> serverCloseFutures = new ArrayList<>();
|
||||||
|
httpServers.forEach(server -> serverCloseFutures.add(server.close()));
|
||||||
|
Future<Void> serverCloseFuture = serverCloseFutures.isEmpty()
|
||||||
|
? Future.succeededFuture()
|
||||||
|
: Future.all(serverCloseFutures).mapEmpty();
|
||||||
|
|
||||||
|
serverCloseFuture.onComplete(serverClose -> {
|
||||||
|
List<Future<Void>> clientCloseFutures = new ArrayList<>();
|
||||||
|
closeHttpClients(clientCloseFutures);
|
||||||
|
Future<Void> clientCloseFuture = clientCloseFutures.isEmpty()
|
||||||
|
? Future.succeededFuture()
|
||||||
|
: Future.all(clientCloseFutures).mapEmpty();
|
||||||
|
|
||||||
|
clientCloseFuture.onComplete(clientClose -> {
|
||||||
|
if (serverClose.succeeded()) {
|
||||||
|
httpServers.clear();
|
||||||
|
}
|
||||||
|
if (clientClose.succeeded()) {
|
||||||
|
httpClientPool.clear();
|
||||||
|
}
|
||||||
|
if (serverClose.failed()) {
|
||||||
|
stopPromise.fail(serverClose.cause());
|
||||||
|
} else if (clientClose.failed()) {
|
||||||
|
stopPromise.fail(clientClose.cause());
|
||||||
|
} else {
|
||||||
|
stopPromise.complete();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void closeHttpClients(List<Future<Void>> closeFutures) {
|
||||||
|
httpClientPool.values().forEach(entry -> {
|
||||||
try {
|
try {
|
||||||
client.close();
|
closeFutures.add(entry.client.close());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
LOGGER.warn("Error closing HttpClient: {}", e.getMessage());
|
LOGGER.warn("Error closing HttpClient: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
httpClientPool.clear();
|
|
||||||
stopPromise.complete();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -105,7 +153,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
*/
|
*/
|
||||||
private HttpClient getOrCreateHttpClient(String host, int port) {
|
private HttpClient getOrCreateHttpClient(String host, int port) {
|
||||||
String key = host + ":" + port;
|
String key = host + ":" + port;
|
||||||
return httpClientPool.computeIfAbsent(key, k -> {
|
HttpClientEntry entry = httpClientPool.computeIfAbsent(key, k -> {
|
||||||
LOGGER.info("Creating new HttpClient for {}", key);
|
LOGGER.info("Creating new HttpClient for {}", key);
|
||||||
HttpClientOptions options = new HttpClientOptions()
|
HttpClientOptions options = new HttpClientOptions()
|
||||||
.setMaxPoolSize(MAX_POOL_SIZE) // 连接池大小
|
.setMaxPoolSize(MAX_POOL_SIZE) // 连接池大小
|
||||||
@@ -116,15 +164,16 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
.setKeepAliveTimeout(120) // Keep-Alive超时120秒
|
.setKeepAliveTimeout(120) // Keep-Alive超时120秒
|
||||||
.setPipelining(PIPELINING) // HTTP管线化
|
.setPipelining(PIPELINING) // HTTP管线化
|
||||||
.setPipeliningLimit(10) // 管线化限制
|
.setPipeliningLimit(10) // 管线化限制
|
||||||
.setDecompressionSupported(true) // 支持解压响应
|
.setDecompressionSupported(false) // 代理不解压,避免放大内存
|
||||||
.setTcpKeepAlive(true) // TCP Keep-Alive
|
.setTcpKeepAlive(true) // TCP Keep-Alive
|
||||||
.setTcpNoDelay(true) // 禁用Nagle算法,降低延迟
|
.setTcpNoDelay(true) // 禁用Nagle算法,降低延迟
|
||||||
.setTcpFastOpen(true) // 启用TCP Fast Open
|
.setTcpFastOpen(true) // 启用TCP Fast Open
|
||||||
.setTcpQuickAck(true) // 启用TCP Quick ACK
|
.setTcpQuickAck(true) // 启用TCP Quick ACK
|
||||||
.setReuseAddress(true) // 允许地址重用
|
.setReuseAddress(true) // 允许地址重用
|
||||||
.setReusePort(true); // 允许端口重用
|
.setReusePort(true); // 允许端口重用
|
||||||
return vertx.createHttpClient(options);
|
return new HttpClientEntry(vertx.createHttpClient(options));
|
||||||
});
|
});
|
||||||
|
return entry.client;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -137,7 +186,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
*
|
*
|
||||||
* @param config proxy config
|
* @param config proxy config
|
||||||
*/
|
*/
|
||||||
private void handleProxyConfList(JsonObject config) {
|
private Future<Void> startProxyServers(JsonObject config) {
|
||||||
serverName = config.getString("server-name");
|
serverName = config.getString("server-name");
|
||||||
// 解析全局 trusted-proxies
|
// 解析全局 trusted-proxies
|
||||||
JsonArray trustedArr = config.getJsonArray("trusted-proxies");
|
JsonArray trustedArr = config.getJsonArray("trusted-proxies");
|
||||||
@@ -149,13 +198,15 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
JsonArray proxyConfList = config.getJsonArray("proxy");
|
JsonArray proxyConfList = config.getJsonArray("proxy");
|
||||||
|
List<Future<Void>> listenFutures = new ArrayList<>();
|
||||||
if (proxyConfList != null) {
|
if (proxyConfList != null) {
|
||||||
proxyConfList.forEach(proxyConf -> {
|
proxyConfList.forEach(proxyConf -> {
|
||||||
if (proxyConf instanceof JsonObject) {
|
if (proxyConf instanceof JsonObject) {
|
||||||
handleProxyConf((JsonObject) proxyConf);
|
listenFutures.add(handleProxyConf((JsonObject) proxyConf));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
return listenFutures.isEmpty() ? Future.succeededFuture() : Future.all(listenFutures).mapEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -201,7 +252,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
*
|
*
|
||||||
* @param proxyConf 代理配置
|
* @param proxyConf 代理配置
|
||||||
*/
|
*/
|
||||||
private void handleProxyConf(JsonObject proxyConf) {
|
private Future<Void> handleProxyConf(JsonObject proxyConf) {
|
||||||
// page404 path
|
// page404 path
|
||||||
if (proxyConf.containsKey(
|
if (proxyConf.containsKey(
|
||||||
|
|
||||||
@@ -226,6 +277,10 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
|
|
||||||
// Add Server name header
|
// Add Server name header
|
||||||
proxyRouter.route().handler(ctx -> {
|
proxyRouter.route().handler(ctx -> {
|
||||||
|
if (stopping) {
|
||||||
|
sendProxyError(ctx, 503, "Service Unavailable");
|
||||||
|
return;
|
||||||
|
}
|
||||||
String realPath = ctx.request().uri();
|
String realPath = ctx.request().uri();
|
||||||
if (realPath.startsWith(REROUTE_PATH_PREFIX)) {
|
if (realPath.startsWith(REROUTE_PATH_PREFIX)) {
|
||||||
// vertx web proxy暂不支持rewrite, 所以这里进行手动替换, 请求地址中的请求path前缀替换为originPath
|
// vertx web proxy暂不支持rewrite, 所以这里进行手动替换, 请求地址中的请求path前缀替换为originPath
|
||||||
@@ -234,7 +289,9 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx.response().putHeader("Server", serverName);
|
if (!ctx.response().ended() && !ctx.response().closed()) {
|
||||||
|
ctx.response().putHeader("Server", serverName);
|
||||||
|
}
|
||||||
ctx.next();
|
ctx.next();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -250,15 +307,19 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
|
|
||||||
// Send page404 page
|
// Send page404 page
|
||||||
proxyRouter.errorHandler(404, ctx -> {
|
proxyRouter.errorHandler(404, ctx -> {
|
||||||
ctx.response().sendFile(proxyConf.getString("page404"));
|
sendNotFoundPage(ctx, proxyConf.getString("page404"));
|
||||||
});
|
});
|
||||||
|
proxyRouter.errorHandler(500, this::handleProxyFailure);
|
||||||
|
|
||||||
HttpServer server = getHttpsServer(proxyConf);
|
HttpServer server = getHttpsServer(proxyConf);
|
||||||
server.requestHandler(proxyRouter);
|
server.requestHandler(proxyRouter);
|
||||||
|
|
||||||
Integer port = proxyConf.getInteger("listen");
|
Integer port = proxyConf.getInteger("listen");
|
||||||
LOGGER.info("proxy server start on {} port", port);
|
LOGGER.info("proxy server start on {} port", port);
|
||||||
server.listen(port);
|
return server.listen(port)
|
||||||
|
.onSuccess(s -> httpServers.add(s))
|
||||||
|
.onFailure(e -> LOGGER.error("proxy server start failed on {} port", port, e))
|
||||||
|
.mapEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
private HttpServer getHttpsServer(JsonObject proxyConf) {
|
private HttpServer getHttpsServer(JsonObject proxyConf) {
|
||||||
@@ -267,7 +328,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
.setTcpKeepAlive(true) // TCP Keep-Alive
|
.setTcpKeepAlive(true) // TCP Keep-Alive
|
||||||
.setTcpNoDelay(true) // 禁用Nagle算法
|
.setTcpNoDelay(true) // 禁用Nagle算法
|
||||||
.setCompressionSupported(true) // 启用压缩
|
.setCompressionSupported(true) // 启用压缩
|
||||||
.setAcceptBacklog(50000) // 增加积压队列到50000
|
.setAcceptBacklog(1024) // 限制积压队列,避免小容器内存膨胀
|
||||||
.setIdleTimeout(120) // 空闲超时120秒
|
.setIdleTimeout(120) // 空闲超时120秒
|
||||||
.setTcpFastOpen(true) // 启用TCP Fast Open
|
.setTcpFastOpen(true) // 启用TCP Fast Open
|
||||||
.setTcpQuickAck(true) // 启用TCP Quick ACK
|
.setTcpQuickAck(true) // 启用TCP Quick ACK
|
||||||
@@ -303,6 +364,67 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
return vertx.createHttpServer(httpServerOptions);
|
return vertx.createHttpServer(httpServerOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void addProxyHandler(Route route, HttpProxy httpProxy) {
|
||||||
|
Handler<RoutingContext> proxyHandler = ProxyHandler.create(httpProxy);
|
||||||
|
route.handler(ctx -> {
|
||||||
|
try {
|
||||||
|
proxyHandler.handle(ctx);
|
||||||
|
} catch (Throwable t) {
|
||||||
|
LOGGER.error("反向代理处理异常", t);
|
||||||
|
ctx.fail(t);
|
||||||
|
}
|
||||||
|
}).failureHandler(this::handleProxyFailure);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleProxyFailure(RoutingContext ctx) {
|
||||||
|
Throwable failure = ctx.failure();
|
||||||
|
if (failure != null) {
|
||||||
|
LOGGER.error("反向代理路由失败", failure);
|
||||||
|
}
|
||||||
|
int statusCode = ctx.statusCode() > 0 ? ctx.statusCode() : 502;
|
||||||
|
if (statusCode < 400) {
|
||||||
|
statusCode = 502;
|
||||||
|
}
|
||||||
|
sendProxyError(ctx, statusCode, "Bad Gateway");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendNotFoundPage(RoutingContext ctx, String page404) {
|
||||||
|
HttpServerResponse response = ctx.response();
|
||||||
|
if (response.ended() || response.closed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (response.headWritten()) {
|
||||||
|
response.reset();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
response.sendFile(page404)
|
||||||
|
.onFailure(e -> {
|
||||||
|
LOGGER.warn("发送代理 404 页面失败: {}", page404, e);
|
||||||
|
sendProxyError(ctx, 404, "404 not found");
|
||||||
|
});
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.warn("发送代理 404 页面异常: {}", page404, e);
|
||||||
|
sendProxyError(ctx, 404, "404 not found");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendProxyError(RoutingContext ctx, int statusCode, String message) {
|
||||||
|
HttpServerResponse response = ctx.response();
|
||||||
|
if (response.ended() || response.closed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (!response.headWritten()) {
|
||||||
|
response.setStatusCode(statusCode).end(message);
|
||||||
|
} else {
|
||||||
|
response.reset();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.debug("代理响应已关闭,忽略错误响应", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 处理静态资源配置
|
* 处理静态资源配置
|
||||||
*
|
*
|
||||||
@@ -351,7 +473,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
String host = url.getHost();
|
String host = url.getHost();
|
||||||
int port = url.getPort();
|
int port = url.getPort();
|
||||||
if (port == -1) {
|
if (port == -1) {
|
||||||
port = 80;
|
port = 443;
|
||||||
}
|
}
|
||||||
String originPath = url.getPath();
|
String originPath = url.getPath();
|
||||||
LOGGER.info("path {}, originPath {}, to {}:{}", path, originPath, host, port);
|
LOGGER.info("path {}, originPath {}, to {}:{}", path, originPath, host, port);
|
||||||
@@ -391,15 +513,14 @@ public class ReverseProxyVerticle extends AbstractVerticle {
|
|||||||
if (StringUtils.isEmpty(originPath) || path.equals(originPath)) {
|
if (StringUtils.isEmpty(originPath) || path.equals(originPath)) {
|
||||||
Route route = path.startsWith("~") ? proxyRouter.routeWithRegex(path.substring(1))
|
Route route = path.startsWith("~") ? proxyRouter.routeWithRegex(path.substring(1))
|
||||||
: proxyRouter.route(path);
|
: proxyRouter.route(path);
|
||||||
// 【优化】为代理处理器添加超时
|
addProxyHandler(route, httpProxy);
|
||||||
route.handler(ProxyHandler.create(httpProxy));
|
|
||||||
} else {
|
} else {
|
||||||
// 配置 /api/, / => 请求 /api/test 代理后 /test
|
// 配置 /api/, / => 请求 /api/test 代理后 /test
|
||||||
// 配置 /api/, /xxx => 请求 /api/test 代理后 /xxx/test
|
// 配置 /api/, /xxx => 请求 /api/test 代理后 /xxx/test
|
||||||
final String path0 = path;
|
final String path0 = path;
|
||||||
final String originPath0 = REROUTE_PATH_PREFIX + originPath;
|
final String originPath0 = REROUTE_PATH_PREFIX + originPath;
|
||||||
|
|
||||||
proxyRouter.route(originPath0 + "*").handler(ProxyHandler.create(httpProxy));
|
addProxyHandler(proxyRouter.route(originPath0 + "*"), httpProxy);
|
||||||
proxyRouter.route(path0 + "*").handler(ctx -> {
|
proxyRouter.route(path0 + "*").handler(ctx -> {
|
||||||
String realPath = ctx.request().uri();
|
String realPath = ctx.request().uri();
|
||||||
if (realPath.startsWith(path0)) {
|
if (realPath.startsWith(path0)) {
|
||||||
|
|||||||
@@ -22,22 +22,22 @@ public class RouterVerticle extends AbstractVerticle {
|
|||||||
|
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(RouterVerticle.class);
|
private static final Logger LOGGER = LoggerFactory.getLogger(RouterVerticle.class);
|
||||||
|
|
||||||
private static final int port = SharedDataUtil.getValueForServerConfig("port");
|
|
||||||
private static final Router router = new RouterHandlerFactory(
|
|
||||||
SharedDataUtil.getJsonStringForServerConfig("contextPath")).createRouter();
|
|
||||||
|
|
||||||
private static final JsonObject globalConfig = SharedDataUtil.getJsonConfig("globalConfig");
|
|
||||||
|
|
||||||
private HttpServer server;
|
private HttpServer server;
|
||||||
|
private Router router;
|
||||||
|
private int port;
|
||||||
|
private JsonObject globalConfig;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
LOGGER.info(JacksonConfig.class.getSimpleName() + " >> ");
|
LOGGER.info(JacksonConfig.class.getSimpleName() + " >> ");
|
||||||
JacksonConfig.nothing();
|
JacksonConfig.nothing();
|
||||||
LOGGER.info("To start listening to port {} ......", port);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start(Promise<Void> startPromise) {
|
public void start(Promise<Void> startPromise) {
|
||||||
|
port = SharedDataUtil.getValueForServerConfig("port");
|
||||||
|
globalConfig = SharedDataUtil.getJsonConfig("globalConfig");
|
||||||
|
LOGGER.info("To start listening to port {} ......", port);
|
||||||
|
|
||||||
// 端口是否占用
|
// 端口是否占用
|
||||||
if (CommonUtil.isPortUsing(port)) {
|
if (CommonUtil.isPortUsing(port)) {
|
||||||
throw new RuntimeException("Start fail: the '" + port + "' port is already in use...");
|
throw new RuntimeException("Start fail: the '" + port + "' port is already in use...");
|
||||||
@@ -61,9 +61,11 @@ public class RouterVerticle extends AbstractVerticle {
|
|||||||
.setReuseAddress(true) // 允许地址重用
|
.setReuseAddress(true) // 允许地址重用
|
||||||
.setReusePort(true); // 允许端口重用
|
.setReusePort(true); // 允许端口重用
|
||||||
|
|
||||||
|
router = new RouterHandlerFactory(
|
||||||
|
SharedDataUtil.getJsonStringForServerConfig("contextPath")).createRouter();
|
||||||
server = vertx.createHttpServer(options);
|
server = vertx.createHttpServer(options);
|
||||||
|
|
||||||
server.requestHandler(router).webSocketHandler(s->{}).listen()
|
server.requestHandler(router).listen()
|
||||||
.onSuccess(s -> startPromise.complete())
|
.onSuccess(s -> startPromise.complete())
|
||||||
.onFailure(e -> startPromise.fail(e.getCause()));
|
.onFailure(e -> startPromise.fail(e.getCause()));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,15 @@ import cn.qaiu.vx.core.base.BaseAsyncService;
|
|||||||
import cn.qaiu.vx.core.util.ReflectionUtil;
|
import cn.qaiu.vx.core.util.ReflectionUtil;
|
||||||
import io.vertx.core.AbstractVerticle;
|
import io.vertx.core.AbstractVerticle;
|
||||||
import io.vertx.core.Promise;
|
import io.vertx.core.Promise;
|
||||||
|
import io.vertx.core.eventbus.MessageConsumer;
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
import io.vertx.serviceproxy.ServiceBinder;
|
import io.vertx.serviceproxy.ServiceBinder;
|
||||||
import org.reflections.Reflections;
|
import org.reflections.Reflections;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
@@ -24,6 +28,7 @@ public class ServiceVerticle extends AbstractVerticle {
|
|||||||
Logger LOGGER = LoggerFactory.getLogger(ServiceVerticle.class);
|
Logger LOGGER = LoggerFactory.getLogger(ServiceVerticle.class);
|
||||||
private static final AtomicInteger ID = new AtomicInteger(1);
|
private static final AtomicInteger ID = new AtomicInteger(1);
|
||||||
private static final Set<Class<?>> handlers;
|
private static final Set<Class<?>> handlers;
|
||||||
|
private final List<MessageConsumer<JsonObject>> consumers = new ArrayList<>();
|
||||||
|
|
||||||
static {
|
static {
|
||||||
Reflections reflections = ReflectionUtil.getReflections();
|
Reflections reflections = ReflectionUtil.getReflections();
|
||||||
@@ -39,7 +44,10 @@ public class ServiceVerticle extends AbstractVerticle {
|
|||||||
try {
|
try {
|
||||||
serviceNames.append(asyncService.getName()).append("|");
|
serviceNames.append(asyncService.getName()).append("|");
|
||||||
BaseAsyncService asInstance = (BaseAsyncService) ReflectionUtil.newWithNoParam(asyncService);
|
BaseAsyncService asInstance = (BaseAsyncService) ReflectionUtil.newWithNoParam(asyncService);
|
||||||
binder.setAddress(asInstance.getAddress()).register(asInstance.getAsyncInterfaceClass(), asInstance);
|
String address = asInstance.getAddress();
|
||||||
|
MessageConsumer<JsonObject> consumer = binder.setAddress(address)
|
||||||
|
.register(asInstance.getAsyncInterfaceClass(), asInstance);
|
||||||
|
consumers.add(consumer);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
LOGGER.error("Failed to register service: {}", asyncService.getName(), e);
|
LOGGER.error("Failed to register service: {}", asyncService.getName(), e);
|
||||||
}
|
}
|
||||||
@@ -49,4 +57,19 @@ public class ServiceVerticle extends AbstractVerticle {
|
|||||||
}
|
}
|
||||||
startPromise.complete();
|
startPromise.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stop(Promise<Void> stopPromise) {
|
||||||
|
int count = consumers.size();
|
||||||
|
consumers.forEach(consumer -> {
|
||||||
|
try {
|
||||||
|
consumer.unregister();
|
||||||
|
} catch (Exception e) {
|
||||||
|
LOGGER.warn("Failed to unregister service consumer at address: {}", consumer.address(), e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
consumers.clear();
|
||||||
|
LOGGER.info("ServiceVerticle stopped, unregistered {} services", count);
|
||||||
|
stopPromise.complete();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -32,7 +32,7 @@ public class HttpProxyConf {
|
|||||||
public HttpProxyConf() {
|
public HttpProxyConf() {
|
||||||
this.username = DEFAULT_USERNAME;
|
this.username = DEFAULT_USERNAME;
|
||||||
this.password = DEFAULT_PASSWORD;
|
this.password = DEFAULT_PASSWORD;
|
||||||
this.timeout = DEFAULT_PORT;
|
this.port = DEFAULT_PORT;
|
||||||
this.timeout = DEFAULT_TIMEOUT;
|
this.timeout = DEFAULT_TIMEOUT;
|
||||||
this.preProxyOptions = new ProxyOptions();
|
this.preProxyOptions = new ProxyOptions();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
app.version=${project.version}
|
app.version=${project.version}
|
||||||
build=${build.timestamp}
|
build=${maven.build.timestamp}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package cn.qaiu.vx.core.verticle;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
|
public class HttpProxyBase64Test {
|
||||||
|
@Test
|
||||||
|
public void matchesJdkBasicDecoder() {
|
||||||
|
for (String value : new String[]{"", "Zg", "Zg==", "Zm8=", "dXNlcjpwYXNz", "+/8=", "ABCD",
|
||||||
|
"AB==", "Z", "Zg=", "Zm8==", "Zg==suffix", "Zg==\n", "-_8=", "AA\u2603", "===="}) {
|
||||||
|
byte[] expected;
|
||||||
|
try {
|
||||||
|
expected = Base64.getDecoder().decode(value);
|
||||||
|
} catch (IllegalArgumentException expectedFailure) {
|
||||||
|
try {
|
||||||
|
HttpProxyVerticle.decodeProxyAuthorization(value);
|
||||||
|
} catch (IllegalArgumentException actualFailure) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
fail("Accepted invalid proxy credentials: " + value);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
assertArrayEquals(expected, HttpProxyVerticle.decodeProxyAuthorization(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Fix permissions on volume-mounted directories (runs as root)
|
||||||
|
chown -R appuser:appgroup /app/db /app/logs /app/resources 2>/dev/null || true
|
||||||
|
|
||||||
|
# Run Java directly - entrypoint is PID 1, exec makes Java PID 1
|
||||||
|
# Docker SIGTERM goes directly to Java, triggering ShutdownHook
|
||||||
|
DEFAULT_JVM_OPTS="-Xmx${JVM_XMX:-512M} -Xss${JVM_XSS:-512k} -XX:MaxDirectMemorySize=${JVM_MAX_DIRECT_MEMORY:-256M} -DNFD_LOG_LEVEL=${NFD_LOG_LEVEL:-info} -DNFD_PLAYGROUND_ENABLED=${NFD_PLAYGROUND_ENABLED:-false}"
|
||||||
|
if [ -n "${JVM_MAX_METASPACE:-}" ]; then
|
||||||
|
DEFAULT_JVM_OPTS="$DEFAULT_JVM_OPTS -XX:MaxMetaspaceSize=$JVM_MAX_METASPACE"
|
||||||
|
fi
|
||||||
|
# Keep this after JVM_OPTS to disable the intrinsic even with an older base image.
|
||||||
|
VECTOR_MODULE_OPT=
|
||||||
|
if java --list-modules 2>/dev/null | grep -q '^jdk.incubator.vector@'; then
|
||||||
|
VECTOR_MODULE_OPT=--add-modules=jdk.incubator.vector
|
||||||
|
fi
|
||||||
|
exec java ${VECTOR_MODULE_OPT} ${DEFAULT_JVM_OPTS} ${JVM_OPTS} -XX:-UseBASE64Intrinsics -Duser.timezone=${TZ:-Asia/Shanghai} -jar /app/netdisk-fast-download.jar
|
||||||
+4
-4
@@ -4,26 +4,26 @@ NFD 解析器模块:聚合各类网盘/分享页解析,统一输出文件列
|
|||||||
|
|
||||||
- 语言:Java 17
|
- 语言:Java 17
|
||||||
- 构建:Maven
|
- 构建:Maven
|
||||||
- 模块版本:10.1.17
|
- 模块版本:10.2.7
|
||||||
|
|
||||||
## 依赖(Maven Central)
|
## 依赖(Maven Central)
|
||||||
```xml
|
```xml
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cn.qaiu</groupId>
|
<groupId>cn.qaiu</groupId>
|
||||||
<artifactId>parser</artifactId>
|
<artifactId>parser</artifactId>
|
||||||
<version>10.1.17</version>
|
<version>10.2.7</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
- Gradle Groovy DSL:
|
- Gradle Groovy DSL:
|
||||||
```groovy
|
```groovy
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation 'cn.qaiu:parser:10.1.17'
|
implementation 'cn.qaiu:parser:10.2.7'
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
- Gradle Kotlin DSL:
|
- Gradle Kotlin DSL:
|
||||||
```kotlin
|
```kotlin
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("cn.qaiu:parser:10.1.17")
|
implementation("cn.qaiu:parser:10.2.7")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -24,11 +24,11 @@
|
|||||||
|
|
||||||
### 认证参数说明(v0.2.1+)
|
### 认证参数说明(v0.2.1+)
|
||||||
|
|
||||||
部分网盘(如夸克QK、UC网盘)需要登录后的 Cookie 才能解析。`auth` 参数用于传递认证信息:
|
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。夸克小文件可以不登录;UC 必须有 Cookie。`auth` 参数用于传递认证信息:
|
||||||
|
|
||||||
**加密方式**:
|
**加密方式**:
|
||||||
- 算法:AES/ECB/PKCS5Padding
|
- 算法:AES/ECB/PKCS5Padding
|
||||||
- 密钥:`nfd_auth_key2026`(16字节)
|
- 密钥:由自建服务显式配置并通过安全渠道交给可信客户端(无公共默认值)
|
||||||
- 流程:JSON → AES加密 → Base64 → URL编码
|
- 流程:JSON → AES加密 → Base64 → URL编码
|
||||||
|
|
||||||
**JSON 结构**:
|
**JSON 结构**:
|
||||||
@@ -42,8 +42,9 @@
|
|||||||
**网盘认证要求**:
|
**网盘认证要求**:
|
||||||
| 网盘 | 认证要求 |
|
| 网盘 | 认证要求 |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
| 夸克网盘(QK) | **必须** |
|
| 夸克网盘(QK) | 小文件可免登录;超过访客大小限制(23018)需要 Cookie |
|
||||||
| UC网盘(UC) | **必须** |
|
| UC网盘(UC) | **必须** |
|
||||||
|
| 123网盘(YE) | 下载通常需要本机 `auths.ye.authorization`;公共云解析没有共享账号 |
|
||||||
| 小飞机网盘(FJ) | 大文件需要 |
|
| 小飞机网盘(FJ) | 大文件需要 |
|
||||||
| 蓝奏优享(IZ) | 大文件需要 |
|
| 蓝奏优享(IZ) | 大文件需要 |
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cn.qaiu</groupId>
|
<groupId>cn.qaiu</groupId>
|
||||||
<artifactId>parser</artifactId>
|
<artifactId>parser</artifactId>
|
||||||
<version>10.1.17</version>
|
<version>10.2.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cn.qaiu</groupId>
|
<groupId>cn.qaiu</groupId>
|
||||||
<artifactId>parser</artifactId>
|
<artifactId>parser</artifactId>
|
||||||
<version>10.1.17</version>
|
<version>10.2.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -240,13 +240,13 @@ var encoded = JsHttpClient.urlEncode("hello world"); // "hello%20world"
|
|||||||
var decoded = JsHttpClient.urlDecode("hello%20world"); // "hello world"
|
var decoded = JsHttpClient.urlDecode("hello%20world"); // "hello world"
|
||||||
|
|
||||||
// 发送简单表单数据
|
// 发送简单表单数据
|
||||||
var formResponse = http.sendForm({
|
var formResponse = http.sendForm("https://api.example.com/login", {
|
||||||
username: "user",
|
username: "user",
|
||||||
password: "pass"
|
password: "pass"
|
||||||
});
|
});
|
||||||
|
|
||||||
// 发送JSON数据
|
// 发送JSON数据
|
||||||
var jsonResponse = http.sendJson({
|
var jsonResponse = http.sendJson("https://api.example.com/submit", {
|
||||||
name: "test",
|
name: "test",
|
||||||
value: 123
|
value: 123
|
||||||
});
|
});
|
||||||
@@ -637,7 +637,7 @@ A: 使用 `shareLinkInfo.getSharePassword()` 方法。
|
|||||||
|
|
||||||
### Q: 如何处理需要登录的网盘?
|
### Q: 如何处理需要登录的网盘?
|
||||||
|
|
||||||
A: 使用 `http.putHeader()` 设置认证头,或使用 `http.sendForm()` 发送登录表单。
|
A: 使用 `http.putHeader()` 设置认证头,或使用 `http.sendForm(url, data)` 发送登录表单。
|
||||||
|
|
||||||
### Q: 如何解析复杂的HTML?
|
### Q: 如何解析复杂的HTML?
|
||||||
|
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ List<FileInfo> files = tool.parseFileListSync();
|
|||||||
```
|
```
|
||||||
|
|
||||||
要点:
|
要点:
|
||||||
- 必须先 WebClientVertxInit.init(Vertx);若未显式初始化,内部将懒加载 Vertx.vertx(),建议显式注入以统一生命周期。
|
- 必须先 WebClientVertxInit.init(Vertx);未初始化时会直接报错,避免解析器偷偷创建第二个 Vert.x 实例。
|
||||||
- 支持三种同步方法:
|
- 支持三种同步方法:
|
||||||
- `parseSync()`: 解析单个文件下载链接
|
- `parseSync()`: 解析单个文件下载链接
|
||||||
- `parseFileListSync()`: 解析文件列表
|
- `parseFileListSync()`: 解析文件列表
|
||||||
|
|||||||
@@ -261,39 +261,11 @@ var methods = systemClass.getDeclaredMethods();
|
|||||||
|
|
||||||
Nashorn引擎默认允许JavaScript访问所有Java类,这是一个严重的安全隐患。以下是建议的安全措施:
|
Nashorn引擎默认允许JavaScript访问所有Java类,这是一个严重的安全隐患。以下是建议的安全措施:
|
||||||
|
|
||||||
### 1. 使用ClassFilter限制类访问 🔒 必须
|
### 1. 演练场与已注册解析器的类访问限制
|
||||||
|
|
||||||
```java
|
两个入口都通过 `ParserScriptEngine.create()` 创建 Nashorn 引擎。引擎使用 `--no-java`,类过滤器拒绝按名称解析 Java 类。引擎在执行解析器代码前禁用包入口、脚本加载函数和脚本上下文全局变量。解析器仍可使用项目显式注入的分享信息、HTTP、Fetch 和日志接口。
|
||||||
import jdk.nashorn.api.scripting.ClassFilter;
|
|
||||||
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
|
||||||
|
|
||||||
public class SecurityClassFilter implements ClassFilter {
|
`ParserScriptEngineTest` 检查受限全局变量的属性,并通过两个执行入口验证普通解析器的行为。
|
||||||
@Override
|
|
||||||
public boolean exposeToScripts(String className) {
|
|
||||||
// 黑名单:禁止访问危险类
|
|
||||||
if (className.startsWith("java.lang.Runtime") ||
|
|
||||||
className.startsWith("java.lang.ProcessBuilder") ||
|
|
||||||
className.startsWith("java.io.File") ||
|
|
||||||
className.startsWith("java.nio.file") ||
|
|
||||||
className.startsWith("java.lang.System") ||
|
|
||||||
className.startsWith("java.lang.Class") ||
|
|
||||||
className.startsWith("java.lang.reflect") ||
|
|
||||||
className.startsWith("java.net.Socket") ||
|
|
||||||
className.startsWith("java.net.URL")) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 白名单:只允许特定的类
|
|
||||||
// return className.startsWith("允许的包名");
|
|
||||||
|
|
||||||
return false; // 默认拒绝所有
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用ClassFilter创建引擎
|
|
||||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
|
||||||
ScriptEngine engine = factory.getScriptEngine(new SecurityClassFilter());
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. 设置执行超时 ⏱️ 强烈推荐
|
### 2. 设置执行超时 ⏱️ 强烈推荐
|
||||||
|
|
||||||
|
|||||||
@@ -33,8 +33,8 @@ URL解码 → Base64解码 → AES解密 → JSON对象
|
|||||||
### 加密配置
|
### 加密配置
|
||||||
|
|
||||||
- **加密算法**: AES/ECB/PKCS5Padding
|
- **加密算法**: AES/ECB/PKCS5Padding
|
||||||
- **密钥长度**: 16位(128位)
|
- **密钥长度**: 16、24 或 32 个 UTF-8 字节
|
||||||
- **默认密钥**: `nfd_auth_key2026`(可在 `app-dev.yml` 中通过 `server.authEncryptKey` 配置)
|
- **密钥**: 没有公共默认值。需要对接的可信客户端应使用自建服务显式配置的 `server.authEncryptKey`。
|
||||||
|
|
||||||
### 密钥作用说明(重要)
|
### 密钥作用说明(重要)
|
||||||
|
|
||||||
@@ -43,7 +43,7 @@ URL解码 → Base64解码 → AES解密 → JSON对象
|
|||||||
1. `server.authEncryptKey`
|
1. `server.authEncryptKey`
|
||||||
- 用途:加解密 `auth` 参数(前端/调用方传入的认证信息)
|
- 用途:加解密 `auth` 参数(前端/调用方传入的认证信息)
|
||||||
- 影响范围:`/parser`、`/json/parser`、`/v2/linkInfo` 等接口中的 `auth` 参数
|
- 影响范围:`/parser`、`/json/parser`、`/v2/linkInfo` 等接口中的 `auth` 参数
|
||||||
- 注意:这是 **AES 对称加密密钥**,要求 16 位
|
- 注意:这是 **AES 对称加密密钥**,要求 16、24 或 32 字节
|
||||||
|
|
||||||
2. `server.donatedAccountFailureTokenSignKey`
|
2. `server.donatedAccountFailureTokenSignKey`
|
||||||
- 用途:签名和验签“捐赠账号失败计数 token”(用于防伪造、失败计数)
|
- 用途:签名和验签“捐赠账号失败计数 token”(用于防伪造、失败计数)
|
||||||
@@ -109,6 +109,8 @@ URL解码 → Base64解码 → AES解密 → JSON对象
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> 123云盘(`ye`)账号密码登录如果返回验证码或风控,解析会直接失败,并提示改用 Authorization,不会尝试验证码。请在浏览器登录后复制 `authorToken` / 请求头 `authorization` / Cookie `sso-token`,用 `authType=authorization` 或 `accesstoken` 传入,或写入 `app-dev.yml` 的 `auths.ye.authorization`。
|
||||||
|
|
||||||
#### 4. 自定义认证
|
#### 4. 自定义认证
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -192,7 +194,7 @@ AuthParam decoded = AuthParamCodec.decode(encrypted);
|
|||||||
// 使用 CryptoJS 库
|
// 使用 CryptoJS 库
|
||||||
const CryptoJS = require('crypto-js');
|
const CryptoJS = require('crypto-js');
|
||||||
|
|
||||||
const AUTH_KEY = 'nfd_auth_key2026';
|
const AUTH_KEY = process.env.NFD_AUTH_ENCRYPT_KEY;
|
||||||
|
|
||||||
// 加密
|
// 加密
|
||||||
function encodeAuthParam(authObj) {
|
function encodeAuthParam(authObj) {
|
||||||
@@ -232,7 +234,8 @@ from urllib.parse import quote, unquote
|
|||||||
from Crypto.Cipher import AES
|
from Crypto.Cipher import AES
|
||||||
from Crypto.Util.Padding import pad, unpad
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
|
||||||
AUTH_KEY = b'nfd_auth_key2026'
|
import os
|
||||||
|
AUTH_KEY = os.environ['NFD_AUTH_ENCRYPT_KEY'].encode('utf-8')
|
||||||
|
|
||||||
def encode_auth_param(auth_obj):
|
def encode_auth_param(auth_obj):
|
||||||
"""加密认证参数"""
|
"""加密认证参数"""
|
||||||
@@ -321,8 +324,8 @@ if (auths != null) {
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
server:
|
server:
|
||||||
# auth参数加密密钥(16位AES密钥)
|
# auth参数加密密钥(16、24 或 32 字节)
|
||||||
authEncryptKey: 'your_custom_key16'
|
# authEncryptKey: "" # 仅在可信客户端或多实例需共享密钥时显式配置
|
||||||
|
|
||||||
# 捐赠账号失败计数token签名密钥(HMAC)
|
# 捐赠账号失败计数token签名密钥(HMAC)
|
||||||
# 建议使用较长随机字符串,并与 authEncryptKey 不同
|
# 建议使用较长随机字符串,并与 authEncryptKey 不同
|
||||||
@@ -339,3 +342,4 @@ server:
|
|||||||
## 更新日志
|
## 更新日志
|
||||||
|
|
||||||
- **2026-02-05**: 初始版本,支持 accesstoken、cookie、password、custom 认证类型
|
- **2026-02-05**: 初始版本,支持 accesstoken、cookie、password、custom 认证类型
|
||||||
|
- **2026-09-27**: 补充 123云盘账号密码登录触发验证码/风控时改用 Authorization 的说明
|
||||||
@@ -57,6 +57,8 @@
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> 123云盘(`ye`)账号密码登录触发验证码/风控时,请改用 `authType=authorization` 或 `accesstoken`(`token` 填浏览器中的 Bearer token / JWT),或在 `app-dev.yml` 配置 `auths.ye.authorization`。解析不会尝试验证码。
|
||||||
|
|
||||||
### 自定义认证
|
### 自定义认证
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -70,7 +72,7 @@
|
|||||||
## 使用说明
|
## 使用说明
|
||||||
|
|
||||||
1. **编码流程**: JSON对象 → AES加密 → Base64编码 → URL编码
|
1. **编码流程**: JSON对象 → AES加密 → Base64编码 → URL编码
|
||||||
2. **加密配置**: AES/ECB/PKCS5Padding, 密钥: `nfd_auth_key2026` (16位)
|
2. **加密配置**: AES/ECB/PKCS5Padding, 密钥: 自建服务配置值(无公共默认值)
|
||||||
3. **接口调用**: `GET /parser?url={分享链接}&pwd={提取码}&auth={加密认证参数}`
|
3. **接口调用**: `GET /parser?url={分享链接}&pwd={提取码}&auth={加密认证参数}`
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
this.temporaryExecutor = WebClientVertxInit.get().createSharedWorkerExecutor(
|
this.temporaryExecutor = WebClientVertxInit.get().createSharedWorkerExecutor(
|
||||||
"playground-temp-" + System.currentTimeMillis(),
|
"playground-temp-" + System.currentTimeMillis(),
|
||||||
1, // 每个请求只需要1个线程
|
1, // 每个请求只需要1个线程
|
||||||
10000000000L // 设置非常长的超时,避免被vertx强制中断
|
10000000000L // 设置非常长的超时,避免触发Vert.x阻塞线程告警
|
||||||
);
|
);
|
||||||
|
|
||||||
// 执行完成或超时后关闭
|
// 执行完成或超时后关闭
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ executionFuture.toCompletionStage()
|
|||||||
### 长期方案(需大量工作)
|
### 长期方案(需大量工作)
|
||||||
1. **迁移到GraalVM JavaScript引擎**
|
1. **迁移到GraalVM JavaScript引擎**
|
||||||
- 支持CPU时间限制
|
- 支持CPU时间限制
|
||||||
- 可以强制中断
|
- 相比Nashorn更容易实现受控取消
|
||||||
- 更好的性能
|
- 更好的性能
|
||||||
- 但需要额外依赖
|
- 但需要额外依赖
|
||||||
|
|
||||||
|
|||||||
+51
-9
@@ -12,7 +12,7 @@
|
|||||||
|
|
||||||
<groupId>cn.qaiu</groupId>
|
<groupId>cn.qaiu</groupId>
|
||||||
<artifactId>parser</artifactId>
|
<artifactId>parser</artifactId>
|
||||||
<version>10.2.5</version>
|
<version>${parserVersion}</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<name>cn.qaiu:parser</name>
|
<name>cn.qaiu:parser</name>
|
||||||
@@ -35,9 +35,9 @@
|
|||||||
</developers>
|
</developers>
|
||||||
|
|
||||||
<scm>
|
<scm>
|
||||||
<connection>scm:git:https://github.com/qaiu/netdisk-fast-download.git</connection>
|
<connection>scm:git:https://github.com/${github.owner}/${github.repo}.git</connection>
|
||||||
<developerConnection>scm:git:ssh://[email protected]:qaiu/netdisk-fast-download.git</developerConnection>
|
<developerConnection>scm:git:ssh://[email protected]:${github.owner}/${github.repo}.git</developerConnection>
|
||||||
<url>https://github.com/qaiu/netdisk-fast-download</url>
|
<url>https://github.com/${github.owner}/${github.repo}</url>
|
||||||
</scm>
|
</scm>
|
||||||
|
|
||||||
<distributionManagement>
|
<distributionManagement>
|
||||||
@@ -52,20 +52,19 @@
|
|||||||
</distributionManagement>
|
</distributionManagement>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<revision>0.2.1</revision>
|
|
||||||
<java.version>17</java.version>
|
<java.version>17</java.version>
|
||||||
<maven.compiler.source>17</maven.compiler.source>
|
<maven.compiler.source>17</maven.compiler.source>
|
||||||
<maven.compiler.target>17</maven.compiler.target>
|
<maven.compiler.target>17</maven.compiler.target>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
|
||||||
<!-- Versions -->
|
<!-- Versions -->
|
||||||
<vertx.version>4.5.24</vertx.version>
|
<vertx.version>4.5.27</vertx.version>
|
||||||
<org.reflections.version>0.10.2</org.reflections.version>
|
<org.reflections.version>0.10.2</org.reflections.version>
|
||||||
<lombok.version>1.18.38</lombok.version>
|
<lombok.version>1.18.38</lombok.version>
|
||||||
<slf4j.version>2.0.16</slf4j.version>
|
<slf4j.version>2.0.16</slf4j.version>
|
||||||
<commons-lang3.version>3.18.0</commons-lang3.version>
|
<commons-lang3.version>3.18.0</commons-lang3.version>
|
||||||
<jackson.version>2.18.6</jackson.version>
|
<jackson.version>2.18.9</jackson.version>
|
||||||
<logback.version>1.5.19</logback.version>
|
<logback.version>1.5.32</logback.version>
|
||||||
<junit.version>4.13.2</junit.version>
|
<junit.version>4.13.2</junit.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
@@ -124,6 +123,41 @@
|
|||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
|
|
||||||
|
<!-- 从 git remote origin 自动识别 GitHub 仓库地址 -->
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.gmavenplus</groupId>
|
||||||
|
<artifactId>gmavenplus-plugin</artifactId>
|
||||||
|
<version>4.1.1</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.groovy</groupId>
|
||||||
|
<artifactId>groovy</artifactId>
|
||||||
|
<version>4.0.24</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>initialize</phase>
|
||||||
|
<goals><goal>execute</goal></goals>
|
||||||
|
<configuration>
|
||||||
|
<scripts>
|
||||||
|
<script>
|
||||||
|
def url = 'git remote get-url origin'.execute().text.trim()
|
||||||
|
def m = (url =~ 'github\\.com[:/]([^/]+)/([^/.]+?)(?:\\.git)?$')
|
||||||
|
if (m.find()) {
|
||||||
|
project.properties.setProperty('github.owner', m.group(1))
|
||||||
|
project.properties.setProperty('github.repo', m.group(2))
|
||||||
|
} else {
|
||||||
|
project.properties.setProperty('github.owner', 'qaiu')
|
||||||
|
project.properties.setProperty('github.repo', 'netdisk-fast-download')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</scripts>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
|
||||||
<!-- 编译 -->
|
<!-- 编译 -->
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
@@ -131,6 +165,10 @@
|
|||||||
<version>3.13.0</version>
|
<version>3.13.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<release>${maven.compiler.source}</release>
|
<release>${maven.compiler.source}</release>
|
||||||
|
<compilerArgs>
|
||||||
|
<arg>--add-modules</arg>
|
||||||
|
<arg>jdk.incubator.vector</arg>
|
||||||
|
</compilerArgs>
|
||||||
<encoding>${project.build.sourceEncoding}</encoding>
|
<encoding>${project.build.sourceEncoding}</encoding>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
@@ -166,7 +204,11 @@
|
|||||||
<!-- 忽略 Javadoc 错误 -->
|
<!-- 忽略 Javadoc 错误 -->
|
||||||
<failOnError>false</failOnError>
|
<failOnError>false</failOnError>
|
||||||
<!-- 禁用 doclint(新版参数名改为 additionalOptions) -->
|
<!-- 禁用 doclint(新版参数名改为 additionalOptions) -->
|
||||||
<additionalOptions>-Xdoclint:none</additionalOptions>
|
<additionalOptions>
|
||||||
|
<additionalOption>-Xdoclint:none</additionalOption>
|
||||||
|
<additionalOption>--add-modules</additionalOption>
|
||||||
|
<additionalOption>jdk.incubator.vector</additionalOption>
|
||||||
|
</additionalOptions>
|
||||||
<!-- 如果项目源码中几乎没有 Javadoc,可设 true -->
|
<!-- 如果项目源码中几乎没有 Javadoc,可设 true -->
|
||||||
<quiet>true</quiet>
|
<quiet>true</quiet>
|
||||||
</configuration>
|
</configuration>
|
||||||
|
|||||||
@@ -7,12 +7,15 @@ import org.slf4j.LoggerFactory;
|
|||||||
import cn.qaiu.parser.custom.CustomParserRegistry;
|
import cn.qaiu.parser.custom.CustomParserRegistry;
|
||||||
|
|
||||||
public class WebClientVertxInit {
|
public class WebClientVertxInit {
|
||||||
private Vertx vertx = null;
|
private volatile Vertx vertx = null;
|
||||||
private static final WebClientVertxInit INSTANCE = new WebClientVertxInit();
|
private static final WebClientVertxInit INSTANCE = new WebClientVertxInit();
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(WebClientVertxInit.class);
|
private static final Logger log = LoggerFactory.getLogger(WebClientVertxInit.class);
|
||||||
|
|
||||||
public static void init(Vertx vx) {
|
public static synchronized void init(Vertx vx) {
|
||||||
|
if (vx == null) {
|
||||||
|
throw new IllegalArgumentException("Vertx instance must not be null");
|
||||||
|
}
|
||||||
INSTANCE.vertx = vx;
|
INSTANCE.vertx = vx;
|
||||||
|
|
||||||
// 自动加载JavaScript解析器脚本
|
// 自动加载JavaScript解析器脚本
|
||||||
@@ -23,18 +26,10 @@ public class WebClientVertxInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Vertx get() {
|
public static synchronized Vertx get() {
|
||||||
if (INSTANCE.vertx == null) {
|
if (INSTANCE.vertx == null) {
|
||||||
log.info("getVertx: Vertx实例不存在, 创建Vertx实例.");
|
throw new IllegalStateException("Vertx实例未初始化,请先调用 WebClientVertxInit.init(vertx)");
|
||||||
INSTANCE.vertx = Vertx.vertx();
|
|
||||||
|
|
||||||
// 如果Vertx实例是新创建的,也尝试加载JavaScript脚本
|
|
||||||
try {
|
|
||||||
CustomParserRegistry.autoLoadJsScripts();
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("自动加载JavaScript解析器脚本失败", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return INSTANCE.vertx;
|
return INSTANCE.vertx;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
package cn.qaiu.entity;
|
package cn.qaiu.entity;
|
||||||
|
|
||||||
|
import cn.qaiu.util.QuarkAccountScope;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -85,8 +87,18 @@ public class ShareLinkInfo {
|
|||||||
public String getCacheKey() {
|
public String getCacheKey() {
|
||||||
// 将type和shareKey组合成一个字符串作为缓存key
|
// 将type和shareKey组合成一个字符串作为缓存key
|
||||||
String key = type + ":" + shareKey;
|
String key = type + ":" + shareKey;
|
||||||
if (type.equals("p115")) {
|
if (type != null && type.equals("p115")) {
|
||||||
key += ("_" + otherParam.get("UA").toString().hashCode());
|
Object ua = otherParam != null ? otherParam.get("UA") : null;
|
||||||
|
if (ua != null) {
|
||||||
|
key += ("_" + ua.toString().hashCode());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 带账号的夸克 / UC 直链按账号隔离,避免会员链和 Cookie 进入分享级缓存。
|
||||||
|
if (type != null && ("qk".equalsIgnoreCase(type) || "uc".equalsIgnoreCase(type))) {
|
||||||
|
String scope = QuarkAccountScope.suffix(otherParam);
|
||||||
|
if (scope != null) {
|
||||||
|
key += "#" + scope;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return key;
|
return key;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
package cn.qaiu.parser;
|
||||||
|
|
||||||
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目录列表分页约定(解析器与 API 共用)。
|
||||||
|
* <p>
|
||||||
|
* 入参写在 {@link ShareLinkInfo#getOtherParam()}:
|
||||||
|
* <ul>
|
||||||
|
* <li>{@link #PAGE}:从 1 开始的页码;不传时解析器按原逻辑只取第一页</li>
|
||||||
|
* <li>{@link #CURSOR}:上一页返回的 {@code nextCursor},可选,只是加速,不可信</li>
|
||||||
|
* </ul>
|
||||||
|
* 解析器取完一页后写回 {@link #PAGE_INFO},见 {@link #pageInfo}。
|
||||||
|
* 没写 {@link #PAGE_INFO} 的解析器视为不分页,整份列表就是第 1 页。
|
||||||
|
*/
|
||||||
|
public final class FolderPaging {
|
||||||
|
|
||||||
|
public static final String PAGE = "page";
|
||||||
|
public static final String CURSOR = "pageCursor";
|
||||||
|
public static final String PAGE_INFO = "pageInfo";
|
||||||
|
|
||||||
|
/** 页码上限。蓝奏无游标时要从第 1 页顺序翻到目标页,必须有界。 */
|
||||||
|
public static final int MAX_PAGE = 500;
|
||||||
|
|
||||||
|
private static final Set<String> PAGED_TYPES = Set.of("lz", "fj", "iz");
|
||||||
|
|
||||||
|
private FolderPaging() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 该网盘的目录解析是否支持按页取。 */
|
||||||
|
public static boolean supports(String type) {
|
||||||
|
return type != null && PAGED_TYPES.contains(type.toLowerCase(Locale.ROOT));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析页码参数。空值返回 null(保持旧行为);非法值抛 IllegalArgumentException。
|
||||||
|
*/
|
||||||
|
public static Integer parsePage(String raw) {
|
||||||
|
if (raw == null || raw.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
int page;
|
||||||
|
try {
|
||||||
|
page = Integer.parseInt(raw.trim());
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
throw new IllegalArgumentException("page 必须是正整数: " + raw);
|
||||||
|
}
|
||||||
|
if (page < 1 || page > MAX_PAGE) {
|
||||||
|
throw new IllegalArgumentException("page 超出范围 1-" + MAX_PAGE + ": " + raw);
|
||||||
|
}
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 本次请求的页码;没传返回 null。 */
|
||||||
|
public static Integer requestedPage(ShareLinkInfo info) {
|
||||||
|
Object v = info.getOtherParam().get(PAGE);
|
||||||
|
if (v instanceof Number n) {
|
||||||
|
return n.intValue();
|
||||||
|
}
|
||||||
|
return v == null ? null : parsePage(v.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 本次请求的页码;没传按第 1 页。 */
|
||||||
|
public static int pageOrFirst(ShareLinkInfo info) {
|
||||||
|
Integer page = requestedPage(info);
|
||||||
|
return page == null ? 1 : page;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String cursor(ShareLinkInfo info) {
|
||||||
|
Object v = info.getOtherParam().get(CURSOR);
|
||||||
|
return v == null || v.toString().isBlank() ? null : v.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写回分页结果。
|
||||||
|
*
|
||||||
|
* @param pageSize 上游每页条数(原始条数口径,含被过滤的占位项)
|
||||||
|
* @param hasMore 上游明确还有下一页
|
||||||
|
* @param total 上游给出的总条数,未知传 null
|
||||||
|
* @param totalPage 上游给出的总页数,未知传 null
|
||||||
|
* @param nextCursor 取下一页可直接复用的游标,没有传 null
|
||||||
|
*/
|
||||||
|
public static JsonObject pageInfo(ShareLinkInfo info, int page, int pageSize, boolean hasMore,
|
||||||
|
Integer total, Integer totalPage, String nextCursor) {
|
||||||
|
JsonObject json = new JsonObject()
|
||||||
|
.put("paged", true)
|
||||||
|
.put("page", page)
|
||||||
|
.put("pageSize", pageSize)
|
||||||
|
.put("hasMore", hasMore)
|
||||||
|
.put("nextPage", hasMore ? page + 1 : null)
|
||||||
|
.put("total", total)
|
||||||
|
.put("totalPage", totalPage)
|
||||||
|
.put("nextCursor", hasMore ? nextCursor : null);
|
||||||
|
info.getOtherParam().put(PAGE_INFO, json);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上游给了总页数就以它为准;没给时整页满才认为可能还有。空页一律结束,避免无限翻页。
|
||||||
|
*/
|
||||||
|
public static boolean hasMore(int page, int rawCount, int pageSize, Integer totalPage) {
|
||||||
|
if (rawCount <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (totalPage != null && totalPage > 0) {
|
||||||
|
return page < totalPage;
|
||||||
|
}
|
||||||
|
return rawCount >= pageSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 小飞机 / 蓝奏优享 share/list 响应:offset 为页码,带 total / totalPage。 */
|
||||||
|
public static JsonObject offsetListPage(ShareLinkInfo info, JsonObject resp, int rawCount, int pageSize) {
|
||||||
|
int page = pageOrFirst(info);
|
||||||
|
Integer total = intOrNull(resp, "total");
|
||||||
|
Integer totalPage = intOrNull(resp, "totalPage");
|
||||||
|
return pageInfo(info, page, pageSize, hasMore(page, rawCount, pageSize, totalPage), total, totalPage, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Integer intOrNull(JsonObject json, String key) {
|
||||||
|
if (json == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Object v = json.getValue(key);
|
||||||
|
if (v instanceof Number n) {
|
||||||
|
return n.intValue();
|
||||||
|
}
|
||||||
|
if (v instanceof CharSequence s) {
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(s.toString().trim());
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static JsonObject pageInfo(ShareLinkInfo info) {
|
||||||
|
Object v = info.getOtherParam().get(PAGE_INFO);
|
||||||
|
return v instanceof JsonObject json ? json : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package cn.qaiu.parser;//package cn.qaiu.lz.common.parser;
|
package cn.qaiu.parser;//package cn.qaiu.lz.common.parser;
|
||||||
|
|
||||||
|
import cn.qaiu.WebClientVertxInit;
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.clientlink.ClientLinkGeneratorFactory;
|
import cn.qaiu.parser.clientlink.ClientLinkGeneratorFactory;
|
||||||
@@ -7,10 +8,26 @@ import cn.qaiu.parser.clientlink.ClientLinkType;
|
|||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
import io.vertx.core.Promise;
|
import io.vertx.core.Promise;
|
||||||
|
|
||||||
|
import java.util.function.Supplier;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.ScheduledFuture;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
public interface IPanTool {
|
public interface IPanTool extends AutoCloseable {
|
||||||
|
|
||||||
|
/** 同步等待超时时间(秒) */
|
||||||
|
long SYNC_TIMEOUT_SECONDS = 120;
|
||||||
|
|
||||||
|
ScheduledExecutorService CLOSE_AFTER_SCHEDULER = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||||
|
Thread t = new Thread(r, "pan-tool-close-after");
|
||||||
|
t.setDaemon(true);
|
||||||
|
return t;
|
||||||
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析文件
|
* 解析文件
|
||||||
@@ -18,8 +35,72 @@ public interface IPanTool {
|
|||||||
*/
|
*/
|
||||||
Future<String> parse();
|
Future<String> parse();
|
||||||
|
|
||||||
|
static <T> Future<T> closeAfter(IPanTool tool, Supplier<Future<T>> action) {
|
||||||
|
Promise<T> promise = Promise.promise();
|
||||||
|
AtomicBoolean cleanupDone = new AtomicBoolean(false);
|
||||||
|
ScheduledFuture<?> cleanupTask = null;
|
||||||
|
try {
|
||||||
|
Future<T> future = action.get();
|
||||||
|
if (future == null) {
|
||||||
|
closeQuietly(tool);
|
||||||
|
return Future.failedFuture("解析器返回空 Future");
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanupTask = CLOSE_AFTER_SCHEDULER.schedule(() -> {
|
||||||
|
if (cleanupDone.compareAndSet(false, true)) {
|
||||||
|
closeQuietly(tool);
|
||||||
|
failOnVertxContext(promise, "解析超时(" + SYNC_TIMEOUT_SECONDS + "秒)");
|
||||||
|
}
|
||||||
|
}, SYNC_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
ScheduledFuture<?> scheduledCleanupTask = cleanupTask;
|
||||||
|
future.onComplete(ar -> {
|
||||||
|
scheduledCleanupTask.cancel(false);
|
||||||
|
if (!cleanupDone.compareAndSet(false, true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
closeQuietly(tool);
|
||||||
|
if (ar.succeeded()) {
|
||||||
|
promise.tryComplete(ar.result());
|
||||||
|
} else {
|
||||||
|
promise.tryFail(ar.cause());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return promise.future();
|
||||||
|
} catch (Throwable t) {
|
||||||
|
if (cleanupTask != null) {
|
||||||
|
cleanupTask.cancel(false);
|
||||||
|
}
|
||||||
|
closeQuietly(tool);
|
||||||
|
return Future.failedFuture(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static <T> void failOnVertxContext(Promise<T> promise, String message) {
|
||||||
|
try {
|
||||||
|
WebClientVertxInit.get().runOnContext(ignored -> promise.tryFail(message));
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
promise.tryFail(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void closeQuietly(IPanTool tool) {
|
||||||
|
if (tool == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
tool.close();
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// ignore cleanup failures
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void shutdownCloseAfterScheduler() {
|
||||||
|
CLOSE_AFTER_SCHEDULER.shutdownNow();
|
||||||
|
}
|
||||||
|
|
||||||
default String parseSync() {
|
default String parseSync() {
|
||||||
return parse().toCompletionStage().toCompletableFuture().join();
|
return timedJoin(parse());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -33,7 +114,7 @@ public interface IPanTool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
default List<FileInfo> parseFileListSync() {
|
default List<FileInfo> parseFileListSync() {
|
||||||
return parseFileList().toCompletionStage().toCompletableFuture().join();
|
return timedJoin(parseFileList());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -47,7 +128,7 @@ public interface IPanTool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
default String parseByIdSync() {
|
default String parseByIdSync() {
|
||||||
return parseById().toCompletionStage().toCompletableFuture().join();
|
return timedJoin(parseById());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -126,7 +207,7 @@ public interface IPanTool {
|
|||||||
* @return Map<ClientLinkType, String> 客户端下载链接集合
|
* @return Map<ClientLinkType, String> 客户端下载链接集合
|
||||||
*/
|
*/
|
||||||
default Map<ClientLinkType, String> parseWithClientLinksSync() {
|
default Map<ClientLinkType, String> parseWithClientLinksSync() {
|
||||||
return parseWithClientLinks().toCompletionStage().toCompletableFuture().join();
|
return timedJoin(parseWithClientLinks());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -137,4 +218,26 @@ public interface IPanTool {
|
|||||||
default ShareLinkInfo getShareLinkInfo() {
|
default ShareLinkInfo getShareLinkInfo() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
default void close() {
|
||||||
|
// default no-op
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 带超时的同步等待工具方法,替代无超时的 join()
|
||||||
|
*/
|
||||||
|
private static <T> T timedJoin(Future<T> future) {
|
||||||
|
try {
|
||||||
|
return future.toCompletionStage().toCompletableFuture()
|
||||||
|
.get(SYNC_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new RuntimeException("线程被中断", e);
|
||||||
|
} catch (TimeoutException e) {
|
||||||
|
throw new RuntimeException("同步等待超时(" + SYNC_TIMEOUT_SECONDS + "秒)", e);
|
||||||
|
} catch (java.util.concurrent.ExecutionException e) {
|
||||||
|
throw new RuntimeException(e.getCause() != null ? e.getCause() : e);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -20,6 +20,9 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@@ -34,36 +37,65 @@ import java.util.zip.GZIPInputStream;
|
|||||||
* <p>{网盘标识}Tool, 网盘标识不超过5个字符, 可以取网盘名称首字母缩写或拼音首字母, <br>
|
* <p>{网盘标识}Tool, 网盘标识不超过5个字符, 可以取网盘名称首字母缩写或拼音首字母, <br>
|
||||||
* 音乐类型的解析以M开头, 例如网易云音乐Mne</p>
|
* 音乐类型的解析以M开头, 例如网易云音乐Mne</p>
|
||||||
*/
|
*/
|
||||||
public abstract class PanBase implements IPanTool {
|
public abstract class PanBase implements IPanTool, Closeable {
|
||||||
protected Logger log = LoggerFactory.getLogger(this.getClass());
|
protected Logger log = LoggerFactory.getLogger(this.getClass());
|
||||||
|
|
||||||
protected Promise<String> promise = Promise.promise();
|
protected Promise<String> promise = Promise.promise();
|
||||||
|
|
||||||
/**
|
private static final int MAX_COMPRESSED_RESPONSE_BYTES = 8 * 1024 * 1024;
|
||||||
* Http client
|
private static final int MAX_DECOMPRESSED_RESPONSE_CHARS = 16 * 1024 * 1024;
|
||||||
*/
|
private static final int MAX_ERROR_BODY_CHARS = 4096;
|
||||||
protected WebClient client = WebClient.create(WebClientVertxInit.get(),
|
|
||||||
new WebClientOptions());
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Http client session (会话管理, 带cookie请求)
|
* 共享的 WebClient 配置(设置超时避免连接无限期占用)
|
||||||
|
*/
|
||||||
|
private static final WebClientOptions SHARED_OPTIONS = new WebClientOptions()
|
||||||
|
.setConnectTimeout(10000) // 连接超时 10 秒
|
||||||
|
.setIdleTimeout(30) // 空闲超时 30 秒
|
||||||
|
.setIdleTimeoutUnit(java.util.concurrent.TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
private static final Object SHARED_CLIENT_LOCK = new Object();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 共享的 WebClient 实例(线程安全,避免每请求创建导致资源泄漏)
|
||||||
|
*/
|
||||||
|
private static volatile WebClient sharedClient;
|
||||||
|
private static volatile WebClient sharedClientNoRedirects;
|
||||||
|
private static volatile WebClient sharedClientDisableUA;
|
||||||
|
private static volatile boolean sharedClientsShutdown = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Http client (默认使用共享实例,代理模式下使用独立实例)
|
||||||
|
*/
|
||||||
|
protected WebClient client = sharedClient();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Http client session (会话管理, 带cookie请求, 每实例独立)
|
||||||
*/
|
*/
|
||||||
protected WebClientSession clientSession = WebClientSession.create(client);
|
protected WebClientSession clientSession = WebClientSession.create(client);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Http client 不自动跳转
|
* Http client 不自动跳转
|
||||||
*/
|
*/
|
||||||
protected WebClient clientNoRedirects = WebClient.create(WebClientVertxInit.get(),
|
protected WebClient clientNoRedirects = sharedClientNoRedirects();
|
||||||
new WebClientOptions().setFollowRedirects(false));
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Http client disable UserAgent
|
* Http client disable UserAgent
|
||||||
*/
|
*/
|
||||||
protected WebClient clientDisableUA = WebClient.create(WebClientVertxInit.get()
|
protected WebClient clientDisableUA = sharedClientDisableUA();
|
||||||
, new WebClientOptions().setUserAgentEnabled(false)
|
|
||||||
);
|
|
||||||
|
|
||||||
protected ShareLinkInfo shareLinkInfo;
|
protected ShareLinkInfo shareLinkInfo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 标记是否为代理模式(代理模式创建的 WebClient 需要手动关闭)
|
||||||
|
*/
|
||||||
|
private boolean isProxyMode = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 代理模式下创建的独立 WebClient 实例(需要在 close 时释放)
|
||||||
|
*/
|
||||||
|
private WebClient proxyClient = null;
|
||||||
|
private WebClient proxyClientNoRedirects = null;
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -80,6 +112,7 @@ public abstract class PanBase implements IPanTool {
|
|||||||
public PanBase(ShareLinkInfo shareLinkInfo) {
|
public PanBase(ShareLinkInfo shareLinkInfo) {
|
||||||
this.shareLinkInfo = shareLinkInfo;
|
this.shareLinkInfo = shareLinkInfo;
|
||||||
if (shareLinkInfo.getOtherParam().containsKey("proxy")) {
|
if (shareLinkInfo.getOtherParam().containsKey("proxy")) {
|
||||||
|
this.isProxyMode = true;
|
||||||
JsonObject proxy = (JsonObject) shareLinkInfo.getOtherParam().get("proxy");
|
JsonObject proxy = (JsonObject) shareLinkInfo.getOtherParam().get("proxy");
|
||||||
ProxyOptions proxyOptions = new ProxyOptions()
|
ProxyOptions proxyOptions = new ProxyOptions()
|
||||||
.setType(ProxyType.valueOf(proxy.getString("type").toUpperCase()))
|
.setType(ProxyType.valueOf(proxy.getString("type").toUpperCase()))
|
||||||
@@ -91,22 +124,156 @@ public abstract class PanBase implements IPanTool {
|
|||||||
if (StringUtils.isNotEmpty(proxy.getString("password"))) {
|
if (StringUtils.isNotEmpty(proxy.getString("password"))) {
|
||||||
proxyOptions.setPassword(proxy.getString("password"));
|
proxyOptions.setPassword(proxy.getString("password"));
|
||||||
}
|
}
|
||||||
this.client = WebClient.create(WebClientVertxInit.get(),
|
// 代理模式下创建独立的 WebClient 实例(应用超时配置)
|
||||||
new WebClientOptions()
|
this.proxyClient = WebClient.create(WebClientVertxInit.get(),
|
||||||
|
new WebClientOptions(SHARED_OPTIONS)
|
||||||
|
.setUserAgentEnabled(false)
|
||||||
|
.setProxyOptions(proxyOptions));
|
||||||
|
this.proxyClientNoRedirects = WebClient.create(WebClientVertxInit.get(),
|
||||||
|
new WebClientOptions(SHARED_OPTIONS).setFollowRedirects(false)
|
||||||
.setUserAgentEnabled(false)
|
.setUserAgentEnabled(false)
|
||||||
.setProxyOptions(proxyOptions));
|
.setProxyOptions(proxyOptions));
|
||||||
|
|
||||||
|
this.client = proxyClient;
|
||||||
this.clientSession = WebClientSession.create(client);
|
this.clientSession = WebClientSession.create(client);
|
||||||
this.clientNoRedirects = WebClient.create(WebClientVertxInit.get(),
|
this.clientNoRedirects = proxyClientNoRedirects;
|
||||||
new WebClientOptions().setFollowRedirects(false)
|
|
||||||
.setUserAgentEnabled(false)
|
|
||||||
.setProxyOptions(proxyOptions));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected PanBase() {
|
protected PanBase() {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static WebClient sharedClient() {
|
||||||
|
synchronized (SHARED_CLIENT_LOCK) {
|
||||||
|
if (sharedClientsShutdown) {
|
||||||
|
throw new IllegalStateException("共享 WebClient 已关闭");
|
||||||
|
}
|
||||||
|
if (sharedClient == null) {
|
||||||
|
sharedClient = WebClient.create(WebClientVertxInit.get(), new WebClientOptions(SHARED_OPTIONS));
|
||||||
|
}
|
||||||
|
return sharedClient;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WebClient sharedClientNoRedirects() {
|
||||||
|
synchronized (SHARED_CLIENT_LOCK) {
|
||||||
|
if (sharedClientsShutdown) {
|
||||||
|
throw new IllegalStateException("共享 WebClient 已关闭");
|
||||||
|
}
|
||||||
|
if (sharedClientNoRedirects == null) {
|
||||||
|
sharedClientNoRedirects = WebClient.create(WebClientVertxInit.get(),
|
||||||
|
new WebClientOptions(SHARED_OPTIONS).setFollowRedirects(false));
|
||||||
|
}
|
||||||
|
return sharedClientNoRedirects;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WebClient sharedClientDisableUA() {
|
||||||
|
synchronized (SHARED_CLIENT_LOCK) {
|
||||||
|
if (sharedClientsShutdown) {
|
||||||
|
throw new IllegalStateException("共享 WebClient 已关闭");
|
||||||
|
}
|
||||||
|
if (sharedClientDisableUA == null) {
|
||||||
|
sharedClientDisableUA = WebClient.create(WebClientVertxInit.get(),
|
||||||
|
new WebClientOptions(SHARED_OPTIONS).setUserAgentEnabled(false));
|
||||||
|
}
|
||||||
|
return sharedClientDisableUA;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void shutdownSharedClients() {
|
||||||
|
synchronized (SHARED_CLIENT_LOCK) {
|
||||||
|
sharedClientsShutdown = true;
|
||||||
|
closeSharedClient(sharedClient, "shared WebClient");
|
||||||
|
closeSharedClient(sharedClientNoRedirects, "shared WebClientNoRedirects");
|
||||||
|
closeSharedClient(sharedClientDisableUA, "shared WebClientDisableUA");
|
||||||
|
sharedClient = null;
|
||||||
|
sharedClientNoRedirects = null;
|
||||||
|
sharedClientDisableUA = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void closeSharedClient(WebClient client, String name) {
|
||||||
|
if (client == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
client.close();
|
||||||
|
} catch (Exception e) {
|
||||||
|
LoggerFactory.getLogger(PanBase.class).warn("关闭 {} 失败: {}", name, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SSRF 防护: 校验通用自定义域名解析器 (CE/Ce4/Kd/Other 等) 即将请求的目标主机,
|
||||||
|
* 拒绝解析到回环/内网/链路本地/组播等非公网地址的域名, 阻止攻击者通过可控 DNS
|
||||||
|
* 记录 (或直接填写内网域名) 让服务端向内网/云元数据接口发起请求。
|
||||||
|
* <p>
|
||||||
|
* 必须在子类 parse() 中构造出 baseUrl/发起任何 clientSession 请求之前调用。
|
||||||
|
*
|
||||||
|
* @param url 从 shareLinkInfo.getShareUrl() 解析出的 URL
|
||||||
|
* @throws IOException 当主机无法解析或解析结果落入禁止的地址段时抛出
|
||||||
|
*/
|
||||||
|
protected static void assertPublicHost(URL url) throws IOException {
|
||||||
|
String host = url.getHost();
|
||||||
|
InetAddress[] addresses;
|
||||||
|
try {
|
||||||
|
addresses = InetAddress.getAllByName(host);
|
||||||
|
} catch (UnknownHostException e) {
|
||||||
|
throw new IOException("无法解析目标主机: " + host, e);
|
||||||
|
}
|
||||||
|
if (addresses.length == 0) {
|
||||||
|
throw new IOException("无法解析目标主机: " + host);
|
||||||
|
}
|
||||||
|
for (InetAddress addr : addresses) {
|
||||||
|
if (isDisallowedAddress(addr)) {
|
||||||
|
throw new IOException("目标地址不允许访问(内网/回环/链路本地/组播): "
|
||||||
|
+ host + " -> " + addr.getHostAddress());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断地址是否落入禁止访问的范围: 0.0.0.0/8, 10/8, 127/8, 169.254/16(含云元数据
|
||||||
|
* 169.254.169.254), 172.16/12, 192.168/16, 100.64/10(CGNAT), 224/4~255/4(组播/保留),
|
||||||
|
* 以及对应的 IPv6 回环/链路本地/唯一本地地址(fc00::/7)/组播地址; IPv4-映射的 IPv6
|
||||||
|
* 地址(::ffff:a.b.c.d) 会先还原为 IPv4 再判断,避免绕过。
|
||||||
|
*/
|
||||||
|
private static boolean isDisallowedAddress(InetAddress addr) {
|
||||||
|
byte[] bytes = addr.getAddress();
|
||||||
|
if (bytes.length == 16 && isIPv4Mapped(bytes)) {
|
||||||
|
byte[] v4 = new byte[4];
|
||||||
|
System.arraycopy(bytes, 12, v4, 0, 4);
|
||||||
|
bytes = v4;
|
||||||
|
}
|
||||||
|
if (bytes.length == 4) {
|
||||||
|
int b0 = bytes[0] & 0xFF;
|
||||||
|
int b1 = bytes[1] & 0xFF;
|
||||||
|
if (b0 == 0) return true; // 0.0.0.0/8
|
||||||
|
if (b0 == 10) return true; // 10.0.0.0/8
|
||||||
|
if (b0 == 127) return true; // 127.0.0.0/8 loopback
|
||||||
|
if (b0 == 169 && b1 == 254) return true; // 169.254.0.0/16 (含云元数据 169.254.169.254)
|
||||||
|
if (b0 == 172 && b1 >= 16 && b1 <= 31) return true; // 172.16.0.0/12
|
||||||
|
if (b0 == 192 && b1 == 168) return true; // 192.168.0.0/16
|
||||||
|
if (b0 == 100 && b1 >= 64 && b1 <= 127) return true;// 100.64.0.0/10 CGNAT
|
||||||
|
return b0 >= 224; // 224.0.0.0/4 组播 + 240.0.0.0/4 保留
|
||||||
|
}
|
||||||
|
// IPv6
|
||||||
|
if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()
|
||||||
|
|| addr.isLinkLocalAddress() || addr.isSiteLocalAddress()
|
||||||
|
|| addr.isMulticastAddress()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return bytes.length == 16 && (bytes[0] & 0xFE) == 0xFC; // fc00::/7 unique local
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isIPv4Mapped(byte[] b) {
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
if (b[i] != 0) return false;
|
||||||
|
}
|
||||||
|
return (b[10] & 0xFF) == 0xFF && (b[11] & 0xFF) == 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
protected String baseMsg() {
|
protected String baseMsg() {
|
||||||
if (shareLinkInfo.getShareUrl() != null) {
|
if (shareLinkInfo.getShareUrl() != null) {
|
||||||
return shareLinkInfo.getPanName() + "-" + shareLinkInfo.getType() + ": url=" + shareLinkInfo.getShareUrl();
|
return shareLinkInfo.getPanName() + "-" + shareLinkInfo.getType() + ": url=" + shareLinkInfo.getShareUrl();
|
||||||
@@ -131,16 +298,19 @@ public abstract class PanBase implements IPanTool {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String s = String.format(errorMsg.replaceAll("\\{}", "%s"), args);
|
String s = String.format(errorMsg.replaceAll("\\{}", "%s"), args);
|
||||||
log.error("解析异常: " + s, t.fillInStackTrace());
|
// 只记录异常消息和类型,不调用 fillInStackTrace 避免产生巨大栈信息
|
||||||
promise.fail(baseMsg() + ": 解析异常: " + s + " -> " + t);
|
log.error("解析异常: {} - {}: {}", s, t.getClass().getSimpleName(), t.getMessage());
|
||||||
|
// 只传递异常消息,不传递完整异常对象,减少内存占用
|
||||||
|
String failMsg = baseMsg() + ": 解析异常: " + s + " -> " + t.getClass().getSimpleName() + ": " + t.getMessage();
|
||||||
|
promise.fail(failMsg);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("ErrorMsg format fail. The parameter has been discarded", e);
|
log.error("ErrorMsg format fail. The parameter has been discarded", e);
|
||||||
log.error("解析异常: " + errorMsg, t.fillInStackTrace());
|
log.error("解析异常: {} - {}: {}", errorMsg, t.getClass().getSimpleName(), t.getMessage());
|
||||||
if (promise.future().isComplete()) {
|
if (promise.future().isComplete()) {
|
||||||
log.warn("ErrorMsg format. Promise 已经完成, 无法再次失败: {}", errorMsg);
|
log.warn("ErrorMsg format. Promise 已经完成, 无法再次失败: {}", errorMsg);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
promise.fail(baseMsg() + ": 解析异常: " + errorMsg + " -> " + t);
|
promise.fail(baseMsg() + ": 解析异常: " + errorMsg + " -> " + t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,7 +350,7 @@ public abstract class PanBase implements IPanTool {
|
|||||||
* @return Handler
|
* @return Handler
|
||||||
*/
|
*/
|
||||||
protected Handler<Throwable> handleFail(String errorMsg) {
|
protected Handler<Throwable> handleFail(String errorMsg) {
|
||||||
return t -> fail(baseMsg() + " - 请求异常 {}: -> {}", errorMsg, t.fillInStackTrace());
|
return t -> fail(baseMsg() + " - 请求异常 {}: -> {}", errorMsg, t.getClass().getSimpleName() + ": " + t.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
protected Handler<Throwable> handleFail() {
|
protected Handler<Throwable> handleFail() {
|
||||||
@@ -198,29 +368,27 @@ public abstract class PanBase implements IPanTool {
|
|||||||
// 检查响应头中的Content-Encoding是否为gzip
|
// 检查响应头中的Content-Encoding是否为gzip
|
||||||
String contentEncoding = res.getHeader("Content-Encoding");
|
String contentEncoding = res.getHeader("Content-Encoding");
|
||||||
try {
|
try {
|
||||||
if ("gzip".equalsIgnoreCase(contentEncoding)) {
|
if ("gzip".equalsIgnoreCase(contentEncoding) && res.body() instanceof Buffer gzipBody
|
||||||
// 如果是gzip压缩的响应体,解压
|
&& gzipBody.length() >= 2
|
||||||
return new JsonObject(decompressGzip((Buffer) res.body()));
|
&& (gzipBody.getByte(0) & 0xff) == 0x1f
|
||||||
|
&& (gzipBody.getByte(1) & 0xff) == 0x8b) {
|
||||||
|
// 如果是gzip压缩的响应体,解压(只解压一次,缓存结果)
|
||||||
|
String decompressed = decompressGzip(gzipBody);
|
||||||
|
return new JsonObject(decompressed);
|
||||||
} else {
|
} else {
|
||||||
return res.bodyAsJsonObject();
|
return res.bodyAsJsonObject();
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
if ("gzip".equalsIgnoreCase(contentEncoding)) {
|
if ("gzip".equalsIgnoreCase(contentEncoding)) {
|
||||||
// 如果是gzip压缩的响应体,解压
|
// gzip解压失败,记录错误
|
||||||
try {
|
log.error("响应gzip解压或JSON解析失败: {}", e.getMessage());
|
||||||
log.error(decompressGzip((Buffer) res.body()));
|
fail("响应gzip解压或JSON解析失败: {}", e.getMessage());
|
||||||
fail(decompressGzip((Buffer) res.body()));
|
|
||||||
//throw new RuntimeException("响应不是JSON格式");
|
|
||||||
} catch (IOException ex) {
|
|
||||||
log.error("响应gzip解压失败");
|
|
||||||
fail("响应gzip解压失败: {}", ex.getMessage());
|
|
||||||
//throw new RuntimeException("响应gzip解压失败", ex);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
log.error("解析失败: json格式异常: {}", res.bodyAsString());
|
// 上游响应体可能来自内网探测目标,仅写日志,避免经 HTTP 500 回传给调用方
|
||||||
fail("解析失败: json格式异常: {}", res.bodyAsString());
|
String bodyPreview = responseBodyPreview(res);
|
||||||
//throw new RuntimeException("解析失败: json格式异常");
|
log.error("解析失败: json格式异常: {}", bodyPreview);
|
||||||
|
fail("解析失败: json格式异常");
|
||||||
}
|
}
|
||||||
return JsonObject.of();
|
return JsonObject.of();
|
||||||
}
|
}
|
||||||
@@ -250,7 +418,18 @@ public abstract class PanBase implements IPanTool {
|
|||||||
protected void completeWithMeta(String url, Map<String, String> headers) {
|
protected void completeWithMeta(String url, Map<String, String> headers) {
|
||||||
shareLinkInfo.getOtherParam().put("downloadUrl", url);
|
shareLinkInfo.getOtherParam().put("downloadUrl", url);
|
||||||
if (headers != null && !headers.isEmpty()) {
|
if (headers != null && !headers.isEmpty()) {
|
||||||
shareLinkInfo.getOtherParam().put("downloadHeaders", headers);
|
// 过滤 null/空值,避免 cookie:null 覆盖入口参数或污染 curl 命令
|
||||||
|
Map<String, String> clean = new HashMap<>();
|
||||||
|
headers.forEach((k, v) -> {
|
||||||
|
if (k != null && v != null && !v.isBlank()) {
|
||||||
|
clean.put(k, v);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (!clean.isEmpty()) {
|
||||||
|
shareLinkInfo.getOtherParam().put("downloadHeaders", clean);
|
||||||
|
// UC/夸克等需带 cookie 的直链,标记前端走下载器
|
||||||
|
shareLinkInfo.getOtherParam().put("needDownloader", true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
promise.complete(url);
|
promise.complete(url);
|
||||||
}
|
}
|
||||||
@@ -283,11 +462,15 @@ public abstract class PanBase implements IPanTool {
|
|||||||
if (iterator.hasNext()) {
|
if (iterator.hasNext()) {
|
||||||
PanDomainTemplate next = iterator.next();
|
PanDomainTemplate next = iterator.next();
|
||||||
log.debug("规则不匹配, 处理解析器转发: {} -> {}", shareLinkInfo.getPanName(), next.getDisplayName());
|
log.debug("规则不匹配, 处理解析器转发: {} -> {}", shareLinkInfo.getPanName(), next.getDisplayName());
|
||||||
ParserCreate.fromType(next.name())
|
try {
|
||||||
.fromAnyShareUrl(shareLinkInfo.getShareUrl())
|
IPanTool nextTool = ParserCreate.fromType(next.name())
|
||||||
.createTool()
|
.fromAnyShareUrl(shareLinkInfo.getShareUrl())
|
||||||
.parse()
|
.createTool();
|
||||||
.onComplete(promise);
|
IPanTool.closeAfter(nextTool, nextTool::parse)
|
||||||
|
.onComplete(promise);
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail(e, "转发到下一个解析器失败: {}", next.getDisplayName());
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
fail("error: 没有下一个解析处理器");
|
fail("error: 没有下一个解析处理器");
|
||||||
}
|
}
|
||||||
@@ -303,6 +486,12 @@ public abstract class PanBase implements IPanTool {
|
|||||||
* @throws IOException IOException
|
* @throws IOException IOException
|
||||||
*/
|
*/
|
||||||
private String decompressGzip(Buffer compressedData) throws IOException {
|
private String decompressGzip(Buffer compressedData) throws IOException {
|
||||||
|
if (compressedData == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (compressedData.length() > MAX_COMPRESSED_RESPONSE_BYTES) {
|
||||||
|
throw new IOException("gzip响应体过大: " + compressedData.length() + " bytes");
|
||||||
|
}
|
||||||
try (ByteArrayInputStream bais = new ByteArrayInputStream(compressedData.getBytes());
|
try (ByteArrayInputStream bais = new ByteArrayInputStream(compressedData.getBytes());
|
||||||
GZIPInputStream gzis = new GZIPInputStream(bais);
|
GZIPInputStream gzis = new GZIPInputStream(bais);
|
||||||
InputStreamReader isr = new InputStreamReader(gzis, StandardCharsets.UTF_8);
|
InputStreamReader isr = new InputStreamReader(gzis, StandardCharsets.UTF_8);
|
||||||
@@ -311,18 +500,97 @@ public abstract class PanBase implements IPanTool {
|
|||||||
char[] buffer = new char[4096];
|
char[] buffer = new char[4096];
|
||||||
int n;
|
int n;
|
||||||
while ((n = isr.read(buffer)) != -1) {
|
while ((n = isr.read(buffer)) != -1) {
|
||||||
writer.write(buffer, 0, n);
|
writeLimited(writer, buffer, n);
|
||||||
}
|
}
|
||||||
return writer.toString();
|
return writer.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void writeLimited(StringWriter writer, char[] buffer, int len) throws IOException {
|
||||||
|
if (writer.getBuffer().length() + len > MAX_DECOMPRESSED_RESPONSE_CHARS) {
|
||||||
|
throw new IOException("gzip解压后响应体过大");
|
||||||
|
}
|
||||||
|
writer.write(buffer, 0, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String responseBodyPreview(HttpResponse<?> res) {
|
||||||
|
if (res == null || res.body() == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (res.body() instanceof Buffer body) {
|
||||||
|
int length = Math.min(body.length(), MAX_ERROR_BODY_CHARS);
|
||||||
|
String preview = new String(body.getBytes(0, length), StandardCharsets.UTF_8);
|
||||||
|
return body.length() > length ? preview + "...(truncated " + body.length() + " bytes)" : preview;
|
||||||
|
}
|
||||||
|
String text = res.bodyAsString();
|
||||||
|
if (text == null || text.length() <= MAX_ERROR_BODY_CHARS) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
return text.substring(0, MAX_ERROR_BODY_CHARS) + "...(truncated " + text.length() + " chars)";
|
||||||
|
} catch (Exception e) {
|
||||||
|
return "<body preview failed: " + e.getMessage() + ">";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
protected String getDomainName(){
|
protected String getDomainName(){
|
||||||
return shareLinkInfo.getOtherParam().getOrDefault("domainName", "").toString();
|
return shareLinkInfo.getOtherParam().getOrDefault("domainName", "").toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将入口请求中的加密 auth 透传到子目录/下载链接,避免进入子目录后丢失认证。
|
||||||
|
* otherParam 中的 key 为 {@code _authQuery}(由 web 层写入)。
|
||||||
|
*/
|
||||||
|
protected String appendAuthQuery(String url) {
|
||||||
|
if (StringUtils.isBlank(url) || shareLinkInfo == null || shareLinkInfo.getOtherParam() == null) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
Object authObj = shareLinkInfo.getOtherParam().get("_authQuery");
|
||||||
|
if (authObj == null) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
String auth = authObj.toString();
|
||||||
|
if (StringUtils.isBlank(auth)) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
// 已带 auth 则不再追加
|
||||||
|
if (url.contains("auth=")) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
String encoded = java.net.URLEncoder.encode(auth, StandardCharsets.UTF_8);
|
||||||
|
return url + (url.contains("?") ? "&" : "?") + "auth=" + encoded;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return url + (url.contains("?") ? "&" : "?") + "auth=" + auth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ShareLinkInfo getShareLinkInfo() {
|
public ShareLinkInfo getShareLinkInfo() {
|
||||||
return shareLinkInfo;
|
return shareLinkInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭代理模式下创建的 WebClient 资源
|
||||||
|
* 非代理模式使用共享实例,不需要关闭
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
if (isProxyMode) {
|
||||||
|
try {
|
||||||
|
if (proxyClient != null) {
|
||||||
|
proxyClient.close();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("关闭代理 WebClient 失败: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (proxyClientNoRedirects != null) {
|
||||||
|
proxyClientNoRedirects.close();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("关闭代理 WebClientNoRedirects 失败: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -121,9 +121,9 @@ public enum PanDomainTemplate {
|
|||||||
"https://lecloud.lenovo.com/share/{shareKey}",
|
"https://lecloud.lenovo.com/share/{shareKey}",
|
||||||
LeTool.class),
|
LeTool.class),
|
||||||
|
|
||||||
// https://v2.fangcloud.com/s/
|
// https://v2.fangcloud.com/s/ https://v2.fangcloud.cn/h5/share/ (移动端H5落地页)
|
||||||
FC("亿方云",
|
FC("亿方云",
|
||||||
compile("https://v2\\.fangcloud\\.(com|cn)/(s|share|sharing)/(?<KEY>.+)"),
|
compile("https://v2\\.fangcloud\\.(com|cn)/(?:h5/)?(s|share|sharing)/(?<KEY>.+)"),
|
||||||
"https://v2.fangcloud.com/s/{shareKey}",
|
"https://v2.fangcloud.com/s/{shareKey}",
|
||||||
"https://www.fangcloud.com/",
|
"https://www.fangcloud.com/",
|
||||||
FcTool.class),
|
FcTool.class),
|
||||||
@@ -208,7 +208,7 @@ public enum PanDomainTemplate {
|
|||||||
123795.com
|
123795.com
|
||||||
*/
|
*/
|
||||||
YE("123网盘",
|
YE("123网盘",
|
||||||
compile("https://www\\.(" +
|
compile("https://(?:[a-zA-Z\\d-]+\\.)*(" +
|
||||||
"123254\\.com|" +
|
"123254\\.com|" +
|
||||||
"123957\\.com|" +
|
"123957\\.com|" +
|
||||||
"123295\\.com|" +
|
"123295\\.com|" +
|
||||||
@@ -232,7 +232,7 @@ public enum PanDomainTemplate {
|
|||||||
"123635\\.com|" +
|
"123635\\.com|" +
|
||||||
"123242\\.com|" +
|
"123242\\.com|" +
|
||||||
"123795\\.com" +
|
"123795\\.com" +
|
||||||
")/s/(?<KEY>[a-zA-Z0-9_-]+)(?:\\.html)?"),
|
")/(?:(?:s|123pan)/|(?:[^/?#]+/)+)?(?<KEY>[a-zA-Z0-9]+-[a-zA-Z0-9]+|[a-zA-Z0-9_-]+)(?:\\.html)?(?:[?#].*)?"),
|
||||||
"https://www.123pan.com/s/{shareKey}",
|
"https://www.123pan.com/s/{shareKey}",
|
||||||
Ye2Tool.class),
|
Ye2Tool.class),
|
||||||
// https://www.ecpan.cn/web/#/yunpanProxy?path=%2F%23%2Fdrive%2Foutside&data={code}&isShare=1
|
// https://www.ecpan.cn/web/#/yunpanProxy?path=%2F%23%2Fdrive%2Foutside&data={code}&isShare=1
|
||||||
@@ -247,9 +247,15 @@ public enum PanDomainTemplate {
|
|||||||
"https://cowtransfer.com/s/{shareKey}",
|
"https://cowtransfer.com/s/{shareKey}",
|
||||||
CowTool.class),
|
CowTool.class),
|
||||||
CT("城通网盘",
|
CT("城通网盘",
|
||||||
compile("https://(?:[a-zA-Z\\d-]+\\.)?(ctfile|545c|u062|ghpym|474b)\\.com/f(ile)?/" +
|
compile("https?://(?:[a-zA-Z\\d-]+\\.)?(ctfile|545c|u062|ghpym|474b)\\.com/f(ile)?/" +
|
||||||
"(?<KEY>[0-9a-zA-Z_-]+)(\\?p=(?<PWD>\\w+))?"),
|
"(?<KEY>[0-9a-zA-Z_-]+)/?(?:\\?(?:(?:[^#&]*&)*p=(?<PWD>\\w+)(?:&[^#]*)?|[^#]*))?"),
|
||||||
"https://474b.com/file/{shareKey}",
|
"https://ctfile.com/file/{shareKey}",
|
||||||
|
CtTool.class),
|
||||||
|
// https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609&d=164803691&fk=decb36
|
||||||
|
CTD("城通网盘-目录",
|
||||||
|
compile("https?://(?:[a-zA-Z\\d-]+\\.)?(ctfile|545c|u062|ghpym|474b)\\.com/d/" +
|
||||||
|
"(?<KEY>[0-9a-zA-Z_-]+)/?(?:\\?(?:(?:[^#&]*&)*p=(?<PWD>\\w+)(?:&[^#]*)?|[^#]*))?"),
|
||||||
|
"https://ctfile.com/d/{shareKey}",
|
||||||
CtTool.class),
|
CtTool.class),
|
||||||
// https://www.vyuyun.com/s/QMa6ie?password=I4KG7H
|
// https://www.vyuyun.com/s/QMa6ie?password=I4KG7H
|
||||||
// https://www.vyuyun.com/s/QMa6ie/file?password=I4KG7H
|
// https://www.vyuyun.com/s/QMa6ie/file?password=I4KG7H
|
||||||
@@ -371,6 +377,16 @@ public enum PanDomainTemplate {
|
|||||||
MmgTool.class),
|
MmgTool.class),
|
||||||
// =====================私有盘解析==========================
|
// =====================私有盘解析==========================
|
||||||
|
|
||||||
|
// 永硕E盘空间分享:https://qaiu.ysepan.com/ (空间名即 shareKey,密码为空间访问密码)
|
||||||
|
// 主域名 ysepan.com / ys168.com;备用 cccpan.com / ysupan.com / uupan.net / ysok.net
|
||||||
|
YS("永硕E盘",
|
||||||
|
compile("https?://(?!(?:www|zy|ht|api|c\\d+|ys-[a-zA-Z0-9]+)\\.)(?<KEY>[a-zA-Z\\d-]+)\\."
|
||||||
|
+ "(?:ysepan\\.com|ys168\\.com|cccpan\\.com|ysupan\\.com|uupan\\.net|ysok\\.net)"
|
||||||
|
+ "/?(?:\\?.*)?"),
|
||||||
|
"https://{shareKey}.ysepan.com/",
|
||||||
|
"https://www.ysepan.com/",
|
||||||
|
YsTool.class),
|
||||||
|
|
||||||
// Cloudreve自定义域名解析, 解析器CeTool兜底策略, 即任意域名如果匹配不到对应的规则, 则由CeTool统一处理,
|
// Cloudreve自定义域名解析, 解析器CeTool兜底策略, 即任意域名如果匹配不到对应的规则, 则由CeTool统一处理,
|
||||||
// 如果不属于Cloudreve盘 则调用下一个自定义域名解析器, 若都处理不了则抛出异常, 这种匹配模式类似责任链
|
// 如果不属于Cloudreve盘 则调用下一个自定义域名解析器, 若都处理不了则抛出异常, 这种匹配模式类似责任链
|
||||||
// http(s)://pan.huang1111.cn/s/xxx
|
// http(s)://pan.huang1111.cn/s/xxx
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import org.apache.commons.lang3.StringUtils;
|
|||||||
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.EnumSet;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
|
|
||||||
import static cn.qaiu.parser.PanDomainTemplate.KEY;
|
import static cn.qaiu.parser.PanDomainTemplate.KEY;
|
||||||
@@ -23,6 +25,9 @@ import static cn.qaiu.parser.PanDomainTemplate.PWD;
|
|||||||
* Create at 2024/9/15 14:10
|
* Create at 2024/9/15 14:10
|
||||||
*/
|
*/
|
||||||
public class ParserCreate {
|
public class ParserCreate {
|
||||||
|
private static final Set<PanDomainTemplate> GENERIC_BUILT_IN_PARSERS =
|
||||||
|
EnumSet.of(PanDomainTemplate.CE, PanDomainTemplate.KD, PanDomainTemplate.OTHER);
|
||||||
|
|
||||||
private final PanDomainTemplate panDomainTemplate;
|
private final PanDomainTemplate panDomainTemplate;
|
||||||
private final ShareLinkInfo shareLinkInfo;
|
private final ShareLinkInfo shareLinkInfo;
|
||||||
|
|
||||||
@@ -81,16 +86,16 @@ public class ParserCreate {
|
|||||||
if (shareKey != null) {
|
if (shareKey != null) {
|
||||||
shareLinkInfo.setShareKey(shareKey);
|
shareLinkInfo.setShareKey(shareKey);
|
||||||
}
|
}
|
||||||
} catch (Exception ignored) {}
|
} catch (IllegalStateException | IllegalArgumentException ignored) {}
|
||||||
|
|
||||||
// 提取密码
|
// 提取密码
|
||||||
try {
|
try {
|
||||||
String pwd = matcher.group("PWD");
|
String pwd = matcher.group("PWD");
|
||||||
if (StringUtils.isNotEmpty(pwd)) {
|
if (StringUtils.isNotEmpty(pwd)) {
|
||||||
shareLinkInfo.setSharePassword(pwd);
|
shareLinkInfo.setSharePassword(pwd);
|
||||||
}
|
}
|
||||||
} catch (Exception ignored) {}
|
} catch (IllegalStateException | IllegalArgumentException ignored) {}
|
||||||
|
|
||||||
// 设置标准URL
|
// 设置标准URL
|
||||||
if (customParserConfig.getStandardUrlTemplate() != null) {
|
if (customParserConfig.getStandardUrlTemplate() != null) {
|
||||||
String standardUrl = customParserConfig.getStandardUrlTemplate()
|
String standardUrl = customParserConfig.getStandardUrlTemplate()
|
||||||
@@ -132,12 +137,12 @@ public class ParserCreate {
|
|||||||
if (StringUtils.isNotEmpty(pwd)) {
|
if (StringUtils.isNotEmpty(pwd)) {
|
||||||
shareLinkInfo.setSharePassword(pwd);
|
shareLinkInfo.setSharePassword(pwd);
|
||||||
}
|
}
|
||||||
standardUrl = standardUrl.replace("{pwd}", pwd);
|
standardUrl = standardUrl.replace("{pwd}", StringUtils.defaultString(pwd));
|
||||||
} catch (Exception ignored) {}
|
} catch (IllegalStateException | IllegalArgumentException ignored) {}
|
||||||
|
|
||||||
shareLinkInfo.setShareUrl(shareUrl);
|
shareLinkInfo.setShareUrl(shareUrl);
|
||||||
shareLinkInfo.setShareKey(shareKey);
|
shareLinkInfo.setShareKey(shareKey);
|
||||||
if (!(panDomainTemplate.ordinal() >= PanDomainTemplate.CE.ordinal())) {
|
if (!isGenericBuiltInParser(panDomainTemplate)) {
|
||||||
shareLinkInfo.setStandardUrl(standardUrl);
|
shareLinkInfo.setStandardUrl(standardUrl);
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
@@ -197,7 +202,7 @@ public class ParserCreate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 内置解析器处理
|
// 内置解析器处理
|
||||||
if (panDomainTemplate.ordinal() >= PanDomainTemplate.CE.ordinal()) {
|
if (isGenericBuiltInParser(panDomainTemplate)) {
|
||||||
// 处理Cloudreve(ce)类: pan.huang1111.cn_s_wDz5TK _ -> /
|
// 处理Cloudreve(ce)类: pan.huang1111.cn_s_wDz5TK _ -> /
|
||||||
String[] s = shareKey.split("_");
|
String[] s = shareKey.split("_");
|
||||||
String standardUrl = "https://" + String.join("/", s);
|
String standardUrl = "https://" + String.join("/", s);
|
||||||
@@ -247,9 +252,19 @@ public class ParserCreate {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 根据分享链接获取PanDomainTemplate实例(优先匹配自定义解析器)
|
// 根据分享链接获取PanDomainTemplate实例
|
||||||
public synchronized static ParserCreate fromShareUrl(String shareUrl) {
|
public synchronized static ParserCreate fromShareUrl(String shareUrl) {
|
||||||
// 优先查找支持正则匹配的自定义解析器
|
if (StringUtils.isBlank(shareUrl)) {
|
||||||
|
throw new IllegalArgumentException("shareUrl不能为空");
|
||||||
|
}
|
||||||
|
shareUrl = shareUrl.trim();
|
||||||
|
|
||||||
|
ParserCreate builtInParser = fromBuiltInShareUrl(shareUrl, false);
|
||||||
|
if (builtInParser != null) {
|
||||||
|
return builtInParser;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 明确内置解析器未命中时,再查找支持正则匹配的自定义解析器
|
||||||
for (CustomParserConfig customConfig : CustomParserRegistry.getAll().values()) {
|
for (CustomParserConfig customConfig : CustomParserRegistry.getAll().values()) {
|
||||||
if (customConfig.supportsFromShareUrl()) {
|
if (customConfig.supportsFromShareUrl()) {
|
||||||
Matcher matcher = customConfig.getMatchPattern().matcher(shareUrl);
|
Matcher matcher = customConfig.getMatchPattern().matcher(shareUrl);
|
||||||
@@ -266,15 +281,15 @@ public class ParserCreate {
|
|||||||
if (shareKey != null) {
|
if (shareKey != null) {
|
||||||
shareLinkInfo.setShareKey(shareKey);
|
shareLinkInfo.setShareKey(shareKey);
|
||||||
}
|
}
|
||||||
} catch (Exception ignored) {}
|
} catch (IllegalStateException | IllegalArgumentException ignored) {}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
String password = matcher.group("PWD");
|
String password = matcher.group("PWD");
|
||||||
if (password != null) {
|
if (password != null) {
|
||||||
shareLinkInfo.setSharePassword(password);
|
shareLinkInfo.setSharePassword(password);
|
||||||
}
|
}
|
||||||
} catch (Exception ignored) {}
|
} catch (IllegalStateException | IllegalArgumentException ignored) {}
|
||||||
|
|
||||||
// 设置标准URL(如果有模板)
|
// 设置标准URL(如果有模板)
|
||||||
if (customConfig.getStandardUrlTemplate() != null) {
|
if (customConfig.getStandardUrlTemplate() != null) {
|
||||||
String standardUrl = customConfig.getStandardUrlTemplate()
|
String standardUrl = customConfig.getStandardUrlTemplate()
|
||||||
@@ -295,22 +310,35 @@ public class ParserCreate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 查找内置解析器
|
// 最后再走 Cloudreve/可道云/其他网盘这类泛化兜底,避免抢走自定义解析器
|
||||||
|
builtInParser = fromBuiltInShareUrl(shareUrl, true);
|
||||||
|
if (builtInParser != null) {
|
||||||
|
return builtInParser;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new IllegalArgumentException("Unsupported share URL");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ParserCreate fromBuiltInShareUrl(String shareUrl, boolean genericOnly) {
|
||||||
for (PanDomainTemplate panDomainTemplate : PanDomainTemplate.values()) {
|
for (PanDomainTemplate panDomainTemplate : PanDomainTemplate.values()) {
|
||||||
|
boolean genericParser = isGenericBuiltInParser(panDomainTemplate);
|
||||||
|
if (genericOnly != genericParser) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (panDomainTemplate.getPattern().matcher(shareUrl).matches()) {
|
if (panDomainTemplate.getPattern().matcher(shareUrl).matches()) {
|
||||||
ShareLinkInfo shareLinkInfo = ShareLinkInfo.newBuilder()
|
ShareLinkInfo shareLinkInfo = ShareLinkInfo.newBuilder()
|
||||||
.type(panDomainTemplate.name().toLowerCase())
|
.type(panDomainTemplate.name().toLowerCase())
|
||||||
.panName(panDomainTemplate.getDisplayName())
|
.panName(panDomainTemplate.getDisplayName())
|
||||||
.shareUrl(shareUrl).build();
|
.shareUrl(shareUrl).build();
|
||||||
if (panDomainTemplate.ordinal() >= PanDomainTemplate.CE.ordinal()) {
|
if (isGenericBuiltInParser(panDomainTemplate)) {
|
||||||
shareLinkInfo.setStandardUrl(shareUrl);
|
shareLinkInfo.setStandardUrl(shareUrl);
|
||||||
}
|
}
|
||||||
ParserCreate parserCreate = new ParserCreate(panDomainTemplate, shareLinkInfo);
|
ParserCreate parserCreate = new ParserCreate(panDomainTemplate, shareLinkInfo);
|
||||||
return parserCreate.normalizeShareLink();
|
return parserCreate.normalizeShareLink();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw new IllegalArgumentException("Unsupported share URL");
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 根据type获取枚举实例(优先查找自定义解析器)
|
// 根据type获取枚举实例(优先查找自定义解析器)
|
||||||
@@ -353,7 +381,7 @@ public class ParserCreate {
|
|||||||
// 自定义解析器处理
|
// 自定义解析器处理
|
||||||
if (isCustomParser) {
|
if (isCustomParser) {
|
||||||
path = this.shareLinkInfo.getType() + "/" + this.shareLinkInfo.getShareKey();
|
path = this.shareLinkInfo.getType() + "/" + this.shareLinkInfo.getShareKey();
|
||||||
} else if (panDomainTemplate.ordinal() >= PanDomainTemplate.CE.ordinal()) {
|
} else if (isGenericBuiltInParser(panDomainTemplate)) {
|
||||||
// 处理Cloudreve(ce)类: pan.huang1111.cn_s_wDz5TK _ -> /
|
// 处理Cloudreve(ce)类: pan.huang1111.cn_s_wDz5TK _ -> /
|
||||||
path = this.shareLinkInfo.getType() + "/"
|
path = this.shareLinkInfo.getType() + "/"
|
||||||
+ this.shareLinkInfo.getShareUrl()
|
+ this.shareLinkInfo.getShareUrl()
|
||||||
@@ -381,7 +409,11 @@ public class ParserCreate {
|
|||||||
public CustomParserConfig getCustomParserConfig() {
|
public CustomParserConfig getCustomParserConfig() {
|
||||||
return customParserConfig;
|
return customParserConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static boolean isGenericBuiltInParser(PanDomainTemplate panDomainTemplate) {
|
||||||
|
return GENERIC_BUILT_IN_PARSERS.contains(panDomainTemplate);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取内置解析器模板(仅当isCustomParser为false时有效)
|
* 获取内置解析器模板(仅当isCustomParser为false时有效)
|
||||||
* @return 内置解析器模板,如果是自定义解析器则返回null
|
* @return 内置解析器模板,如果是自定义解析器则返回null
|
||||||
|
|||||||
@@ -0,0 +1,270 @@
|
|||||||
|
package cn.qaiu.parser;
|
||||||
|
|
||||||
|
import io.vertx.core.json.JsonArray;
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 账号密码登录撞上验证码/风控时的用户提示。
|
||||||
|
* 只识别失败形态并引导改用 Authorization,不实现验证码求解、扫码或重试。
|
||||||
|
*/
|
||||||
|
public final class PasswordLoginRisk {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 123 云盘(ye)账号密码登录被验证码/风控拦住时返回给调用方的固定说明。
|
||||||
|
* 上游 code/message 会另附在这句话后面,便于和“密码错误”区分。
|
||||||
|
*/
|
||||||
|
public static final String AUTHORIZATION_HINT =
|
||||||
|
"账号密码登录触发了验证码/风控,已停止用户名密码登录(不会尝试验证码)。"
|
||||||
|
+ "请改为配置 Authorization(浏览器登录后的 Bearer token / JWT,"
|
||||||
|
+ "例如 localStorage 的 authorToken、请求头 authorization 或 Cookie 的 sso-token)。"
|
||||||
|
+ "静态配置写在 app-dev.yml 的 auths.ye.authorization(与 auths.ye.token 等价);"
|
||||||
|
+ "临时请求使用 authType=authorization 或 authType=accesstoken,token 填该令牌(不要重复带 Bearer 前缀)。"
|
||||||
|
+ "说明见 parser/doc/auth-param/。";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上游文案命中这些片段时视为验证码/风控,而不是单纯的密码错误。
|
||||||
|
* 依据公开客户端(AList/OpenList)实际展示过的 123 登录失败文案,以及登录页上的滑块/人机验证提示。
|
||||||
|
*/
|
||||||
|
private static final String[] RISK_KEYWORDS = {
|
||||||
|
"验证码",
|
||||||
|
"风控",
|
||||||
|
"安全风险",
|
||||||
|
"安全验证",
|
||||||
|
"安全校验",
|
||||||
|
"滑块",
|
||||||
|
"滑动验证",
|
||||||
|
"拼图验证",
|
||||||
|
"短信验证",
|
||||||
|
"微信登录",
|
||||||
|
"微信进行登录",
|
||||||
|
"境外登录",
|
||||||
|
"需要验证",
|
||||||
|
"请验证",
|
||||||
|
"请你验证",
|
||||||
|
"进行验证",
|
||||||
|
"完成验证",
|
||||||
|
"二次验证",
|
||||||
|
"人机验证",
|
||||||
|
"操作频繁",
|
||||||
|
"请求过于频繁",
|
||||||
|
"请求频繁",
|
||||||
|
"captcha",
|
||||||
|
"recaptcha",
|
||||||
|
"risk control"
|
||||||
|
};
|
||||||
|
|
||||||
|
private PasswordLoginRisk() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isLoginSuccess(JsonObject json) {
|
||||||
|
if (json == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Integer code = readCode(json);
|
||||||
|
return code != null && code == 200 && StringUtils.isNotBlank(readToken(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean indicatesCaptchaOrRisk(JsonObject json) {
|
||||||
|
if (json == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (hasTruthyRiskField(json) || hasTruthyRiskField(dataObject(json))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return textIndicatesCaptchaOrRisk(collectMessageText(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean textIndicatesCaptchaOrRisk(String text) {
|
||||||
|
if (StringUtils.isBlank(text)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String lower = text.toLowerCase(Locale.ROOT);
|
||||||
|
for (String keyword : RISK_KEYWORDS) {
|
||||||
|
if (lower.contains(keyword.toLowerCase(Locale.ROOT))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 非成功登录响应的用户可见说明。验证码/风控走 Authorization 引导,其余保持“登录失败: 上游文案”。
|
||||||
|
*/
|
||||||
|
public static String describeLoginFailure(JsonObject json) {
|
||||||
|
if (json == null) {
|
||||||
|
return "登录响应格式异常";
|
||||||
|
}
|
||||||
|
if (indicatesCaptchaOrRisk(json)) {
|
||||||
|
return AUTHORIZATION_HINT + " 上游返回:" + upstreamSummary(json);
|
||||||
|
}
|
||||||
|
Integer code = readCode(json);
|
||||||
|
if (code != null && code == 200) {
|
||||||
|
return "未获取到token";
|
||||||
|
}
|
||||||
|
String message = firstMessage(json);
|
||||||
|
if (StringUtils.isBlank(message)) {
|
||||||
|
return "登录失败";
|
||||||
|
}
|
||||||
|
return "登录失败: " + message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String nonJsonLoginFailure(String body) {
|
||||||
|
if (textIndicatesCaptchaOrRisk(body)) {
|
||||||
|
return AUTHORIZATION_HINT + " 上游返回:" + truncate(body, 300);
|
||||||
|
}
|
||||||
|
return "登录响应格式异常: " + body;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String collectMessageText(JsonObject json) {
|
||||||
|
StringBuilder text = new StringBuilder();
|
||||||
|
appendMessage(text, json);
|
||||||
|
JsonObject data = dataObject(json);
|
||||||
|
if (data != null) {
|
||||||
|
appendMessage(text, data);
|
||||||
|
}
|
||||||
|
return text.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void appendMessage(StringBuilder text, JsonObject json) {
|
||||||
|
append(text, json.getString("message"));
|
||||||
|
append(text, json.getString("msg"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void append(StringBuilder text, String value) {
|
||||||
|
if (StringUtils.isNotBlank(value)) {
|
||||||
|
if (text.length() > 0) {
|
||||||
|
text.append(' ');
|
||||||
|
}
|
||||||
|
text.append(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasTruthyRiskField(JsonObject obj) {
|
||||||
|
if (obj == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (String key : obj.fieldNames()) {
|
||||||
|
if (!isRiskFieldName(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isTruthyRiskValue(obj.getValue(key))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isRiskFieldName(String key) {
|
||||||
|
String lower = key.toLowerCase(Locale.ROOT);
|
||||||
|
return lower.contains("captcha")
|
||||||
|
|| lower.contains("vcode")
|
||||||
|
|| lower.contains("risk")
|
||||||
|
|| "needverify".equals(lower)
|
||||||
|
|| "need_verify".equals(lower)
|
||||||
|
|| "slideverify".equals(lower)
|
||||||
|
|| "verifycode".equals(lower)
|
||||||
|
|| "verify_code".equals(lower);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isTruthyRiskValue(Object value) {
|
||||||
|
if (value == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (value instanceof Boolean) {
|
||||||
|
return (Boolean) value;
|
||||||
|
}
|
||||||
|
if (value instanceof Number) {
|
||||||
|
return ((Number) value).doubleValue() != 0d;
|
||||||
|
}
|
||||||
|
if (value instanceof CharSequence) {
|
||||||
|
String text = value.toString().trim();
|
||||||
|
if (text.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String lower = text.toLowerCase(Locale.ROOT);
|
||||||
|
return !"false".equals(lower) && !"0".equals(lower) && !"null".equals(lower) && !"none".equals(lower);
|
||||||
|
}
|
||||||
|
if (value instanceof JsonObject) {
|
||||||
|
return !((JsonObject) value).isEmpty();
|
||||||
|
}
|
||||||
|
if (value instanceof JsonArray) {
|
||||||
|
return !((JsonArray) value).isEmpty();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String upstreamSummary(JsonObject json) {
|
||||||
|
StringBuilder summary = new StringBuilder();
|
||||||
|
Integer code = readCode(json);
|
||||||
|
if (code != null) {
|
||||||
|
summary.append("code=").append(code);
|
||||||
|
}
|
||||||
|
String message = firstMessage(json);
|
||||||
|
if (StringUtils.isNotBlank(message)) {
|
||||||
|
if (summary.length() > 0) {
|
||||||
|
summary.append(", ");
|
||||||
|
}
|
||||||
|
summary.append("message=").append(message);
|
||||||
|
}
|
||||||
|
if (summary.length() == 0) {
|
||||||
|
summary.append(json.encode());
|
||||||
|
}
|
||||||
|
return truncate(summary.toString(), 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String firstMessage(JsonObject json) {
|
||||||
|
String message = json.getString("message");
|
||||||
|
if (StringUtils.isBlank(message)) {
|
||||||
|
message = json.getString("msg");
|
||||||
|
}
|
||||||
|
if (StringUtils.isBlank(message)) {
|
||||||
|
JsonObject data = dataObject(json);
|
||||||
|
if (data != null) {
|
||||||
|
message = data.getString("message");
|
||||||
|
if (StringUtils.isBlank(message)) {
|
||||||
|
message = data.getString("msg");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String readToken(JsonObject json) {
|
||||||
|
JsonObject data = dataObject(json);
|
||||||
|
if (data == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Object token = data.getValue("token");
|
||||||
|
return token == null ? null : token.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static JsonObject dataObject(JsonObject json) {
|
||||||
|
Object data = json.getValue("data");
|
||||||
|
return data instanceof JsonObject ? (JsonObject) data : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Integer readCode(JsonObject json) {
|
||||||
|
Object code = json.getValue("code");
|
||||||
|
if (code instanceof Number) {
|
||||||
|
return ((Number) code).intValue();
|
||||||
|
}
|
||||||
|
if (code instanceof String && StringUtils.isNumeric(((String) code).trim())) {
|
||||||
|
return Integer.parseInt(((String) code).trim());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String truncate(String value, int max) {
|
||||||
|
if (value == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String trimmed = value.trim();
|
||||||
|
if (trimmed.length() <= max) {
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
return trimmed.substring(0, max) + "...";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
package cn.qaiu.parser;
|
||||||
|
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析器 Token/Cookie 缓存 — 支持多账号隔离。
|
||||||
|
* <p>
|
||||||
|
* 以 (diskType + "#" + accountKey) 作为缓存 key,不同账号的 token 互不覆盖。
|
||||||
|
* accountKey 优先使用 _configId,其次使用 username、cookie 前16位等可区分标识。
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
public final class TokenCache {
|
||||||
|
|
||||||
|
private TokenCache() {}
|
||||||
|
|
||||||
|
/** token 缓存 */
|
||||||
|
private static final ConcurrentHashMap<String, String> tokenMap = new ConcurrentHashMap<>();
|
||||||
|
/** 过期时间缓存(毫秒时间戳) */
|
||||||
|
private static final ConcurrentHashMap<String, Long> expireMap = new ConcurrentHashMap<>();
|
||||||
|
/** 同一 key 下的额外字符串缓存(如 userId) */
|
||||||
|
private static final ConcurrentHashMap<String, String> extraMap = new ConcurrentHashMap<>();
|
||||||
|
/** 布尔标记缓存(如 authFlag) */
|
||||||
|
private static final ConcurrentHashMap<String, Boolean> flagMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
// ============ key 构造 ============
|
||||||
|
|
||||||
|
public static String key(String diskType, String accountKey) {
|
||||||
|
return diskType + "#" + (accountKey == null ? "_default" : accountKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ token ============
|
||||||
|
|
||||||
|
public static String getToken(String cacheKey) {
|
||||||
|
return tokenMap.get(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void putToken(String cacheKey, String token) {
|
||||||
|
if (token == null) {
|
||||||
|
tokenMap.remove(cacheKey);
|
||||||
|
} else {
|
||||||
|
tokenMap.put(cacheKey, token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ expire ============
|
||||||
|
|
||||||
|
public static long getExpire(String cacheKey) {
|
||||||
|
return expireMap.getOrDefault(cacheKey, 0L);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void putExpire(String cacheKey, long expireMs) {
|
||||||
|
expireMap.put(cacheKey, expireMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isExpired(String cacheKey) {
|
||||||
|
long exp = getExpire(cacheKey);
|
||||||
|
return exp <= 0 || System.currentTimeMillis() > exp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ extra (userId 等) ============
|
||||||
|
|
||||||
|
public static String getExtra(String cacheKey) {
|
||||||
|
return extraMap.get(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void putExtra(String cacheKey, String value) {
|
||||||
|
if (value == null) {
|
||||||
|
extraMap.remove(cacheKey);
|
||||||
|
} else {
|
||||||
|
extraMap.put(cacheKey, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ flag (authFlag 等) ============
|
||||||
|
|
||||||
|
public static boolean getFlag(String cacheKey, boolean defaultValue) {
|
||||||
|
return flagMap.getOrDefault(cacheKey, defaultValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void putFlag(String cacheKey, boolean value) {
|
||||||
|
flagMap.put(cacheKey, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ 清除 ============
|
||||||
|
|
||||||
|
public static void remove(String cacheKey) {
|
||||||
|
tokenMap.remove(cacheKey);
|
||||||
|
expireMap.remove(cacheKey);
|
||||||
|
extraMap.remove(cacheKey);
|
||||||
|
flagMap.remove(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除指定网盘类型的所有缓存(精准清除,不影响其他网盘类型)
|
||||||
|
*/
|
||||||
|
public static void removeByDiskType(String diskType) {
|
||||||
|
String prefix = diskType + "#";
|
||||||
|
tokenMap.keySet().removeIf(k -> k.startsWith(prefix));
|
||||||
|
expireMap.keySet().removeIf(k -> k.startsWith(prefix));
|
||||||
|
extraMap.keySet().removeIf(k -> k.startsWith(prefix));
|
||||||
|
flagMap.keySet().removeIf(k -> k.startsWith(prefix));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void clear() {
|
||||||
|
tokenMap.clear();
|
||||||
|
expireMap.clear();
|
||||||
|
extraMap.clear();
|
||||||
|
flagMap.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Token 持久化队列 ============
|
||||||
|
|
||||||
|
/** 待持久化的 cachedToken 数据 (cacheKey -> [token, expireMs]) */
|
||||||
|
private static final ConcurrentHashMap<String, String[]> persistQueue = new ConcurrentHashMap<>();
|
||||||
|
/** 待回写的凭据更新 (cacheKey -> newCredential),如 PaliTool refresh_token 轮换 */
|
||||||
|
private static final ConcurrentHashMap<String, String> credentialUpdateQueue = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析器登录成功后,将 token 加入持久化队列(下次 recordConfigUsage 回写 DB)
|
||||||
|
*/
|
||||||
|
public static void queueCachedTokenPersist(String cacheKey, String token, long expireMs) {
|
||||||
|
if (cacheKey != null && token != null) {
|
||||||
|
persistQueue.put(cacheKey, new String[]{token, String.valueOf(expireMs)});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 凭据本身被替换(如 PaliTool refresh_token 轮换),加入回写队列
|
||||||
|
*/
|
||||||
|
public static void queueCredentialUpdate(String cacheKey, String newCredential) {
|
||||||
|
if (cacheKey != null && newCredential != null) {
|
||||||
|
credentialUpdateQueue.put(cacheKey, newCredential);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 消费持久化队列:返回 [token, expireMs] 并移除;无数据返回 null
|
||||||
|
*/
|
||||||
|
public static String[] pollCachedTokenPersist(String cacheKey) {
|
||||||
|
return cacheKey == null ? null : persistQueue.remove(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 消费凭据更新队列:返回新凭据并移除;无数据返回 null
|
||||||
|
*/
|
||||||
|
public static String pollCredentialUpdate(String cacheKey) {
|
||||||
|
return cacheKey == null ? null : credentialUpdateQueue.remove(cacheKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
package cn.qaiu.parser.clientlink.impl;
|
package cn.qaiu.parser.clientlink.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.util.Base64Encoder;
|
||||||
import cn.qaiu.parser.clientlink.ClientLinkGenerator;
|
import cn.qaiu.parser.clientlink.ClientLinkGenerator;
|
||||||
import cn.qaiu.parser.clientlink.ClientLinkType;
|
import cn.qaiu.parser.clientlink.ClientLinkType;
|
||||||
import cn.qaiu.parser.clientlink.DownloadLinkMeta;
|
import cn.qaiu.parser.clientlink.DownloadLinkMeta;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Base64;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 迅雷协议链接生成器
|
* 迅雷协议链接生成器
|
||||||
@@ -27,7 +27,7 @@ public class ThunderLinkGenerator implements ClientLinkGenerator {
|
|||||||
String thunderUrl = "AA" + originalUrl + "ZZ";
|
String thunderUrl = "AA" + originalUrl + "ZZ";
|
||||||
|
|
||||||
// Base64编码
|
// Base64编码
|
||||||
String encodedUrl = Base64.getEncoder().encodeToString(
|
String encodedUrl = Base64Encoder.encode(
|
||||||
thunderUrl.getBytes(StandardCharsets.UTF_8)
|
thunderUrl.getBytes(StandardCharsets.UTF_8)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||||||
public class CustomParserRegistry {
|
public class CustomParserRegistry {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(CustomParserRegistry.class);
|
private static final Logger log = LoggerFactory.getLogger(CustomParserRegistry.class);
|
||||||
|
private static final int MAX_CUSTOM_PARSERS = Integer.getInteger("parser.custom.maxRegistrySize", 256);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 存储自定义解析器配置的Map,key为类型标识,value为配置对象
|
* 存储自定义解析器配置的Map,key为类型标识,value为配置对象
|
||||||
@@ -33,7 +34,7 @@ public class CustomParserRegistry {
|
|||||||
* @param config 解析器配置
|
* @param config 解析器配置
|
||||||
* @throws IllegalArgumentException 如果type已存在或与内置解析器冲突
|
* @throws IllegalArgumentException 如果type已存在或与内置解析器冲突
|
||||||
*/
|
*/
|
||||||
public static void register(CustomParserConfig config) {
|
public static synchronized void register(CustomParserConfig config) {
|
||||||
if (config == null) {
|
if (config == null) {
|
||||||
throw new IllegalArgumentException("config不能为空");
|
throw new IllegalArgumentException("config不能为空");
|
||||||
}
|
}
|
||||||
@@ -59,6 +60,11 @@ public class CustomParserRegistry {
|
|||||||
"类型标识 '" + type + "' 已被注册,请先注销或使用其他标识"
|
"类型标识 '" + type + "' 已被注册,请先注销或使用其他标识"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (CUSTOM_PARSERS.size() >= MAX_CUSTOM_PARSERS) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"自定义解析器数量已达到上限(" + MAX_CUSTOM_PARSERS + "个),请先注销不需要的解析器"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
CUSTOM_PARSERS.put(type, config);
|
CUSTOM_PARSERS.put(type, config);
|
||||||
log.info("注册自定义解析器成功: {} ({})", config.getDisplayName(), type);
|
log.info("注册自定义解析器成功: {} ({})", config.getDisplayName(), type);
|
||||||
@@ -171,7 +177,7 @@ public class CustomParserRegistry {
|
|||||||
* @param type 解析器类型标识
|
* @param type 解析器类型标识
|
||||||
* @return 是否注销成功
|
* @return 是否注销成功
|
||||||
*/
|
*/
|
||||||
public static boolean unregister(String type) {
|
public static synchronized boolean unregister(String type) {
|
||||||
if (type == null || type.trim().isEmpty()) {
|
if (type == null || type.trim().isEmpty()) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -213,7 +219,7 @@ public class CustomParserRegistry {
|
|||||||
/**
|
/**
|
||||||
* 清空所有自定义解析器
|
* 清空所有自定义解析器
|
||||||
*/
|
*/
|
||||||
public static void clear() {
|
public static synchronized void clear() {
|
||||||
CUSTOM_PARSERS.clear();
|
CUSTOM_PARSERS.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,19 +2,21 @@ package cn.qaiu.parser.customjs;
|
|||||||
|
|
||||||
import cn.qaiu.WebClientVertxInit;
|
import cn.qaiu.WebClientVertxInit;
|
||||||
import cn.qaiu.util.HttpResponseHelper;
|
import cn.qaiu.util.HttpResponseHelper;
|
||||||
import io.vertx.core.Future;
|
|
||||||
import io.vertx.core.MultiMap;
|
import io.vertx.core.MultiMap;
|
||||||
import io.vertx.core.Promise;
|
import io.vertx.core.Promise;
|
||||||
import io.vertx.core.buffer.Buffer;
|
import io.vertx.core.buffer.Buffer;
|
||||||
|
import io.vertx.core.http.HttpClient;
|
||||||
|
import io.vertx.core.http.HttpClientOptions;
|
||||||
|
import io.vertx.core.http.HttpClientRequest;
|
||||||
|
import io.vertx.core.http.HttpClientResponse;
|
||||||
|
import io.vertx.core.http.HttpHeaders;
|
||||||
|
import io.vertx.core.http.HttpMethod;
|
||||||
|
import io.vertx.core.http.RequestOptions;
|
||||||
|
import io.vertx.core.json.Json;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import io.vertx.core.net.ProxyOptions;
|
import io.vertx.core.net.ProxyOptions;
|
||||||
import io.vertx.core.net.ProxyType;
|
import io.vertx.core.net.ProxyType;
|
||||||
import io.vertx.ext.web.client.HttpRequest;
|
|
||||||
import io.vertx.ext.web.client.HttpResponse;
|
import io.vertx.ext.web.client.HttpResponse;
|
||||||
import io.vertx.ext.web.client.WebClient;
|
|
||||||
import io.vertx.ext.web.client.WebClientOptions;
|
|
||||||
import io.vertx.ext.web.client.WebClientSession;
|
|
||||||
import io.vertx.ext.web.multipart.MultipartForm;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@@ -27,8 +29,13 @@ import java.net.UnknownHostException;
|
|||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.TimeoutException;
|
import java.util.concurrent.TimeoutException;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,11 +46,60 @@ import java.util.regex.Pattern;
|
|||||||
* Create at 2025/10/17
|
* Create at 2025/10/17
|
||||||
*/
|
*/
|
||||||
public class JsHttpClient {
|
public class JsHttpClient {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(JsHttpClient.class);
|
private static final Logger log = LoggerFactory.getLogger(JsHttpClient.class);
|
||||||
|
private static final int MAX_RESPONSE_BODY_BYTES = 8 * 1024 * 1024;
|
||||||
private final WebClient client;
|
private static final int MAX_REQUEST_BODY_BYTES = 8 * 1024 * 1024;
|
||||||
private final WebClientSession clientSession;
|
private static final int MAX_HEADER_COUNT = 64;
|
||||||
|
private static final int MAX_HEADER_VALUE_LENGTH = 4096;
|
||||||
|
private static final int MAX_TIMEOUT_SECONDS = 120;
|
||||||
|
private static final int MAX_REDIRECTS = 5;
|
||||||
|
private static final String DEFAULT_ACCEPT_ENCODING = "gzip, deflate, br";
|
||||||
|
|
||||||
|
private static final Object SHARED_CLIENT_LOCK = new Object();
|
||||||
|
// 共享 HttpClient 实例(非代理模式),懒加载避免类初始化阶段抢跑 Vert.x。
|
||||||
|
private static volatile HttpClient sharedClient;
|
||||||
|
private static volatile boolean sharedClientShutdown = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭共享 HttpClient(应用关闭时调用)
|
||||||
|
*/
|
||||||
|
public static void shutdownSharedClient() {
|
||||||
|
synchronized (SHARED_CLIENT_LOCK) {
|
||||||
|
sharedClientShutdown = true;
|
||||||
|
if (sharedClient != null) {
|
||||||
|
sharedClient.close();
|
||||||
|
sharedClient = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HttpClient sharedClient() {
|
||||||
|
synchronized (SHARED_CLIENT_LOCK) {
|
||||||
|
ensureSharedClientAvailable();
|
||||||
|
if (sharedClient == null) {
|
||||||
|
sharedClient = WebClientVertxInit.get().createHttpClient(
|
||||||
|
new HttpClientOptions()
|
||||||
|
.setConnectTimeout(10000)
|
||||||
|
.setIdleTimeout(30)
|
||||||
|
.setIdleTimeoutUnit(TimeUnit.SECONDS)
|
||||||
|
.setMaxPoolSize(64));
|
||||||
|
}
|
||||||
|
return sharedClient;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ensureSharedClientAvailable() {
|
||||||
|
if (sharedClientShutdown) {
|
||||||
|
throw new IllegalStateException("共享 JavaScript HttpClient 已关闭");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final HttpClient client;
|
||||||
|
private final boolean ownClient; // 标记是否为自建 client(需要 close)
|
||||||
|
private final AtomicBoolean closed = new AtomicBoolean(false);
|
||||||
|
private final Object requestLock = new Object();
|
||||||
|
private final Set<HttpClientRequest> activeRequests = ConcurrentHashMap.newKeySet();
|
||||||
private MultiMap headers;
|
private MultiMap headers;
|
||||||
private int timeoutSeconds = 30; // 默认超时时间30秒
|
private int timeoutSeconds = 30; // 默认超时时间30秒
|
||||||
|
|
||||||
@@ -61,11 +117,12 @@ public class JsHttpClient {
|
|||||||
};
|
};
|
||||||
|
|
||||||
public JsHttpClient() {
|
public JsHttpClient() {
|
||||||
this.client = WebClient.create(WebClientVertxInit.get(), new WebClientOptions());;
|
ensureSharedClientAvailable();
|
||||||
this.clientSession = WebClientSession.create(client);
|
this.client = sharedClient();
|
||||||
|
this.ownClient = false;
|
||||||
this.headers = MultiMap.caseInsensitiveMultiMap();
|
this.headers = MultiMap.caseInsensitiveMultiMap();
|
||||||
// 设置默认的Accept-Encoding头以支持压缩响应
|
// 设置默认的Accept-Encoding头以支持压缩响应
|
||||||
this.headers.set("Accept-Encoding", "gzip, deflate, br, zstd");
|
this.headers.set("Accept-Encoding", DEFAULT_ACCEPT_ENCODING);
|
||||||
// 设置默认的User-Agent头
|
// 设置默认的User-Agent头
|
||||||
this.headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
|
this.headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
|
||||||
// 设置默认的Accept-Language头
|
// 设置默认的Accept-Language头
|
||||||
@@ -77,31 +134,35 @@ public class JsHttpClient {
|
|||||||
* @param proxyConfig 代理配置JsonObject,包含type、host、port、username、password
|
* @param proxyConfig 代理配置JsonObject,包含type、host、port、username、password
|
||||||
*/
|
*/
|
||||||
public JsHttpClient(JsonObject proxyConfig) {
|
public JsHttpClient(JsonObject proxyConfig) {
|
||||||
|
ensureSharedClientAvailable();
|
||||||
if (proxyConfig != null && proxyConfig.containsKey("type")) {
|
if (proxyConfig != null && proxyConfig.containsKey("type")) {
|
||||||
ProxyOptions proxyOptions = new ProxyOptions()
|
ProxyOptions proxyOptions = new ProxyOptions()
|
||||||
.setType(ProxyType.valueOf(proxyConfig.getString("type").toUpperCase()))
|
.setType(ProxyType.valueOf(proxyConfig.getString("type").toUpperCase()))
|
||||||
.setHost(proxyConfig.getString("host"))
|
.setHost(proxyConfig.getString("host"))
|
||||||
.setPort(proxyConfig.getInteger("port"));
|
.setPort(proxyConfig.getInteger("port"));
|
||||||
|
|
||||||
if (StringUtils.isNotEmpty(proxyConfig.getString("username"))) {
|
if (StringUtils.isNotEmpty(proxyConfig.getString("username"))) {
|
||||||
proxyOptions.setUsername(proxyConfig.getString("username"));
|
proxyOptions.setUsername(proxyConfig.getString("username"));
|
||||||
}
|
}
|
||||||
if (StringUtils.isNotEmpty(proxyConfig.getString("password"))) {
|
if (StringUtils.isNotEmpty(proxyConfig.getString("password"))) {
|
||||||
proxyOptions.setPassword(proxyConfig.getString("password"));
|
proxyOptions.setPassword(proxyConfig.getString("password"));
|
||||||
}
|
}
|
||||||
|
|
||||||
this.client = WebClient.create(WebClientVertxInit.get(),
|
this.client = WebClientVertxInit.get().createHttpClient(
|
||||||
new WebClientOptions()
|
new HttpClientOptions()
|
||||||
.setUserAgentEnabled(false)
|
.setConnectTimeout(10000)
|
||||||
|
.setIdleTimeout(30)
|
||||||
|
.setIdleTimeoutUnit(TimeUnit.SECONDS)
|
||||||
|
.setMaxPoolSize(16)
|
||||||
.setProxyOptions(proxyOptions));
|
.setProxyOptions(proxyOptions));
|
||||||
this.clientSession = WebClientSession.create(client);
|
this.ownClient = true;
|
||||||
} else {
|
} else {
|
||||||
this.client = WebClient.create(WebClientVertxInit.get());
|
this.client = sharedClient();
|
||||||
this.clientSession = WebClientSession.create(client);
|
this.ownClient = false;
|
||||||
}
|
}
|
||||||
this.headers = MultiMap.caseInsensitiveMultiMap();
|
this.headers = MultiMap.caseInsensitiveMultiMap();
|
||||||
// 设置默认的Accept-Encoding头以支持压缩响应
|
// 设置默认的Accept-Encoding头以支持压缩响应
|
||||||
this.headers.set("Accept-Encoding", "gzip, deflate, br, zstd");
|
this.headers.set("Accept-Encoding", DEFAULT_ACCEPT_ENCODING);
|
||||||
// 设置默认的User-Agent头
|
// 设置默认的User-Agent头
|
||||||
this.headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
|
this.headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
|
||||||
// 设置默认的Accept-Language头
|
// 设置默认的Accept-Language头
|
||||||
@@ -183,13 +244,7 @@ public class JsHttpClient {
|
|||||||
*/
|
*/
|
||||||
public JsHttpResponse get(String url) {
|
public JsHttpResponse get(String url) {
|
||||||
validateUrlSecurity(url);
|
validateUrlSecurity(url);
|
||||||
return executeRequest(() -> {
|
return executeRequest(HttpMethod.GET, url, null, false);
|
||||||
HttpRequest<Buffer> request = client.getAbs(url);
|
|
||||||
if (!headers.isEmpty()) {
|
|
||||||
request.putHeaders(headers);
|
|
||||||
}
|
|
||||||
return request.send();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -198,16 +253,25 @@ public class JsHttpClient {
|
|||||||
* @return HTTP响应
|
* @return HTTP响应
|
||||||
*/
|
*/
|
||||||
public JsHttpResponse getWithRedirect(String url) {
|
public JsHttpResponse getWithRedirect(String url) {
|
||||||
validateUrlSecurity(url);
|
String currentUrl = url;
|
||||||
return executeRequest(() -> {
|
for (int redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount++) {
|
||||||
HttpRequest<Buffer> request = client.getAbs(url);
|
validateUrlSecurity(currentUrl);
|
||||||
if (!headers.isEmpty()) {
|
JsHttpResponse response = executeRequest(HttpMethod.GET, currentUrl, null, false);
|
||||||
request.putHeaders(headers);
|
if (!isRedirectStatus(response.statusCode())) {
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
// 设置跟随重定向
|
|
||||||
request.followRedirects(true);
|
if (redirectCount == MAX_REDIRECTS) {
|
||||||
return request.send();
|
throw new RuntimeException("重定向次数超过限制: " + MAX_REDIRECTS);
|
||||||
});
|
}
|
||||||
|
|
||||||
|
String location = response.header(HttpHeaders.LOCATION.toString());
|
||||||
|
if (StringUtils.isBlank(location)) {
|
||||||
|
throw new RuntimeException("重定向响应缺少Location头");
|
||||||
|
}
|
||||||
|
currentUrl = resolveRedirectUrl(currentUrl, location);
|
||||||
|
}
|
||||||
|
throw new RuntimeException("重定向处理失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -217,15 +281,7 @@ public class JsHttpClient {
|
|||||||
*/
|
*/
|
||||||
public JsHttpResponse getNoRedirect(String url) {
|
public JsHttpResponse getNoRedirect(String url) {
|
||||||
validateUrlSecurity(url);
|
validateUrlSecurity(url);
|
||||||
return executeRequest(() -> {
|
return executeRequest(HttpMethod.GET, url, null, false);
|
||||||
HttpRequest<Buffer> request = client.getAbs(url);
|
|
||||||
if (!headers.isEmpty()) {
|
|
||||||
request.putHeaders(headers);
|
|
||||||
}
|
|
||||||
// 设置不跟随重定向
|
|
||||||
request.followRedirects(false);
|
|
||||||
return request.send();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -236,26 +292,7 @@ public class JsHttpClient {
|
|||||||
*/
|
*/
|
||||||
public JsHttpResponse post(String url, Object data) {
|
public JsHttpResponse post(String url, Object data) {
|
||||||
validateUrlSecurity(url);
|
validateUrlSecurity(url);
|
||||||
return executeRequest(() -> {
|
return executeRequest(HttpMethod.POST, url, bodyFromData(data), false);
|
||||||
HttpRequest<Buffer> request = client.postAbs(url);
|
|
||||||
if (!headers.isEmpty()) {
|
|
||||||
request.putHeaders(headers);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data != null) {
|
|
||||||
if (data instanceof String) {
|
|
||||||
return request.sendBuffer(Buffer.buffer((String) data));
|
|
||||||
} else if (data instanceof Map) {
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
Map<String, String> mapData = (Map<String, String>) data;
|
|
||||||
return request.sendForm(MultiMap.caseInsensitiveMultiMap().addAll(mapData));
|
|
||||||
} else {
|
|
||||||
return request.sendJson(data);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return request.send();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -266,26 +303,7 @@ public class JsHttpClient {
|
|||||||
*/
|
*/
|
||||||
public JsHttpResponse put(String url, Object data) {
|
public JsHttpResponse put(String url, Object data) {
|
||||||
validateUrlSecurity(url);
|
validateUrlSecurity(url);
|
||||||
return executeRequest(() -> {
|
return executeRequest(HttpMethod.PUT, url, bodyFromData(data), false);
|
||||||
HttpRequest<Buffer> request = client.putAbs(url);
|
|
||||||
if (!headers.isEmpty()) {
|
|
||||||
request.putHeaders(headers);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data != null) {
|
|
||||||
if (data instanceof String) {
|
|
||||||
return request.sendBuffer(Buffer.buffer((String) data));
|
|
||||||
} else if (data instanceof Map) {
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
Map<String, String> mapData = (Map<String, String>) data;
|
|
||||||
return request.sendForm(MultiMap.caseInsensitiveMultiMap().addAll(mapData));
|
|
||||||
} else {
|
|
||||||
return request.sendJson(data);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return request.send();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -294,13 +312,8 @@ public class JsHttpClient {
|
|||||||
* @return HTTP响应
|
* @return HTTP响应
|
||||||
*/
|
*/
|
||||||
public JsHttpResponse delete(String url) {
|
public JsHttpResponse delete(String url) {
|
||||||
return executeRequest(() -> {
|
validateUrlSecurity(url);
|
||||||
HttpRequest<Buffer> request = client.deleteAbs(url);
|
return executeRequest(HttpMethod.DELETE, url, null, false);
|
||||||
if (!headers.isEmpty()) {
|
|
||||||
request.putHeaders(headers);
|
|
||||||
}
|
|
||||||
return request.send();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -310,26 +323,8 @@ public class JsHttpClient {
|
|||||||
* @return HTTP响应
|
* @return HTTP响应
|
||||||
*/
|
*/
|
||||||
public JsHttpResponse patch(String url, Object data) {
|
public JsHttpResponse patch(String url, Object data) {
|
||||||
return executeRequest(() -> {
|
validateUrlSecurity(url);
|
||||||
HttpRequest<Buffer> request = client.patchAbs(url);
|
return executeRequest(HttpMethod.PATCH, url, bodyFromData(data), false);
|
||||||
if (!headers.isEmpty()) {
|
|
||||||
request.putHeaders(headers);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data != null) {
|
|
||||||
if (data instanceof String) {
|
|
||||||
return request.sendBuffer(Buffer.buffer((String) data));
|
|
||||||
} else if (data instanceof Map) {
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
Map<String, String> mapData = (Map<String, String>) data;
|
|
||||||
return request.sendForm(MultiMap.caseInsensitiveMultiMap().addAll(mapData));
|
|
||||||
} else {
|
|
||||||
return request.sendJson(data);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return request.send();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -340,6 +335,12 @@ public class JsHttpClient {
|
|||||||
*/
|
*/
|
||||||
public JsHttpClient putHeader(String name, String value) {
|
public JsHttpClient putHeader(String name, String value) {
|
||||||
if (name != null && value != null) {
|
if (name != null && value != null) {
|
||||||
|
if (headers.size() >= MAX_HEADER_COUNT && !headers.contains(name)) {
|
||||||
|
throw new IllegalArgumentException("请求头数量超过限制");
|
||||||
|
}
|
||||||
|
if (value.length() > MAX_HEADER_VALUE_LENGTH) {
|
||||||
|
throw new IllegalArgumentException("请求头过长: " + name);
|
||||||
|
}
|
||||||
headers.set(name, value);
|
headers.set(name, value);
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
@@ -353,9 +354,7 @@ public class JsHttpClient {
|
|||||||
public JsHttpClient putHeaders(Map<String, String> headersMap) {
|
public JsHttpClient putHeaders(Map<String, String> headersMap) {
|
||||||
if (headersMap != null) {
|
if (headersMap != null) {
|
||||||
for (Map.Entry<String, String> entry : headersMap.entrySet()) {
|
for (Map.Entry<String, String> entry : headersMap.entrySet()) {
|
||||||
if (entry.getKey() != null && entry.getValue() != null) {
|
putHeader(entry.getKey(), entry.getValue());
|
||||||
headers.set(entry.getKey(), entry.getValue());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
@@ -380,7 +379,7 @@ public class JsHttpClient {
|
|||||||
public JsHttpClient clearHeaders() {
|
public JsHttpClient clearHeaders() {
|
||||||
headers.clear();
|
headers.clear();
|
||||||
// 重新设置默认头
|
// 重新设置默认头
|
||||||
headers.set("Accept-Encoding", "gzip, deflate, br, zstd");
|
headers.set("Accept-Encoding", DEFAULT_ACCEPT_ENCODING);
|
||||||
headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
|
headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
|
||||||
headers.set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
|
headers.set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
|
||||||
return this;
|
return this;
|
||||||
@@ -405,7 +404,7 @@ public class JsHttpClient {
|
|||||||
*/
|
*/
|
||||||
public JsHttpClient setTimeout(int seconds) {
|
public JsHttpClient setTimeout(int seconds) {
|
||||||
if (seconds > 0) {
|
if (seconds > 0) {
|
||||||
this.timeoutSeconds = seconds;
|
this.timeoutSeconds = Math.min(seconds, MAX_TIMEOUT_SECONDS);
|
||||||
}
|
}
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
@@ -450,19 +449,12 @@ public class JsHttpClient {
|
|||||||
* @return HTTP响应
|
* @return HTTP响应
|
||||||
*/
|
*/
|
||||||
public JsHttpResponse sendForm(Map<String, String> data) {
|
public JsHttpResponse sendForm(Map<String, String> data) {
|
||||||
return executeRequest(() -> {
|
throw new IllegalArgumentException("sendForm(data) 缺少请求URL,请使用 post(url, data)");
|
||||||
HttpRequest<Buffer> request = client.postAbs("");
|
}
|
||||||
if (!headers.isEmpty()) {
|
|
||||||
request.putHeaders(headers);
|
public JsHttpResponse sendForm(String url, Map<String, String> data) {
|
||||||
}
|
validateUrlSecurity(url);
|
||||||
|
return executeRequest(HttpMethod.POST, url, formBody(data), false);
|
||||||
MultiMap formData = MultiMap.caseInsensitiveMultiMap();
|
|
||||||
if (data != null) {
|
|
||||||
formData.addAll(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
return request.sendForm(formData);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -474,34 +466,8 @@ public class JsHttpClient {
|
|||||||
* @return HTTP响应
|
* @return HTTP响应
|
||||||
*/
|
*/
|
||||||
public JsHttpResponse sendMultipartForm(String url, Map<String, Object> data) {
|
public JsHttpResponse sendMultipartForm(String url, Map<String, Object> data) {
|
||||||
return executeRequest(() -> {
|
validateUrlSecurity(url);
|
||||||
HttpRequest<Buffer> request = client.postAbs(url);
|
return executeRequest(HttpMethod.POST, url, multipartBody(data), false);
|
||||||
if (!headers.isEmpty()) {
|
|
||||||
request.putHeaders(headers);
|
|
||||||
}
|
|
||||||
|
|
||||||
MultipartForm form = MultipartForm.create();
|
|
||||||
|
|
||||||
if (data != null) {
|
|
||||||
for (Map.Entry<String, Object> entry : data.entrySet()) {
|
|
||||||
String key = entry.getKey();
|
|
||||||
Object value = entry.getValue();
|
|
||||||
|
|
||||||
if (value instanceof String) {
|
|
||||||
form.attribute(key, (String) value);
|
|
||||||
} else if (value instanceof byte[]) {
|
|
||||||
form.binaryFileUpload(key, key, Buffer.buffer((byte[]) value), "application/octet-stream");
|
|
||||||
} else if (value instanceof Buffer) {
|
|
||||||
form.binaryFileUpload(key, key, (Buffer) value, "application/octet-stream");
|
|
||||||
} else if (value != null) {
|
|
||||||
// 其他类型转换为字符串
|
|
||||||
form.attribute(key, value.toString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return request.sendMultipartForm(form);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -510,44 +476,103 @@ public class JsHttpClient {
|
|||||||
* @return HTTP响应
|
* @return HTTP响应
|
||||||
*/
|
*/
|
||||||
public JsHttpResponse sendJson(Object data) {
|
public JsHttpResponse sendJson(Object data) {
|
||||||
return executeRequest(() -> {
|
throw new IllegalArgumentException("sendJson(data) 缺少请求URL,请使用 post(url, data)");
|
||||||
HttpRequest<Buffer> request = client.postAbs("");
|
}
|
||||||
if (!headers.isEmpty()) {
|
|
||||||
request.putHeaders(headers);
|
public JsHttpResponse sendJson(String url, Object data) {
|
||||||
}
|
validateUrlSecurity(url);
|
||||||
|
return executeRequest(HttpMethod.POST, url, jsonBody(data), false);
|
||||||
return request.sendJson(data);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 执行HTTP请求(同步)
|
* 执行HTTP请求(同步)
|
||||||
*/
|
*/
|
||||||
private JsHttpResponse executeRequest(RequestExecutor executor) {
|
private JsHttpResponse executeRequest(HttpMethod method, String url, RequestBody requestBody, boolean followRedirects) {
|
||||||
|
if (closed.get()) {
|
||||||
|
throw new IllegalStateException("HTTP客户端已关闭");
|
||||||
|
}
|
||||||
|
AtomicReference<HttpClientRequest> requestRef = new AtomicReference<>();
|
||||||
|
AtomicBoolean abandoned = new AtomicBoolean(false);
|
||||||
try {
|
try {
|
||||||
Promise<HttpResponse<Buffer>> promise = Promise.promise();
|
Promise<JsHttpResponse> promise = Promise.promise();
|
||||||
Future<HttpResponse<Buffer>> future = executor.execute();
|
|
||||||
|
RequestOptions options = new RequestOptions()
|
||||||
future.onComplete(result -> {
|
.setMethod(method)
|
||||||
if (result.succeeded()) {
|
.setAbsoluteURI(url)
|
||||||
promise.complete(result.result());
|
.setFollowRedirects(followRedirects)
|
||||||
} else {
|
.setTimeout(TimeUnit.SECONDS.toMillis(timeoutSeconds))
|
||||||
promise.fail(result.cause());
|
.setHeaders(MultiMap.caseInsensitiveMultiMap().setAll(headers));
|
||||||
|
|
||||||
|
client.request(options).onComplete(ar -> {
|
||||||
|
if (ar.failed()) {
|
||||||
|
promise.tryFail(ar.cause());
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}).onFailure(Throwable::printStackTrace);
|
|
||||||
|
HttpClientRequest request = ar.result();
|
||||||
// 等待响应完成(使用配置的超时时间)
|
synchronized (requestLock) {
|
||||||
HttpResponse<Buffer> response = promise.future().toCompletionStage()
|
if (closed.get() || abandoned.get()) {
|
||||||
|
request.reset();
|
||||||
|
promise.tryFail("HTTP客户端已关闭");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
activeRequests.add(request);
|
||||||
|
requestRef.set(request);
|
||||||
|
request.exceptionHandler(e -> {
|
||||||
|
finishRequest(request);
|
||||||
|
promise.tryFail(e);
|
||||||
|
});
|
||||||
|
request.response().onComplete(responseAr -> {
|
||||||
|
if (responseAr.succeeded()) {
|
||||||
|
collectResponse(request, responseAr.result(), promise);
|
||||||
|
} else {
|
||||||
|
finishRequest(request);
|
||||||
|
promise.tryFail(responseAr.cause());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (closed.get() || abandoned.get()) {
|
||||||
|
request.reset();
|
||||||
|
finishRequest(request);
|
||||||
|
promise.tryFail("HTTP客户端已关闭");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (requestBody == null || requestBody.body() == null) {
|
||||||
|
request.end().onFailure(e -> {
|
||||||
|
finishRequest(request);
|
||||||
|
promise.tryFail(e);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
request.headers().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(requestBody.body().length()));
|
||||||
|
if (StringUtils.isNotEmpty(requestBody.contentType())) {
|
||||||
|
request.headers().set(HttpHeaders.CONTENT_TYPE, requestBody.contentType());
|
||||||
|
}
|
||||||
|
request.end(requestBody.body()).onFailure(e -> {
|
||||||
|
finishRequest(request);
|
||||||
|
promise.tryFail(e);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return promise.future().toCompletionStage()
|
||||||
.toCompletableFuture()
|
.toCompletableFuture()
|
||||||
.get(timeoutSeconds, TimeUnit.SECONDS);
|
.get(timeoutSeconds, TimeUnit.SECONDS);
|
||||||
|
|
||||||
return new JsHttpResponse(response);
|
|
||||||
|
|
||||||
} catch (TimeoutException e) {
|
} catch (TimeoutException e) {
|
||||||
|
// RequestOptions timeout 通常会先触发;这里再兜底,避免等待线程返回后请求还在后台下载。
|
||||||
String errorMsg = "HTTP请求超时(" + timeoutSeconds + "秒)";
|
String errorMsg = "HTTP请求超时(" + timeoutSeconds + "秒)";
|
||||||
|
abandoned.set(true);
|
||||||
|
synchronized (requestLock) {
|
||||||
|
abortRequest(requestRef);
|
||||||
|
}
|
||||||
log.error(errorMsg, e);
|
log.error(errorMsg, e);
|
||||||
throw new RuntimeException(errorMsg, e);
|
throw new RuntimeException(errorMsg, e);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
abandoned.set(true);
|
||||||
|
synchronized (requestLock) {
|
||||||
|
abortRequest(requestRef);
|
||||||
|
}
|
||||||
String errorMsg = e.getMessage();
|
String errorMsg = e.getMessage();
|
||||||
if (errorMsg == null || errorMsg.trim().isEmpty()) {
|
if (errorMsg == null || errorMsg.trim().isEmpty()) {
|
||||||
errorMsg = e.getClass().getSimpleName();
|
errorMsg = e.getClass().getSimpleName();
|
||||||
@@ -559,13 +584,196 @@ public class JsHttpClient {
|
|||||||
throw new RuntimeException("HTTP请求执行失败: " + errorMsg, e);
|
throw new RuntimeException("HTTP请求执行失败: " + errorMsg, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private static boolean isRedirectStatus(int statusCode) {
|
||||||
* 请求执行器接口
|
return statusCode == 301 || statusCode == 302 || statusCode == 303
|
||||||
*/
|
|| statusCode == 307 || statusCode == 308;
|
||||||
@FunctionalInterface
|
}
|
||||||
private interface RequestExecutor {
|
|
||||||
Future<HttpResponse<Buffer>> execute();
|
private String resolveRedirectUrl(String currentUrl, String location) {
|
||||||
|
try {
|
||||||
|
URI redirectUri = new URI(currentUrl).resolve(location.trim());
|
||||||
|
String scheme = redirectUri.getScheme();
|
||||||
|
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
|
||||||
|
throw new SecurityException("🔒 安全拦截: 重定向协议不被允许");
|
||||||
|
}
|
||||||
|
String redirectUrl = redirectUri.toString();
|
||||||
|
validateUrlSecurity(redirectUrl);
|
||||||
|
return redirectUrl;
|
||||||
|
} catch (SecurityException e) {
|
||||||
|
throw e;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("解析重定向地址失败: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void collectResponse(HttpClientRequest request, HttpClientResponse response, Promise<JsHttpResponse> promise) {
|
||||||
|
Buffer body = Buffer.buffer();
|
||||||
|
AtomicBoolean done = new AtomicBoolean(false);
|
||||||
|
|
||||||
|
String contentLengthHeader = response.getHeader(HttpHeaders.CONTENT_LENGTH.toString());
|
||||||
|
if (StringUtils.isNumeric(contentLengthHeader)) {
|
||||||
|
long contentLength = Long.parseLong(contentLengthHeader);
|
||||||
|
if (contentLength > MAX_RESPONSE_BODY_BYTES) {
|
||||||
|
done.set(true);
|
||||||
|
request.reset();
|
||||||
|
finishRequest(request);
|
||||||
|
promise.tryFail("响应体过大: " + contentLength + " bytes");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
response.exceptionHandler(e -> {
|
||||||
|
if (done.compareAndSet(false, true)) {
|
||||||
|
finishRequest(request);
|
||||||
|
promise.tryFail(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
response.handler(chunk -> {
|
||||||
|
if (done.get()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (body.length() + chunk.length() > MAX_RESPONSE_BODY_BYTES) {
|
||||||
|
if (done.compareAndSet(false, true)) {
|
||||||
|
request.reset();
|
||||||
|
finishRequest(request);
|
||||||
|
promise.tryFail("响应体过大: " + (body.length() + chunk.length()) + " bytes");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
body.appendBuffer(chunk);
|
||||||
|
});
|
||||||
|
response.endHandler(v -> {
|
||||||
|
if (done.compareAndSet(false, true)) {
|
||||||
|
finishRequest(request);
|
||||||
|
promise.tryComplete(new JsHttpResponse(
|
||||||
|
response.statusCode(),
|
||||||
|
MultiMap.caseInsensitiveMultiMap().setAll(response.headers()),
|
||||||
|
body,
|
||||||
|
response.statusMessage(),
|
||||||
|
null
|
||||||
|
));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
response.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishRequest(HttpClientRequest request) {
|
||||||
|
if (request != null) {
|
||||||
|
activeRequests.remove(request);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void abortRequest(AtomicReference<HttpClientRequest> requestRef) {
|
||||||
|
HttpClientRequest request = requestRef.get();
|
||||||
|
if (request != null) {
|
||||||
|
try {
|
||||||
|
request.reset();
|
||||||
|
} finally {
|
||||||
|
finishRequest(request);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private RequestBody bodyFromData(Object data) {
|
||||||
|
if (data == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (data instanceof String str) {
|
||||||
|
return plainTextBody(str);
|
||||||
|
}
|
||||||
|
if (data instanceof Buffer buffer) {
|
||||||
|
return limitedBody(buffer, null);
|
||||||
|
}
|
||||||
|
if (data instanceof byte[] bytes) {
|
||||||
|
return limitedBody(Buffer.buffer(bytes), null);
|
||||||
|
}
|
||||||
|
if (data instanceof Map<?, ?> map) {
|
||||||
|
Map<String, String> formMap = new HashMap<>();
|
||||||
|
map.forEach((key, value) -> {
|
||||||
|
if (key != null && value != null) {
|
||||||
|
formMap.put(String.valueOf(key), String.valueOf(value));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return formBody(formMap);
|
||||||
|
}
|
||||||
|
return jsonBody(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
private RequestBody plainTextBody(String data) {
|
||||||
|
return limitedBody(Buffer.buffer(data, StandardCharsets.UTF_8.name()), null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private RequestBody jsonBody(Object data) {
|
||||||
|
Buffer body = data == null ? Buffer.buffer() : Buffer.buffer(Json.encode(data), StandardCharsets.UTF_8.name());
|
||||||
|
return limitedBody(body, "application/json; charset=utf-8");
|
||||||
|
}
|
||||||
|
|
||||||
|
private RequestBody formBody(Map<String, String> data) {
|
||||||
|
StringBuilder encoded = new StringBuilder();
|
||||||
|
if (data != null) {
|
||||||
|
for (Map.Entry<String, String> entry : data.entrySet()) {
|
||||||
|
if (encoded.length() > 0) {
|
||||||
|
encoded.append('&');
|
||||||
|
}
|
||||||
|
encoded.append(urlEncode(entry.getKey()));
|
||||||
|
encoded.append('=');
|
||||||
|
encoded.append(urlEncode(entry.getValue()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return limitedBody(Buffer.buffer(encoded.toString(), StandardCharsets.UTF_8.name()),
|
||||||
|
"application/x-www-form-urlencoded; charset=utf-8");
|
||||||
|
}
|
||||||
|
|
||||||
|
private RequestBody multipartBody(Map<String, Object> data) {
|
||||||
|
String boundary = "----NetdiskJsHttpClientBoundary" + UUID.randomUUID().toString().replace("-", "");
|
||||||
|
Buffer body = Buffer.buffer();
|
||||||
|
if (data != null) {
|
||||||
|
for (Map.Entry<String, Object> entry : data.entrySet()) {
|
||||||
|
String key = entry.getKey();
|
||||||
|
Object value = entry.getValue();
|
||||||
|
if (key == null || value == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
appendAscii(body, "--" + boundary + "\r\n");
|
||||||
|
if (value instanceof byte[] bytes) {
|
||||||
|
appendAscii(body, "Content-Disposition: form-data; name=\"" + escapeMultipart(key)
|
||||||
|
+ "\"; filename=\"" + escapeMultipart(key) + "\"\r\n");
|
||||||
|
appendAscii(body, "Content-Type: application/octet-stream\r\n\r\n");
|
||||||
|
body.appendBytes(bytes);
|
||||||
|
appendAscii(body, "\r\n");
|
||||||
|
} else if (value instanceof Buffer buffer) {
|
||||||
|
appendAscii(body, "Content-Disposition: form-data; name=\"" + escapeMultipart(key)
|
||||||
|
+ "\"; filename=\"" + escapeMultipart(key) + "\"\r\n");
|
||||||
|
appendAscii(body, "Content-Type: application/octet-stream\r\n\r\n");
|
||||||
|
body.appendBuffer(buffer);
|
||||||
|
appendAscii(body, "\r\n");
|
||||||
|
} else {
|
||||||
|
appendAscii(body, "Content-Disposition: form-data; name=\"" + escapeMultipart(key) + "\"\r\n\r\n");
|
||||||
|
body.appendString(String.valueOf(value), StandardCharsets.UTF_8.name());
|
||||||
|
appendAscii(body, "\r\n");
|
||||||
|
}
|
||||||
|
ensureRequestBodyLimit(body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
appendAscii(body, "--" + boundary + "--\r\n");
|
||||||
|
return limitedBody(body, "multipart/form-data; boundary=" + boundary);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void appendAscii(Buffer body, String value) {
|
||||||
|
body.appendString(value, StandardCharsets.US_ASCII.name());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String escapeMultipart(String value) {
|
||||||
|
return value.replace("\\", "\\\\").replace("\"", "\\\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RequestBody limitedBody(Buffer body, String contentType) {
|
||||||
|
ensureRequestBodyLimit(body);
|
||||||
|
return new RequestBody(body, contentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
private record RequestBody(Buffer body, String contentType) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -573,10 +781,29 @@ public class JsHttpClient {
|
|||||||
*/
|
*/
|
||||||
public static class JsHttpResponse {
|
public static class JsHttpResponse {
|
||||||
|
|
||||||
private final HttpResponse<Buffer> response;
|
private final int statusCode;
|
||||||
|
private final MultiMap headers;
|
||||||
|
private final Buffer body;
|
||||||
|
private final String statusMessage;
|
||||||
|
private final HttpResponse<Buffer> originalResponse;
|
||||||
|
|
||||||
public JsHttpResponse(HttpResponse<Buffer> response) {
|
public JsHttpResponse(HttpResponse<Buffer> response) {
|
||||||
this.response = response;
|
this(
|
||||||
|
response.statusCode(),
|
||||||
|
MultiMap.caseInsensitiveMultiMap().setAll(response.headers()),
|
||||||
|
response.body(),
|
||||||
|
response.statusMessage(),
|
||||||
|
response
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public JsHttpResponse(int statusCode, MultiMap headers, Buffer body, String statusMessage,
|
||||||
|
HttpResponse<Buffer> originalResponse) {
|
||||||
|
this.statusCode = statusCode;
|
||||||
|
this.headers = headers == null ? MultiMap.caseInsensitiveMultiMap() : headers;
|
||||||
|
this.body = body == null ? Buffer.buffer() : body;
|
||||||
|
this.statusMessage = statusMessage;
|
||||||
|
this.originalResponse = originalResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -584,7 +811,7 @@ public class JsHttpClient {
|
|||||||
* @return 响应体字符串
|
* @return 响应体字符串
|
||||||
*/
|
*/
|
||||||
public String body() {
|
public String body() {
|
||||||
return HttpResponseHelper.asText(response);
|
return HttpResponseHelper.asText(body, header(HttpHeaders.CONTENT_ENCODING.toString()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -593,7 +820,7 @@ public class JsHttpClient {
|
|||||||
*/
|
*/
|
||||||
public Object json() {
|
public Object json() {
|
||||||
try {
|
try {
|
||||||
JsonObject jsonObject = HttpResponseHelper.asJson(response);
|
JsonObject jsonObject = HttpResponseHelper.asJson(body, header(HttpHeaders.CONTENT_ENCODING.toString()));
|
||||||
if (jsonObject == null || jsonObject.isEmpty()) {
|
if (jsonObject == null || jsonObject.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -611,7 +838,7 @@ public class JsHttpClient {
|
|||||||
* @return 状态码
|
* @return 状态码
|
||||||
*/
|
*/
|
||||||
public int statusCode() {
|
public int statusCode() {
|
||||||
return response.statusCode();
|
return statusCode;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -620,7 +847,7 @@ public class JsHttpClient {
|
|||||||
* @return 头值
|
* @return 头值
|
||||||
*/
|
*/
|
||||||
public String header(String name) {
|
public String header(String name) {
|
||||||
return response.getHeader(name);
|
return headers.get(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -628,10 +855,9 @@ public class JsHttpClient {
|
|||||||
* @return 响应头Map
|
* @return 响应头Map
|
||||||
*/
|
*/
|
||||||
public Map<String, String> headers() {
|
public Map<String, String> headers() {
|
||||||
MultiMap responseHeaders = response.headers();
|
|
||||||
Map<String, String> result = new HashMap<>();
|
Map<String, String> result = new HashMap<>();
|
||||||
for (String name : responseHeaders.names()) {
|
for (String name : headers.names()) {
|
||||||
result.put(name, responseHeaders.get(name));
|
result.put(name, headers.get(name));
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -649,8 +875,14 @@ public class JsHttpClient {
|
|||||||
* 获取原始响应对象
|
* 获取原始响应对象
|
||||||
* @return HttpResponse对象
|
* @return HttpResponse对象
|
||||||
*/
|
*/
|
||||||
|
@Deprecated
|
||||||
public HttpResponse<Buffer> getOriginalResponse() {
|
public HttpResponse<Buffer> getOriginalResponse() {
|
||||||
return response;
|
if (originalResponse == null) {
|
||||||
|
throw new UnsupportedOperationException(
|
||||||
|
"流式HTTP客户端不再保留原始Vert.x HttpResponse,请使用statusCode/header/headers/body/bodyBytes方法"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return originalResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -658,11 +890,8 @@ public class JsHttpClient {
|
|||||||
* @return 响应体字节数组
|
* @return 响应体字节数组
|
||||||
*/
|
*/
|
||||||
public byte[] bodyBytes() {
|
public byte[] bodyBytes() {
|
||||||
Buffer buffer = response.body();
|
ensureResponseBodyLimit(body);
|
||||||
if (buffer == null) {
|
return body.getBytes();
|
||||||
return new byte[0];
|
|
||||||
}
|
|
||||||
return buffer.getBytes();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -670,11 +899,46 @@ public class JsHttpClient {
|
|||||||
* @return 响应体大小(字节)
|
* @return 响应体大小(字节)
|
||||||
*/
|
*/
|
||||||
public long bodySize() {
|
public long bodySize() {
|
||||||
Buffer buffer = response.body();
|
return body.length();
|
||||||
if (buffer == null) {
|
}
|
||||||
return 0;
|
|
||||||
|
public String statusMessage() {
|
||||||
|
return statusMessage;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭 HttpClient 释放连接池资源
|
||||||
|
* 仅关闭自建的 client(代理模式),共享实例不关闭
|
||||||
|
*/
|
||||||
|
public void close() {
|
||||||
|
if (!closed.compareAndSet(false, true)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
synchronized (requestLock) {
|
||||||
|
for (HttpClientRequest request : activeRequests) {
|
||||||
|
try {
|
||||||
|
request.reset();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("重置 JavaScript HTTP 请求失败: {}", e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return buffer.length();
|
activeRequests.clear();
|
||||||
|
}
|
||||||
|
if (ownClient && client != null) {
|
||||||
|
client.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ensureResponseBodyLimit(Buffer buffer) {
|
||||||
|
if (buffer != null && buffer.length() > MAX_RESPONSE_BODY_BYTES) {
|
||||||
|
throw new IllegalArgumentException("响应体过大: " + buffer.length() + " bytes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ensureRequestBodyLimit(Buffer buffer) {
|
||||||
|
if (buffer != null && buffer.length() > MAX_REQUEST_BODY_BYTES) {
|
||||||
|
throw new IllegalArgumentException("请求体过大: " + buffer.length() + " bytes");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,9 +6,9 @@ import cn.qaiu.entity.ShareLinkInfo;
|
|||||||
import cn.qaiu.parser.IPanTool;
|
import cn.qaiu.parser.IPanTool;
|
||||||
import cn.qaiu.parser.custom.CustomParserConfig;
|
import cn.qaiu.parser.custom.CustomParserConfig;
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
|
import io.vertx.core.Promise;
|
||||||
import io.vertx.core.WorkerExecutor;
|
import io.vertx.core.WorkerExecutor;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
|
||||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@@ -20,6 +20,13 @@ import java.io.InputStreamReader;
|
|||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.ScheduledFuture;
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,21 +36,46 @@ import java.util.stream.Collectors;
|
|||||||
* @author <a href="https://qaiu.top">QAIU</a>
|
* @author <a href="https://qaiu.top">QAIU</a>
|
||||||
* Create at 2025/10/17
|
* Create at 2025/10/17
|
||||||
*/
|
*/
|
||||||
public class JsParserExecutor implements IPanTool {
|
public class JsParserExecutor implements IPanTool, AutoCloseable {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(JsParserExecutor.class);
|
private static final Logger log = LoggerFactory.getLogger(JsParserExecutor.class);
|
||||||
|
|
||||||
private static final WorkerExecutor EXECUTOR = WebClientVertxInit.get().createSharedWorkerExecutor("parser-executor", 32);
|
private static volatile WorkerExecutor EXECUTOR;
|
||||||
|
private static final Object EXECUTOR_LOCK = new Object();
|
||||||
private static String FETCH_RUNTIME_JS = null;
|
private static volatile boolean executorShutdown = false;
|
||||||
|
|
||||||
|
/** 安全网调度器:当 onComplete 未触发时,延迟强制释放资源 */
|
||||||
|
private static final ScheduledExecutorService CLEANUP_SCHEDULER =
|
||||||
|
Executors.newSingleThreadScheduledExecutor(r -> {
|
||||||
|
Thread t = new Thread(r, "js-parser-cleanup-safety");
|
||||||
|
t.setDaemon(true);
|
||||||
|
return t;
|
||||||
|
});
|
||||||
|
private static final long EXECUTION_TIMEOUT_SECONDS = 30;
|
||||||
|
private static final int MAX_RESULT_STRING_LENGTH = 1024 * 1024;
|
||||||
|
private static final int MAX_FILE_LIST_SIZE = 1000;
|
||||||
|
private static final int MAX_FILE_FIELD_LENGTH = 4096;
|
||||||
|
private static final int MAX_CONCURRENT_EXECUTIONS =
|
||||||
|
Math.max(1, Integer.getInteger("parser.custom.js.maxConcurrentExecutions", 32));
|
||||||
|
private static final Semaphore EXECUTION_PERMITS = new Semaphore(MAX_CONCURRENT_EXECUTIONS);
|
||||||
|
|
||||||
|
private static volatile String FETCH_RUNTIME_JS = null;
|
||||||
|
|
||||||
private final CustomParserConfig config;
|
private final CustomParserConfig config;
|
||||||
private final ShareLinkInfo shareLinkInfo;
|
private final ShareLinkInfo shareLinkInfo;
|
||||||
private final ScriptEngine engine;
|
private volatile ScriptEngine engine;
|
||||||
|
private final Object engineLock = new Object();
|
||||||
private final JsHttpClient httpClient;
|
private final JsHttpClient httpClient;
|
||||||
private final JsLogger jsLogger;
|
private final JsLogger jsLogger;
|
||||||
private final JsShareLinkInfoWrapper shareLinkInfoWrapper;
|
private final JsShareLinkInfoWrapper shareLinkInfoWrapper;
|
||||||
private final JsFetchBridge fetchBridge;
|
private final JsFetchBridge fetchBridge;
|
||||||
|
/** 标记是否已释放,防止重复关闭 */
|
||||||
|
private final AtomicBoolean closed = new AtomicBoolean(false);
|
||||||
|
private final Object lifecycleLock = new Object();
|
||||||
|
private volatile boolean running = false;
|
||||||
|
private volatile boolean closeRequested = false;
|
||||||
|
/** 安全网定时任务句柄,正常完成时取消 */
|
||||||
|
private volatile ScheduledFuture<?> safetyCleanupFuture = null;
|
||||||
|
|
||||||
public JsParserExecutor(ShareLinkInfo shareLinkInfo, CustomParserConfig config) {
|
public JsParserExecutor(ShareLinkInfo shareLinkInfo, CustomParserConfig config) {
|
||||||
this.config = config;
|
this.config = config;
|
||||||
@@ -59,7 +91,6 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
this.jsLogger = new JsLogger("JsParser-" + config.getType());
|
this.jsLogger = new JsLogger("JsParser-" + config.getType());
|
||||||
this.shareLinkInfoWrapper = new JsShareLinkInfoWrapper(shareLinkInfo);
|
this.shareLinkInfoWrapper = new JsShareLinkInfoWrapper(shareLinkInfo);
|
||||||
this.fetchBridge = new JsFetchBridge(httpClient);
|
this.fetchBridge = new JsFetchBridge(httpClient);
|
||||||
this.engine = initEngine();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -102,15 +133,8 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
*/
|
*/
|
||||||
private ScriptEngine initEngine() {
|
private ScriptEngine initEngine() {
|
||||||
try {
|
try {
|
||||||
// 使用安全的ClassFilter创建Nashorn引擎
|
ScriptEngine engine = ParserScriptEngine.create();
|
||||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
this.engine = engine;
|
||||||
|
|
||||||
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
|
|
||||||
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
|
|
||||||
|
|
||||||
if (engine == null) {
|
|
||||||
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 注入Java对象到JavaScript环境
|
// 注入Java对象到JavaScript环境
|
||||||
engine.put("http", httpClient);
|
engine.put("http", httpClient);
|
||||||
@@ -118,14 +142,6 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
||||||
engine.put("JavaFetch", fetchBridge);
|
engine.put("JavaFetch", fetchBridge);
|
||||||
|
|
||||||
// 禁用Java对象访问
|
|
||||||
engine.eval("var Java = undefined;");
|
|
||||||
engine.eval("var JavaImporter = undefined;");
|
|
||||||
engine.eval("var Packages = undefined;");
|
|
||||||
engine.eval("var javax = undefined;");
|
|
||||||
engine.eval("var org = undefined;");
|
|
||||||
engine.eval("var com = undefined;");
|
|
||||||
|
|
||||||
// 加载fetch运行时(Promise和fetch API polyfill)
|
// 加载fetch运行时(Promise和fetch API polyfill)
|
||||||
String fetchRuntime = loadFetchRuntime();
|
String fetchRuntime = loadFetchRuntime();
|
||||||
if (!fetchRuntime.isEmpty()) {
|
if (!fetchRuntime.isEmpty()) {
|
||||||
@@ -145,28 +161,207 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
throw new RuntimeException("JavaScript引擎初始化失败: " + e.getMessage(), e);
|
throw new RuntimeException("JavaScript引擎初始化失败: " + e.getMessage(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ScriptEngine engine() {
|
||||||
|
ScriptEngine current = engine;
|
||||||
|
if (current != null) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
synchronized (engineLock) {
|
||||||
|
if (closed.get()) {
|
||||||
|
throw new IllegalStateException("JavaScript解析器已关闭");
|
||||||
|
}
|
||||||
|
if (engine == null) {
|
||||||
|
engine = initEngine();
|
||||||
|
}
|
||||||
|
return engine;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void beginExecution() {
|
||||||
|
synchronized (lifecycleLock) {
|
||||||
|
if (closed.get() || closeRequested) {
|
||||||
|
throw new IllegalStateException("JavaScript解析器已关闭");
|
||||||
|
}
|
||||||
|
if (running) {
|
||||||
|
throw new IllegalStateException("JavaScript解析器已在运行");
|
||||||
|
}
|
||||||
|
running = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishExecution() {
|
||||||
|
synchronized (lifecycleLock) {
|
||||||
|
running = false;
|
||||||
|
if (closeRequested) {
|
||||||
|
doClose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 释放资源(ScriptEngine 和 HttpClient),避免内存泄漏
|
||||||
|
* 幂等:可安全多次调用
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
synchronized (lifecycleLock) {
|
||||||
|
closeRequested = true;
|
||||||
|
cancelSafetyCleanup();
|
||||||
|
if (running || closed.get()) {
|
||||||
|
closeExternalResources();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
doClose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void doClose() {
|
||||||
|
if (!closed.compareAndSet(false, true)) return;
|
||||||
|
closeRequested = false;
|
||||||
|
closeExternalResources();
|
||||||
|
cleanupEngine();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void closeExternalResources() {
|
||||||
|
if (httpClient != null) {
|
||||||
|
httpClient.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cleanupEngine() {
|
||||||
|
// 清除 ScriptEngine 持有的所有引用和内部状态,帮助 GC 回收
|
||||||
|
if (engine != null) {
|
||||||
|
try {
|
||||||
|
engine.put("http", null);
|
||||||
|
engine.put("logger", null);
|
||||||
|
engine.put("shareLinkInfo", null);
|
||||||
|
engine.put("JavaFetch", null);
|
||||||
|
// 彻底清除 ENGINE_SCOPE bindings,释放 JS AST、编译函数、闭包等运行时状态
|
||||||
|
var bindings = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
|
||||||
|
if (bindings != null) {
|
||||||
|
bindings.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("清理 ScriptEngine bindings 失败: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cancelSafetyCleanup() {
|
||||||
|
// 取消安全网定时任务(如果正常完成则无需再触发)
|
||||||
|
if (safetyCleanupFuture != null) {
|
||||||
|
safetyCleanupFuture.cancel(false);
|
||||||
|
safetyCleanupFuture = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭全局 WorkerExecutor 和清理调度器(应在应用关闭时调用)
|
||||||
|
*/
|
||||||
|
public static void shutdownExecutor() {
|
||||||
|
synchronized (EXECUTOR_LOCK) {
|
||||||
|
executorShutdown = true;
|
||||||
|
if (EXECUTOR != null) {
|
||||||
|
EXECUTOR.close();
|
||||||
|
EXECUTOR = null;
|
||||||
|
log.info("JsParserExecutor WorkerExecutor 已关闭");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
CLEANUP_SCHEDULER.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取或创建 WorkerExecutor(懒加载)
|
||||||
|
*/
|
||||||
|
private static WorkerExecutor getExecutor() {
|
||||||
|
synchronized (EXECUTOR_LOCK) {
|
||||||
|
if (executorShutdown) {
|
||||||
|
throw new IllegalStateException("JavaScript解析器 WorkerExecutor 已关闭");
|
||||||
|
}
|
||||||
|
if (EXECUTOR == null) {
|
||||||
|
EXECUTOR = WebClientVertxInit.get().createSharedWorkerExecutor("parser-executor", 32);
|
||||||
|
}
|
||||||
|
return EXECUTOR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> Future<T> executeBlockingWithPermit(String operation, Callable<T> blockingCode) {
|
||||||
|
if (!EXECUTION_PERMITS.tryAcquire()) {
|
||||||
|
String message = "JavaScript " + operation + " 执行并发已满,请稍后重试";
|
||||||
|
jsLogger.error(message);
|
||||||
|
close();
|
||||||
|
return Future.failedFuture(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return getExecutor().executeBlocking(() -> {
|
||||||
|
boolean executionStarted = false;
|
||||||
|
try {
|
||||||
|
beginExecution();
|
||||||
|
executionStarted = true;
|
||||||
|
return blockingCode.call();
|
||||||
|
} finally {
|
||||||
|
if (executionStarted) {
|
||||||
|
finishExecution();
|
||||||
|
}
|
||||||
|
EXECUTION_PERMITS.release();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (Throwable e) {
|
||||||
|
EXECUTION_PERMITS.release();
|
||||||
|
close();
|
||||||
|
return Future.failedFuture(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> Future<T> withTimeout(Future<T> executionFuture, String operation) {
|
||||||
|
Promise<T> promise = Promise.promise();
|
||||||
|
try {
|
||||||
|
safetyCleanupFuture = CLEANUP_SCHEDULER.schedule(() -> {
|
||||||
|
if (promise.tryFail("JavaScript " + operation + " 执行超时(" + EXECUTION_TIMEOUT_SECONDS + "秒)")) {
|
||||||
|
jsLogger.error("{} 执行超时,已停止外部HTTP资源;ScriptEngine将在执行线程退出后清理", operation);
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
}, EXECUTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("安全网调度失败: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
executionFuture.onComplete(ar -> {
|
||||||
|
cancelSafetyCleanup();
|
||||||
|
if (ar.succeeded()) {
|
||||||
|
promise.tryComplete(ar.result());
|
||||||
|
} else {
|
||||||
|
promise.tryFail(ar.cause());
|
||||||
|
}
|
||||||
|
close();
|
||||||
|
});
|
||||||
|
return promise.future();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
jsLogger.info("开始执行JavaScript解析器: {}", config.getType());
|
jsLogger.info("开始执行JavaScript解析器: {}", config.getType());
|
||||||
|
|
||||||
// 使用executeBlocking在工作线程上执行,避免阻塞EventLoop线程
|
// 使用executeBlocking在工作线程上执行,避免阻塞EventLoop线程
|
||||||
return EXECUTOR.executeBlocking(() -> {
|
Future<String> executionFuture = executeBlockingWithPermit("parse", () -> {
|
||||||
|
ScriptEngine engine = engine();
|
||||||
// 直接调用全局parse函数
|
// 直接调用全局parse函数
|
||||||
Object parseFunction = engine.get("parse");
|
Object parseFunction = engine.get("parse");
|
||||||
if (parseFunction == null) {
|
if (parseFunction == null) {
|
||||||
throw new RuntimeException("JavaScript代码中未找到parse函数");
|
throw new RuntimeException("JavaScript代码中未找到parse函数");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parseFunction instanceof ScriptObjectMirror parseMirror) {
|
if (parseFunction instanceof ScriptObjectMirror parseMirror) {
|
||||||
|
|
||||||
Object result = parseMirror.call(null, shareLinkInfoWrapper, httpClient, jsLogger);
|
Object result = parseMirror.call(null, shareLinkInfoWrapper, httpClient, jsLogger);
|
||||||
|
|
||||||
if (result instanceof String) {
|
if (result instanceof String) {
|
||||||
jsLogger.info("解析成功: {}", result);
|
String resultText = limitResultString((String) result, "parse");
|
||||||
return (String) result;
|
jsLogger.info("解析成功,结果长度: {}", resultText.length());
|
||||||
|
return resultText;
|
||||||
} else {
|
} else {
|
||||||
jsLogger.error("parse方法返回值类型错误,期望String,实际: {}",
|
jsLogger.error("parse方法返回值类型错误,期望String,实际: {}",
|
||||||
result != null ? result.getClass().getSimpleName() : "null");
|
result != null ? result.getClass().getSimpleName() : "null");
|
||||||
throw new RuntimeException("parse方法返回值类型错误");
|
throw new RuntimeException("parse方法返回值类型错误");
|
||||||
}
|
}
|
||||||
@@ -174,32 +369,34 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
throw new RuntimeException("parse函数类型错误");
|
throw new RuntimeException("parse函数类型错误");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
return withTimeout(executionFuture, "parse");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Future<List<FileInfo>> parseFileList() {
|
public Future<List<FileInfo>> parseFileList() {
|
||||||
jsLogger.info("开始执行JavaScript文件列表解析: {}", config.getType());
|
jsLogger.info("开始执行JavaScript文件列表解析: {}", config.getType());
|
||||||
|
|
||||||
// 使用executeBlocking在工作线程上执行,避免阻塞EventLoop线程
|
// 使用executeBlocking在工作线程上执行,避免阻塞EventLoop线程
|
||||||
return EXECUTOR.executeBlocking(() -> {
|
Future<List<FileInfo>> executionFuture = executeBlockingWithPermit("parseFileList", () -> {
|
||||||
|
ScriptEngine engine = engine();
|
||||||
// 直接调用全局parseFileList函数
|
// 直接调用全局parseFileList函数
|
||||||
Object parseFileListFunction = engine.get("parseFileList");
|
Object parseFileListFunction = engine.get("parseFileList");
|
||||||
if (parseFileListFunction == null) {
|
if (parseFileListFunction == null) {
|
||||||
throw new RuntimeException("JavaScript代码中未找到parseFileList函数");
|
throw new RuntimeException("JavaScript代码中未找到parseFileList函数");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 调用parseFileList方法
|
// 调用parseFileList方法
|
||||||
if (parseFileListFunction instanceof ScriptObjectMirror parseFileListMirror) {
|
if (parseFileListFunction instanceof ScriptObjectMirror parseFileListMirror) {
|
||||||
|
|
||||||
Object result = parseFileListMirror.call(null, shareLinkInfoWrapper, httpClient, jsLogger);
|
Object result = parseFileListMirror.call(null, shareLinkInfoWrapper, httpClient, jsLogger);
|
||||||
|
|
||||||
if (result instanceof ScriptObjectMirror resultMirror) {
|
if (result instanceof ScriptObjectMirror resultMirror) {
|
||||||
List<FileInfo> fileList = convertToFileInfoList(resultMirror);
|
List<FileInfo> fileList = convertToFileInfoList(resultMirror);
|
||||||
|
|
||||||
jsLogger.info("文件列表解析成功,共 {} 个文件", fileList.size());
|
jsLogger.info("文件列表解析成功,共 {} 个文件", fileList.size());
|
||||||
return fileList;
|
return fileList;
|
||||||
} else {
|
} else {
|
||||||
jsLogger.error("parseFileList方法返回值类型错误,期望数组,实际: {}",
|
jsLogger.error("parseFileList方法返回值类型错误,期望数组,实际: {}",
|
||||||
result != null ? result.getClass().getSimpleName() : "null");
|
result != null ? result.getClass().getSimpleName() : "null");
|
||||||
throw new RuntimeException("parseFileList方法返回值类型错误");
|
throw new RuntimeException("parseFileList方法返回值类型错误");
|
||||||
}
|
}
|
||||||
@@ -207,30 +404,33 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
throw new RuntimeException("parseFileList函数类型错误");
|
throw new RuntimeException("parseFileList函数类型错误");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
return withTimeout(executionFuture, "parseFileList");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Future<String> parseById() {
|
public Future<String> parseById() {
|
||||||
jsLogger.info("开始执行JavaScript按ID解析: {}", config.getType());
|
jsLogger.info("开始执行JavaScript按ID解析: {}", config.getType());
|
||||||
|
|
||||||
// 使用executeBlocking在工作线程上执行,避免阻塞EventLoop线程
|
// 使用executeBlocking在工作线程上执行,避免阻塞EventLoop线程
|
||||||
return EXECUTOR.executeBlocking(() -> {
|
Future<String> executionFuture = executeBlockingWithPermit("parseById", () -> {
|
||||||
|
ScriptEngine engine = engine();
|
||||||
// 直接调用全局parseById函数
|
// 直接调用全局parseById函数
|
||||||
Object parseByIdFunction = engine.get("parseById");
|
Object parseByIdFunction = engine.get("parseById");
|
||||||
if (parseByIdFunction == null) {
|
if (parseByIdFunction == null) {
|
||||||
throw new RuntimeException("JavaScript代码中未找到parseById函数");
|
throw new RuntimeException("JavaScript代码中未找到parseById函数");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 调用parseById方法
|
// 调用parseById方法
|
||||||
if (parseByIdFunction instanceof ScriptObjectMirror parseByIdMirror) {
|
if (parseByIdFunction instanceof ScriptObjectMirror parseByIdMirror) {
|
||||||
|
|
||||||
Object result = parseByIdMirror.call(null, shareLinkInfoWrapper, httpClient, jsLogger);
|
Object result = parseByIdMirror.call(null, shareLinkInfoWrapper, httpClient, jsLogger);
|
||||||
|
|
||||||
if (result instanceof String) {
|
if (result instanceof String) {
|
||||||
jsLogger.info("按ID解析成功: {}", result);
|
String resultText = limitResultString((String) result, "parseById");
|
||||||
return (String) result;
|
jsLogger.info("按ID解析成功,结果长度: {}", resultText.length());
|
||||||
|
return resultText;
|
||||||
} else {
|
} else {
|
||||||
jsLogger.error("parseById方法返回值类型错误,期望String,实际: {}",
|
jsLogger.error("parseById方法返回值类型错误,期望String,实际: {}",
|
||||||
result != null ? result.getClass().getSimpleName() : "null");
|
result != null ? result.getClass().getSimpleName() : "null");
|
||||||
throw new RuntimeException("parseById方法返回值类型错误");
|
throw new RuntimeException("parseById方法返回值类型错误");
|
||||||
}
|
}
|
||||||
@@ -238,6 +438,7 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
throw new RuntimeException("parseById函数类型错误");
|
throw new RuntimeException("parseById函数类型错误");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
return withTimeout(executionFuture, "parseById");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -247,6 +448,9 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
List<FileInfo> fileList = new ArrayList<>();
|
List<FileInfo> fileList = new ArrayList<>();
|
||||||
|
|
||||||
if (resultMirror.isArray()) {
|
if (resultMirror.isArray()) {
|
||||||
|
if (resultMirror.size() > MAX_FILE_LIST_SIZE) {
|
||||||
|
throw new RuntimeException("文件列表数量超过限制: " + resultMirror.size());
|
||||||
|
}
|
||||||
for (int i = 0; i < resultMirror.size(); i++) {
|
for (int i = 0; i < resultMirror.size(); i++) {
|
||||||
Object item = resultMirror.get(String.valueOf(i));
|
Object item = resultMirror.get(String.valueOf(i));
|
||||||
if (item instanceof ScriptObjectMirror) {
|
if (item instanceof ScriptObjectMirror) {
|
||||||
@@ -270,13 +474,13 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
|
|
||||||
// 设置基本字段
|
// 设置基本字段
|
||||||
if (itemMirror.hasMember("fileName")) {
|
if (itemMirror.hasMember("fileName")) {
|
||||||
fileInfo.setFileName(itemMirror.getMember("fileName").toString());
|
fileInfo.setFileName(limitField(itemMirror.getMember("fileName")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("fileId")) {
|
if (itemMirror.hasMember("fileId")) {
|
||||||
fileInfo.setFileId(itemMirror.getMember("fileId").toString());
|
fileInfo.setFileId(limitField(itemMirror.getMember("fileId")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("fileType")) {
|
if (itemMirror.hasMember("fileType")) {
|
||||||
fileInfo.setFileType(itemMirror.getMember("fileType").toString());
|
fileInfo.setFileType(limitField(itemMirror.getMember("fileType")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("size")) {
|
if (itemMirror.hasMember("size")) {
|
||||||
Object size = itemMirror.getMember("size");
|
Object size = itemMirror.getMember("size");
|
||||||
@@ -285,16 +489,16 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("sizeStr")) {
|
if (itemMirror.hasMember("sizeStr")) {
|
||||||
fileInfo.setSizeStr(itemMirror.getMember("sizeStr").toString());
|
fileInfo.setSizeStr(limitField(itemMirror.getMember("sizeStr")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("createTime")) {
|
if (itemMirror.hasMember("createTime")) {
|
||||||
fileInfo.setCreateTime(itemMirror.getMember("createTime").toString());
|
fileInfo.setCreateTime(limitField(itemMirror.getMember("createTime")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("updateTime")) {
|
if (itemMirror.hasMember("updateTime")) {
|
||||||
fileInfo.setUpdateTime(itemMirror.getMember("updateTime").toString());
|
fileInfo.setUpdateTime(limitField(itemMirror.getMember("updateTime")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("createBy")) {
|
if (itemMirror.hasMember("createBy")) {
|
||||||
fileInfo.setCreateBy(itemMirror.getMember("createBy").toString());
|
fileInfo.setCreateBy(limitField(itemMirror.getMember("createBy")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("downloadCount")) {
|
if (itemMirror.hasMember("downloadCount")) {
|
||||||
Object downloadCount = itemMirror.getMember("downloadCount");
|
Object downloadCount = itemMirror.getMember("downloadCount");
|
||||||
@@ -303,16 +507,16 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("fileIcon")) {
|
if (itemMirror.hasMember("fileIcon")) {
|
||||||
fileInfo.setFileIcon(itemMirror.getMember("fileIcon").toString());
|
fileInfo.setFileIcon(limitField(itemMirror.getMember("fileIcon")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("panType")) {
|
if (itemMirror.hasMember("panType")) {
|
||||||
fileInfo.setPanType(itemMirror.getMember("panType").toString());
|
fileInfo.setPanType(limitField(itemMirror.getMember("panType")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("parserUrl")) {
|
if (itemMirror.hasMember("parserUrl")) {
|
||||||
fileInfo.setParserUrl(itemMirror.getMember("parserUrl").toString());
|
fileInfo.setParserUrl(limitField(itemMirror.getMember("parserUrl")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("previewUrl")) {
|
if (itemMirror.hasMember("previewUrl")) {
|
||||||
fileInfo.setPreviewUrl(itemMirror.getMember("previewUrl").toString());
|
fileInfo.setPreviewUrl(limitField(itemMirror.getMember("previewUrl")));
|
||||||
}
|
}
|
||||||
|
|
||||||
return fileInfo;
|
return fileInfo;
|
||||||
@@ -322,4 +526,22 @@ public class JsParserExecutor implements IPanTool {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String limitResultString(String value, String operation) {
|
||||||
|
if (value.length() > MAX_RESULT_STRING_LENGTH) {
|
||||||
|
throw new RuntimeException(operation + " 返回结果过大: " + value.length() + " 字符");
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String limitField(Object value) {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String text = value.toString();
|
||||||
|
if (text.length() > MAX_FILE_FIELD_LENGTH) {
|
||||||
|
throw new RuntimeException("文件字段过长: " + text.length() + " 字符");
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,6 @@ import cn.qaiu.entity.ShareLinkInfo;
|
|||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
import io.vertx.core.Promise;
|
import io.vertx.core.Promise;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
|
||||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@@ -21,20 +20,37 @@ import java.util.concurrent.*;
|
|||||||
*
|
*
|
||||||
* @author <a href="https://qaiu.top">QAIU</a>
|
* @author <a href="https://qaiu.top">QAIU</a>
|
||||||
*/
|
*/
|
||||||
public class JsPlaygroundExecutor {
|
public class JsPlaygroundExecutor implements AutoCloseable {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(JsPlaygroundExecutor.class);
|
private static final Logger log = LoggerFactory.getLogger(JsPlaygroundExecutor.class);
|
||||||
|
|
||||||
// JavaScript执行超时时间(秒)
|
// JavaScript执行超时时间(秒)
|
||||||
private static final long EXECUTION_TIMEOUT_SECONDS = 30;
|
private static final long EXECUTION_TIMEOUT_SECONDS = 30;
|
||||||
|
private static final int MAX_RESULT_STRING_LENGTH = 1024 * 1024;
|
||||||
|
private static final int MAX_FILE_LIST_SIZE = 1000;
|
||||||
|
private static final int MAX_FILE_FIELD_LENGTH = 4096;
|
||||||
|
private static final int TIMEOUT_LOG_RETAIN = 50;
|
||||||
|
|
||||||
// 使用独立的线程池,不受Vert.x的BlockedThreadChecker监控
|
// 使用有界线程池,防止线程无限增长导致内存溢出
|
||||||
private static final ExecutorService INDEPENDENT_EXECUTOR = Executors.newCachedThreadPool(r -> {
|
private static final int POOL_MAX_THREADS = 16;
|
||||||
Thread thread = new Thread(r);
|
private static final int POOL_QUEUE_CAPACITY = 256;
|
||||||
thread.setName("playground-independent-" + System.currentTimeMillis());
|
private static final ExecutorService INDEPENDENT_EXECUTOR = new ThreadPoolExecutor(
|
||||||
thread.setDaemon(true); // 设置为守护线程,服务关闭时自动清理
|
4, POOL_MAX_THREADS, 60L, TimeUnit.SECONDS,
|
||||||
return thread;
|
new ArrayBlockingQueue<>(POOL_QUEUE_CAPACITY),
|
||||||
});
|
r -> {
|
||||||
|
Thread thread = new Thread(r);
|
||||||
|
thread.setName("playground-independent-" + thread.getId());
|
||||||
|
thread.setDaemon(true);
|
||||||
|
return thread;
|
||||||
|
},
|
||||||
|
(r, executor) -> {
|
||||||
|
// 拒绝策略:记录日志并抛出异常,避免阻塞 Vert.x EventLoop
|
||||||
|
log.warn("演练场线程池已满,拒绝任务。活跃线程: {}, 队列大小: {}",
|
||||||
|
((ThreadPoolExecutor) executor).getActiveCount(),
|
||||||
|
((ThreadPoolExecutor) executor).getQueue().size());
|
||||||
|
throw new java.util.concurrent.RejectedExecutionException("演练场线程池已满,请稍后重试");
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// 超时调度线程池,用于处理超时中断
|
// 超时调度线程池,用于处理超时中断
|
||||||
private static final ScheduledExecutorService TIMEOUT_SCHEDULER = Executors.newScheduledThreadPool(2, r -> {
|
private static final ScheduledExecutorService TIMEOUT_SCHEDULER = Executors.newScheduledThreadPool(2, r -> {
|
||||||
@@ -43,14 +59,29 @@ public class JsPlaygroundExecutor {
|
|||||||
thread.setDaemon(true);
|
thread.setDaemon(true);
|
||||||
return thread;
|
return thread;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭静态线程池(应在应用关闭时调用)
|
||||||
|
*/
|
||||||
|
public static void shutdownPools() {
|
||||||
|
INDEPENDENT_EXECUTOR.shutdown();
|
||||||
|
TIMEOUT_SCHEDULER.shutdown();
|
||||||
|
log.info("JsPlaygroundExecutor 线程池已关闭");
|
||||||
|
}
|
||||||
|
|
||||||
private final ShareLinkInfo shareLinkInfo;
|
private final ShareLinkInfo shareLinkInfo;
|
||||||
private final String jsCode;
|
private final String jsCode;
|
||||||
private final ScriptEngine engine;
|
private volatile ScriptEngine engine;
|
||||||
|
private final Object engineLock = new Object();
|
||||||
private final JsHttpClient httpClient;
|
private final JsHttpClient httpClient;
|
||||||
private final JsPlaygroundLogger playgroundLogger;
|
private final JsPlaygroundLogger playgroundLogger;
|
||||||
private final JsShareLinkInfoWrapper shareLinkInfoWrapper;
|
private final JsShareLinkInfoWrapper shareLinkInfoWrapper;
|
||||||
private final JsFetchBridge fetchBridge;
|
private final JsFetchBridge fetchBridge;
|
||||||
|
/** 标记是否已释放,防止重复关闭 */
|
||||||
|
private volatile boolean closed = false;
|
||||||
|
private final Object lifecycleLock = new Object();
|
||||||
|
private volatile boolean running = false;
|
||||||
|
private volatile boolean closeRequested = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建演练场执行器
|
* 创建演练场执行器
|
||||||
@@ -72,7 +103,6 @@ public class JsPlaygroundExecutor {
|
|||||||
this.playgroundLogger = new JsPlaygroundLogger();
|
this.playgroundLogger = new JsPlaygroundLogger();
|
||||||
this.shareLinkInfoWrapper = new JsShareLinkInfoWrapper(shareLinkInfo);
|
this.shareLinkInfoWrapper = new JsShareLinkInfoWrapper(shareLinkInfo);
|
||||||
this.fetchBridge = new JsFetchBridge(httpClient);
|
this.fetchBridge = new JsFetchBridge(httpClient);
|
||||||
this.engine = initEngine();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -80,15 +110,8 @@ public class JsPlaygroundExecutor {
|
|||||||
*/
|
*/
|
||||||
private ScriptEngine initEngine() {
|
private ScriptEngine initEngine() {
|
||||||
try {
|
try {
|
||||||
// 使用安全的ClassFilter创建Nashorn引擎
|
ScriptEngine engine = ParserScriptEngine.create();
|
||||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
this.engine = engine;
|
||||||
|
|
||||||
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
|
|
||||||
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
|
|
||||||
|
|
||||||
if (engine == null) {
|
|
||||||
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 注入Java对象到JavaScript环境
|
// 注入Java对象到JavaScript环境
|
||||||
engine.put("http", httpClient);
|
engine.put("http", httpClient);
|
||||||
@@ -96,14 +119,6 @@ public class JsPlaygroundExecutor {
|
|||||||
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
||||||
engine.put("JavaFetch", fetchBridge);
|
engine.put("JavaFetch", fetchBridge);
|
||||||
|
|
||||||
// 禁用Java对象访问
|
|
||||||
engine.eval("var Java = undefined;");
|
|
||||||
engine.eval("var JavaImporter = undefined;");
|
|
||||||
engine.eval("var Packages = undefined;");
|
|
||||||
engine.eval("var javax = undefined;");
|
|
||||||
engine.eval("var org = undefined;");
|
|
||||||
engine.eval("var com = undefined;");
|
|
||||||
|
|
||||||
// 加载fetch运行时(Promise和fetch API polyfill)
|
// 加载fetch运行时(Promise和fetch API polyfill)
|
||||||
String fetchRuntime = JsParserExecutor.loadFetchRuntime();
|
String fetchRuntime = JsParserExecutor.loadFetchRuntime();
|
||||||
if (!fetchRuntime.isEmpty()) {
|
if (!fetchRuntime.isEmpty()) {
|
||||||
@@ -133,9 +148,14 @@ public class JsPlaygroundExecutor {
|
|||||||
*/
|
*/
|
||||||
public Future<String> executeParseAsync() {
|
public Future<String> executeParseAsync() {
|
||||||
Promise<String> promise = Promise.promise();
|
Promise<String> promise = Promise.promise();
|
||||||
|
|
||||||
// 使用独立的ExecutorService执行,避免Vert.x的BlockedThreadChecker输出警告
|
final CompletableFuture<String> executionFuture;
|
||||||
CompletableFuture<String> executionFuture = CompletableFuture.supplyAsync(() -> {
|
try {
|
||||||
|
// 使用独立的ExecutorService执行,避免Vert.x的BlockedThreadChecker输出警告
|
||||||
|
executionFuture = CompletableFuture.supplyAsync(() -> {
|
||||||
|
beginExecution();
|
||||||
|
try {
|
||||||
|
ScriptEngine engine = engine();
|
||||||
playgroundLogger.infoJava("开始执行parse方法");
|
playgroundLogger.infoJava("开始执行parse方法");
|
||||||
try {
|
try {
|
||||||
Object parseFunction = engine.get("parse");
|
Object parseFunction = engine.get("parse");
|
||||||
@@ -151,8 +171,9 @@ public class JsPlaygroundExecutor {
|
|||||||
log.debug("[JsPlaygroundExecutor] parse函数执行完成,当前日志数量: {}", playgroundLogger.size());
|
log.debug("[JsPlaygroundExecutor] parse函数执行完成,当前日志数量: {}", playgroundLogger.size());
|
||||||
|
|
||||||
if (result instanceof String) {
|
if (result instanceof String) {
|
||||||
playgroundLogger.infoJava("解析成功,返回结果: " + result);
|
String resultText = limitResultString((String) result, "parse");
|
||||||
return (String) result;
|
playgroundLogger.infoJava("解析成功,返回结果长度: " + resultText.length());
|
||||||
|
return resultText;
|
||||||
} else {
|
} else {
|
||||||
String errorMsg = "parse方法返回值类型错误,期望String,实际: " +
|
String errorMsg = "parse方法返回值类型错误,期望String,实际: " +
|
||||||
(result != null ? result.getClass().getSimpleName() : "null");
|
(result != null ? result.getClass().getSimpleName() : "null");
|
||||||
@@ -167,25 +188,27 @@ public class JsPlaygroundExecutor {
|
|||||||
playgroundLogger.errorJava("执行parse方法失败: " + e.getMessage(), e);
|
playgroundLogger.errorJava("执行parse方法失败: " + e.getMessage(), e);
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}, INDEPENDENT_EXECUTOR);
|
} finally {
|
||||||
|
finishExecution();
|
||||||
// 创建超时任务,强制取消执行
|
|
||||||
ScheduledFuture<?> timeoutTask = TIMEOUT_SCHEDULER.schedule(() -> {
|
|
||||||
if (!executionFuture.isDone()) {
|
|
||||||
executionFuture.cancel(true); // 强制中断执行线程
|
|
||||||
playgroundLogger.errorJava("执行超时,已强制中断");
|
|
||||||
log.warn("JavaScript执行超时,已强制取消");
|
|
||||||
}
|
}
|
||||||
}, EXECUTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
}, INDEPENDENT_EXECUTOR);
|
||||||
|
} catch (java.util.concurrent.RejectedExecutionException e) {
|
||||||
|
log.warn("演练场线程池已满,任务被拒绝");
|
||||||
|
close(); // 释放已创建的 ScriptEngine 和 HttpClient 资源
|
||||||
|
promise.fail(new RuntimeException("演练场线程池已满,请稍后重试", e));
|
||||||
|
return promise.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
ScheduledFuture<?> timeoutTask = scheduleTimeout(executionFuture, "parse");
|
||||||
|
|
||||||
// 处理执行结果
|
// 处理执行结果
|
||||||
executionFuture.whenComplete((result, error) -> {
|
executionFuture.whenComplete((result, error) -> {
|
||||||
// 取消超时任务
|
// 取消超时任务
|
||||||
timeoutTask.cancel(false);
|
timeoutTask.cancel(false);
|
||||||
|
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
if (error instanceof CancellationException) {
|
if (error instanceof CancellationException) {
|
||||||
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已强制中断";
|
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已返回超时并停止外部HTTP资源;ScriptEngine将在执行线程退出后清理";
|
||||||
playgroundLogger.errorJava(timeoutMsg);
|
playgroundLogger.errorJava(timeoutMsg);
|
||||||
log.error(timeoutMsg);
|
log.error(timeoutMsg);
|
||||||
promise.fail(new RuntimeException(timeoutMsg));
|
promise.fail(new RuntimeException(timeoutMsg));
|
||||||
@@ -197,10 +220,10 @@ public class JsPlaygroundExecutor {
|
|||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 执行parseFileList方法(异步,带超时控制)
|
* 执行parseFileList方法(异步,带超时控制)
|
||||||
* 使用独立线程池,不受Vert.x BlockedThreadChecker监控
|
* 使用独立线程池,不受Vert.x BlockedThreadChecker监控
|
||||||
@@ -209,9 +232,14 @@ public class JsPlaygroundExecutor {
|
|||||||
*/
|
*/
|
||||||
public Future<List<FileInfo>> executeParseFileListAsync() {
|
public Future<List<FileInfo>> executeParseFileListAsync() {
|
||||||
Promise<List<FileInfo>> promise = Promise.promise();
|
Promise<List<FileInfo>> promise = Promise.promise();
|
||||||
|
|
||||||
// 使用独立的ExecutorService执行,避免Vert.x的BlockedThreadChecker输出警告
|
final CompletableFuture<List<FileInfo>> executionFuture;
|
||||||
CompletableFuture<List<FileInfo>> executionFuture = CompletableFuture.supplyAsync(() -> {
|
try {
|
||||||
|
// 使用独立的ExecutorService执行,避免Vert.x的BlockedThreadChecker输出警告
|
||||||
|
executionFuture = CompletableFuture.supplyAsync(() -> {
|
||||||
|
beginExecution();
|
||||||
|
try {
|
||||||
|
ScriptEngine engine = engine();
|
||||||
playgroundLogger.infoJava("开始执行parseFileList方法");
|
playgroundLogger.infoJava("开始执行parseFileList方法");
|
||||||
try {
|
try {
|
||||||
Object parseFileListFunction = engine.get("parseFileList");
|
Object parseFileListFunction = engine.get("parseFileList");
|
||||||
@@ -242,25 +270,27 @@ public class JsPlaygroundExecutor {
|
|||||||
playgroundLogger.errorJava("执行parseFileList方法失败: " + e.getMessage(), e);
|
playgroundLogger.errorJava("执行parseFileList方法失败: " + e.getMessage(), e);
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}, INDEPENDENT_EXECUTOR);
|
} finally {
|
||||||
|
finishExecution();
|
||||||
// 创建超时任务,强制取消执行
|
|
||||||
ScheduledFuture<?> timeoutTask = TIMEOUT_SCHEDULER.schedule(() -> {
|
|
||||||
if (!executionFuture.isDone()) {
|
|
||||||
executionFuture.cancel(true); // 强制中断执行线程
|
|
||||||
playgroundLogger.errorJava("执行超时,已强制中断");
|
|
||||||
log.warn("JavaScript执行超时,已强制取消");
|
|
||||||
}
|
}
|
||||||
}, EXECUTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
}, INDEPENDENT_EXECUTOR);
|
||||||
|
} catch (java.util.concurrent.RejectedExecutionException e) {
|
||||||
|
log.warn("演练场线程池已满,任务被拒绝");
|
||||||
|
close(); // 释放已创建的 ScriptEngine 和 HttpClient 资源
|
||||||
|
promise.fail(new RuntimeException("演练场线程池已满,请稍后重试", e));
|
||||||
|
return promise.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
ScheduledFuture<?> timeoutTask = scheduleTimeout(executionFuture, "parseFileList");
|
||||||
|
|
||||||
// 处理执行结果
|
// 处理执行结果
|
||||||
executionFuture.whenComplete((result, error) -> {
|
executionFuture.whenComplete((result, error) -> {
|
||||||
// 取消超时任务
|
// 取消超时任务
|
||||||
timeoutTask.cancel(false);
|
timeoutTask.cancel(false);
|
||||||
|
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
if (error instanceof CancellationException) {
|
if (error instanceof CancellationException) {
|
||||||
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已强制中断";
|
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已返回超时并停止外部HTTP资源;ScriptEngine将在执行线程退出后清理";
|
||||||
playgroundLogger.errorJava(timeoutMsg);
|
playgroundLogger.errorJava(timeoutMsg);
|
||||||
log.error(timeoutMsg);
|
log.error(timeoutMsg);
|
||||||
promise.fail(new RuntimeException(timeoutMsg));
|
promise.fail(new RuntimeException(timeoutMsg));
|
||||||
@@ -272,10 +302,10 @@ public class JsPlaygroundExecutor {
|
|||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 执行parseById方法(异步,带超时控制)
|
* 执行parseById方法(异步,带超时控制)
|
||||||
* 使用独立线程池,不受Vert.x BlockedThreadChecker监控
|
* 使用独立线程池,不受Vert.x BlockedThreadChecker监控
|
||||||
@@ -284,9 +314,14 @@ public class JsPlaygroundExecutor {
|
|||||||
*/
|
*/
|
||||||
public Future<String> executeParseByIdAsync() {
|
public Future<String> executeParseByIdAsync() {
|
||||||
Promise<String> promise = Promise.promise();
|
Promise<String> promise = Promise.promise();
|
||||||
|
|
||||||
// 使用独立的ExecutorService执行,避免Vert.x的BlockedThreadChecker输出警告
|
final CompletableFuture<String> executionFuture;
|
||||||
CompletableFuture<String> executionFuture = CompletableFuture.supplyAsync(() -> {
|
try {
|
||||||
|
// 使用独立的ExecutorService执行,避免Vert.x的BlockedThreadChecker输出警告
|
||||||
|
executionFuture = CompletableFuture.supplyAsync(() -> {
|
||||||
|
beginExecution();
|
||||||
|
try {
|
||||||
|
ScriptEngine engine = engine();
|
||||||
playgroundLogger.infoJava("开始执行parseById方法");
|
playgroundLogger.infoJava("开始执行parseById方法");
|
||||||
try {
|
try {
|
||||||
Object parseByIdFunction = engine.get("parseById");
|
Object parseByIdFunction = engine.get("parseById");
|
||||||
@@ -300,8 +335,9 @@ public class JsPlaygroundExecutor {
|
|||||||
Object result = parseByIdMirror.call(null, shareLinkInfoWrapper, httpClient, playgroundLogger);
|
Object result = parseByIdMirror.call(null, shareLinkInfoWrapper, httpClient, playgroundLogger);
|
||||||
|
|
||||||
if (result instanceof String) {
|
if (result instanceof String) {
|
||||||
playgroundLogger.infoJava("按ID解析成功: " + result);
|
String resultText = limitResultString((String) result, "parseById");
|
||||||
return (String) result;
|
playgroundLogger.infoJava("按ID解析成功,返回结果长度: " + resultText.length());
|
||||||
|
return resultText;
|
||||||
} else {
|
} else {
|
||||||
String errorMsg = "parseById方法返回值类型错误,期望String,实际: " +
|
String errorMsg = "parseById方法返回值类型错误,期望String,实际: " +
|
||||||
(result != null ? result.getClass().getSimpleName() : "null");
|
(result != null ? result.getClass().getSimpleName() : "null");
|
||||||
@@ -316,25 +352,27 @@ public class JsPlaygroundExecutor {
|
|||||||
playgroundLogger.errorJava("执行parseById方法失败: " + e.getMessage(), e);
|
playgroundLogger.errorJava("执行parseById方法失败: " + e.getMessage(), e);
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}, INDEPENDENT_EXECUTOR);
|
} finally {
|
||||||
|
finishExecution();
|
||||||
// 创建超时任务,强制取消执行
|
|
||||||
ScheduledFuture<?> timeoutTask = TIMEOUT_SCHEDULER.schedule(() -> {
|
|
||||||
if (!executionFuture.isDone()) {
|
|
||||||
executionFuture.cancel(true); // 强制中断执行线程
|
|
||||||
playgroundLogger.errorJava("执行超时,已强制中断");
|
|
||||||
log.warn("JavaScript执行超时,已强制取消");
|
|
||||||
}
|
}
|
||||||
}, EXECUTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
}, INDEPENDENT_EXECUTOR);
|
||||||
|
} catch (java.util.concurrent.RejectedExecutionException e) {
|
||||||
|
log.warn("演练场线程池已满,任务被拒绝");
|
||||||
|
close(); // 释放已创建的 ScriptEngine 和 HttpClient 资源
|
||||||
|
promise.fail(new RuntimeException("演练场线程池已满,请稍后重试", e));
|
||||||
|
return promise.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
ScheduledFuture<?> timeoutTask = scheduleTimeout(executionFuture, "parseById");
|
||||||
|
|
||||||
// 处理执行结果
|
// 处理执行结果
|
||||||
executionFuture.whenComplete((result, error) -> {
|
executionFuture.whenComplete((result, error) -> {
|
||||||
// 取消超时任务
|
// 取消超时任务
|
||||||
timeoutTask.cancel(false);
|
timeoutTask.cancel(false);
|
||||||
|
|
||||||
if (error != null) {
|
if (error != null) {
|
||||||
if (error instanceof CancellationException) {
|
if (error instanceof CancellationException) {
|
||||||
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已强制中断";
|
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已返回超时并停止外部HTTP资源;ScriptEngine将在执行线程退出后清理";
|
||||||
playgroundLogger.errorJava(timeoutMsg);
|
playgroundLogger.errorJava(timeoutMsg);
|
||||||
log.error(timeoutMsg);
|
log.error(timeoutMsg);
|
||||||
promise.fail(new RuntimeException(timeoutMsg));
|
promise.fail(new RuntimeException(timeoutMsg));
|
||||||
@@ -346,7 +384,7 @@ public class JsPlaygroundExecutor {
|
|||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -355,7 +393,7 @@ public class JsPlaygroundExecutor {
|
|||||||
*/
|
*/
|
||||||
public List<JsPlaygroundLogger.LogEntry> getLogs() {
|
public List<JsPlaygroundLogger.LogEntry> getLogs() {
|
||||||
List<JsPlaygroundLogger.LogEntry> logs = playgroundLogger.getLogs();
|
List<JsPlaygroundLogger.LogEntry> logs = playgroundLogger.getLogs();
|
||||||
System.out.println("[JsPlaygroundExecutor] 获取日志,数量: " + logs.size());
|
log.debug("获取日志,数量: {}", logs.size());
|
||||||
return logs;
|
return logs;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -373,6 +411,9 @@ public class JsPlaygroundExecutor {
|
|||||||
List<FileInfo> fileList = new ArrayList<>();
|
List<FileInfo> fileList = new ArrayList<>();
|
||||||
|
|
||||||
if (resultMirror.isArray()) {
|
if (resultMirror.isArray()) {
|
||||||
|
if (resultMirror.size() > MAX_FILE_LIST_SIZE) {
|
||||||
|
throw new RuntimeException("文件列表数量超过限制: " + resultMirror.size());
|
||||||
|
}
|
||||||
for (int i = 0; i < resultMirror.size(); i++) {
|
for (int i = 0; i < resultMirror.size(); i++) {
|
||||||
Object item = resultMirror.get(String.valueOf(i));
|
Object item = resultMirror.get(String.valueOf(i));
|
||||||
if (item instanceof ScriptObjectMirror) {
|
if (item instanceof ScriptObjectMirror) {
|
||||||
@@ -396,13 +437,13 @@ public class JsPlaygroundExecutor {
|
|||||||
|
|
||||||
// 设置基本字段
|
// 设置基本字段
|
||||||
if (itemMirror.hasMember("fileName")) {
|
if (itemMirror.hasMember("fileName")) {
|
||||||
fileInfo.setFileName(itemMirror.getMember("fileName").toString());
|
fileInfo.setFileName(limitField(itemMirror.getMember("fileName")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("fileId")) {
|
if (itemMirror.hasMember("fileId")) {
|
||||||
fileInfo.setFileId(itemMirror.getMember("fileId").toString());
|
fileInfo.setFileId(limitField(itemMirror.getMember("fileId")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("fileType")) {
|
if (itemMirror.hasMember("fileType")) {
|
||||||
fileInfo.setFileType(itemMirror.getMember("fileType").toString());
|
fileInfo.setFileType(limitField(itemMirror.getMember("fileType")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("size")) {
|
if (itemMirror.hasMember("size")) {
|
||||||
Object size = itemMirror.getMember("size");
|
Object size = itemMirror.getMember("size");
|
||||||
@@ -411,16 +452,16 @@ public class JsPlaygroundExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("sizeStr")) {
|
if (itemMirror.hasMember("sizeStr")) {
|
||||||
fileInfo.setSizeStr(itemMirror.getMember("sizeStr").toString());
|
fileInfo.setSizeStr(limitField(itemMirror.getMember("sizeStr")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("createTime")) {
|
if (itemMirror.hasMember("createTime")) {
|
||||||
fileInfo.setCreateTime(itemMirror.getMember("createTime").toString());
|
fileInfo.setCreateTime(limitField(itemMirror.getMember("createTime")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("updateTime")) {
|
if (itemMirror.hasMember("updateTime")) {
|
||||||
fileInfo.setUpdateTime(itemMirror.getMember("updateTime").toString());
|
fileInfo.setUpdateTime(limitField(itemMirror.getMember("updateTime")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("createBy")) {
|
if (itemMirror.hasMember("createBy")) {
|
||||||
fileInfo.setCreateBy(itemMirror.getMember("createBy").toString());
|
fileInfo.setCreateBy(limitField(itemMirror.getMember("createBy")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("downloadCount")) {
|
if (itemMirror.hasMember("downloadCount")) {
|
||||||
Object downloadCount = itemMirror.getMember("downloadCount");
|
Object downloadCount = itemMirror.getMember("downloadCount");
|
||||||
@@ -429,24 +470,154 @@ public class JsPlaygroundExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("fileIcon")) {
|
if (itemMirror.hasMember("fileIcon")) {
|
||||||
fileInfo.setFileIcon(itemMirror.getMember("fileIcon").toString());
|
fileInfo.setFileIcon(limitField(itemMirror.getMember("fileIcon")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("panType")) {
|
if (itemMirror.hasMember("panType")) {
|
||||||
fileInfo.setPanType(itemMirror.getMember("panType").toString());
|
fileInfo.setPanType(limitField(itemMirror.getMember("panType")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("parserUrl")) {
|
if (itemMirror.hasMember("parserUrl")) {
|
||||||
fileInfo.setParserUrl(itemMirror.getMember("parserUrl").toString());
|
fileInfo.setParserUrl(limitField(itemMirror.getMember("parserUrl")));
|
||||||
}
|
}
|
||||||
if (itemMirror.hasMember("previewUrl")) {
|
if (itemMirror.hasMember("previewUrl")) {
|
||||||
fileInfo.setPreviewUrl(itemMirror.getMember("previewUrl").toString());
|
fileInfo.setPreviewUrl(limitField(itemMirror.getMember("previewUrl")));
|
||||||
}
|
}
|
||||||
|
|
||||||
return fileInfo;
|
return fileInfo;
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
playgroundLogger.errorJava("转换FileInfo对象失败", e);
|
playgroundLogger.errorJava("转换FileInfo对象失败", e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static String limitResultString(String value, String operation) {
|
||||||
|
if (value.length() > MAX_RESULT_STRING_LENGTH) {
|
||||||
|
throw new RuntimeException(operation + " 返回结果过大: " + value.length() + " 字符");
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String limitField(Object value) {
|
||||||
|
if (value == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String text = value.toString();
|
||||||
|
if (text.length() > MAX_FILE_FIELD_LENGTH) {
|
||||||
|
throw new RuntimeException("文件字段过长: " + text.length() + " 字符");
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void beginExecution() {
|
||||||
|
synchronized (lifecycleLock) {
|
||||||
|
if (closed) {
|
||||||
|
throw new CancellationException("演练场执行器已关闭");
|
||||||
|
}
|
||||||
|
if (running) {
|
||||||
|
throw new IllegalStateException("演练场执行器已在运行");
|
||||||
|
}
|
||||||
|
running = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ScriptEngine engine() {
|
||||||
|
ScriptEngine current = engine;
|
||||||
|
if (current != null) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
synchronized (engineLock) {
|
||||||
|
if (closed) {
|
||||||
|
throw new CancellationException("演练场执行器已关闭");
|
||||||
|
}
|
||||||
|
if (engine == null) {
|
||||||
|
engine = initEngine();
|
||||||
|
}
|
||||||
|
return engine;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishExecution() {
|
||||||
|
synchronized (lifecycleLock) {
|
||||||
|
running = false;
|
||||||
|
if (closeRequested) {
|
||||||
|
doClose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ScheduledFuture<?> scheduleTimeout(CompletableFuture<?> executionFuture, String operation) {
|
||||||
|
// cancel(true) 只能请求中断,Nashorn 死循环不保证立即停止。
|
||||||
|
return TIMEOUT_SCHEDULER.schedule(() -> {
|
||||||
|
if (!executionFuture.isDone()) {
|
||||||
|
executionFuture.cancel(true);
|
||||||
|
playgroundLogger.errorJava(operation + " 执行超时,已请求取消并停止外部HTTP资源");
|
||||||
|
forceCloseAfterTimeout();
|
||||||
|
log.warn("JavaScript {} 执行超时,已请求取消;Nashorn长循环可能继续占用线程,ScriptEngine将在执行线程退出后清理", operation);
|
||||||
|
}
|
||||||
|
}, EXECUTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void forceCloseAfterTimeout() {
|
||||||
|
synchronized (lifecycleLock) {
|
||||||
|
closeRequested = true;
|
||||||
|
if (running || closed) {
|
||||||
|
closeExternalResources();
|
||||||
|
} else {
|
||||||
|
doClose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
playgroundLogger.trimToLast(TIMEOUT_LOG_RETAIN);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 释放资源(HttpClient 和 ScriptEngine),避免内存泄漏
|
||||||
|
* 幂等:可安全多次调用
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
synchronized (lifecycleLock) {
|
||||||
|
closeRequested = true;
|
||||||
|
if (running || closed) {
|
||||||
|
closeExternalResources();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
doClose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void doClose() {
|
||||||
|
if (closed) return;
|
||||||
|
closed = true;
|
||||||
|
closeRequested = false;
|
||||||
|
closeExternalResources();
|
||||||
|
cleanupEngine();
|
||||||
|
log.debug("JsPlaygroundExecutor 资源已释放");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void closeExternalResources() {
|
||||||
|
if (httpClient != null) {
|
||||||
|
httpClient.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cleanupEngine() {
|
||||||
|
// 清除 ScriptEngine 的所有 bindings,释放 JS 运行时引用
|
||||||
|
if (engine != null) {
|
||||||
|
try {
|
||||||
|
// 清除注入的 Java 对象引用
|
||||||
|
engine.put("http", null);
|
||||||
|
engine.put("logger", null);
|
||||||
|
engine.put("shareLinkInfo", null);
|
||||||
|
engine.put("JavaFetch", null);
|
||||||
|
// 清除所有 ENGINE_SCOPE bindings,包括 eval 加载的 JS 函数
|
||||||
|
var bindings = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
|
||||||
|
if (bindings != null) {
|
||||||
|
bindings.clear();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("清理 ScriptEngine bindings 失败: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4,6 +4,9 @@ import java.util.ArrayList;
|
|||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 演练场日志收集器
|
* 演练场日志收集器
|
||||||
* 收集JavaScript执行过程中的日志信息
|
* 收集JavaScript执行过程中的日志信息
|
||||||
@@ -12,8 +15,12 @@ import java.util.List;
|
|||||||
* @author <a href="https://qaiu.top">QAIU</a>
|
* @author <a href="https://qaiu.top">QAIU</a>
|
||||||
*/
|
*/
|
||||||
public class JsPlaygroundLogger {
|
public class JsPlaygroundLogger {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(JsPlaygroundLogger.class);
|
||||||
|
|
||||||
// 使用线程安全的列表
|
// 使用线程安全的列表
|
||||||
|
private static final int MAX_LOG_SIZE = 1000;
|
||||||
|
private static final int MAX_LOG_MESSAGE_LENGTH = 4096;
|
||||||
private final List<LogEntry> logs = Collections.synchronizedList(new ArrayList<>());
|
private final List<LogEntry> logs = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -56,9 +63,25 @@ public class JsPlaygroundLogger {
|
|||||||
if (obj == null) {
|
if (obj == null) {
|
||||||
return "null";
|
return "null";
|
||||||
}
|
}
|
||||||
return obj.toString();
|
String msg = obj.toString();
|
||||||
|
if (msg.length() <= MAX_LOG_MESSAGE_LENGTH) {
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
return msg.substring(0, MAX_LOG_MESSAGE_LENGTH) + "...[truncated]";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 添加日志条目,超过最大容量时移除最早的条目
|
||||||
|
*/
|
||||||
|
private void addLog(LogEntry entry) {
|
||||||
|
synchronized (logs) {
|
||||||
|
if (logs.size() >= MAX_LOG_SIZE) {
|
||||||
|
logs.remove(0);
|
||||||
|
}
|
||||||
|
logs.add(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 记录日志(内部方法)
|
* 记录日志(内部方法)
|
||||||
* @param level 日志级别
|
* @param level 日志级别
|
||||||
@@ -67,8 +90,8 @@ public class JsPlaygroundLogger {
|
|||||||
*/
|
*/
|
||||||
private void log(String level, Object message, String source) {
|
private void log(String level, Object message, String source) {
|
||||||
String msg = toString(message);
|
String msg = toString(message);
|
||||||
logs.add(new LogEntry(level, msg, source));
|
addLog(new LogEntry(level, msg, source));
|
||||||
System.out.println("[" + source + "PlaygroundLogger] " + level + ": " + msg);
|
log.debug("[{}PlaygroundLogger] {}: {}", source, level, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -109,10 +132,10 @@ public class JsPlaygroundLogger {
|
|||||||
public void error(Object message, Throwable throwable) {
|
public void error(Object message, Throwable throwable) {
|
||||||
String msg = toString(message);
|
String msg = toString(message);
|
||||||
if (throwable != null) {
|
if (throwable != null) {
|
||||||
msg = msg + ": " + throwable.getMessage();
|
msg = toString(msg + ": " + throwable.getMessage());
|
||||||
}
|
}
|
||||||
logs.add(new LogEntry("ERROR", msg, "JS"));
|
addLog(new LogEntry("ERROR", msg, "JS"));
|
||||||
System.out.println("[JSPlaygroundLogger] ERROR: " + msg);
|
log.debug("[JSPlaygroundLogger] ERROR: {}", msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 以下是供Java层调用的内部方法 =====
|
// ===== 以下是供Java层调用的内部方法 =====
|
||||||
@@ -149,12 +172,12 @@ public class JsPlaygroundLogger {
|
|||||||
* 错误日志(带异常,供Java层调用)
|
* 错误日志(带异常,供Java层调用)
|
||||||
*/
|
*/
|
||||||
public void errorJava(String message, Throwable throwable) {
|
public void errorJava(String message, Throwable throwable) {
|
||||||
String msg = message;
|
String msg = toString(message);
|
||||||
if (throwable != null) {
|
if (throwable != null) {
|
||||||
msg = msg + ": " + throwable.getMessage();
|
msg = toString(msg + ": " + throwable.getMessage());
|
||||||
}
|
}
|
||||||
logs.add(new LogEntry("ERROR", msg, "JAVA"));
|
addLog(new LogEntry("ERROR", msg, "JAVA"));
|
||||||
System.out.println("[JAVAPlaygroundLogger] ERROR: " + msg);
|
log.debug("[JAVAPlaygroundLogger] ERROR: {}", msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -179,4 +202,17 @@ public class JsPlaygroundLogger {
|
|||||||
public void clear() {
|
public void clear() {
|
||||||
logs.clear();
|
logs.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void trimToLast(int maxEntries) {
|
||||||
|
if (maxEntries < 0) {
|
||||||
|
throw new IllegalArgumentException("maxEntries不能小于0");
|
||||||
|
}
|
||||||
|
synchronized (logs) {
|
||||||
|
int removeCount = logs.size() - maxEntries;
|
||||||
|
if (removeCount <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
logs.subList(0, removeCount).clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -31,6 +31,8 @@ public class JsScriptLoader {
|
|||||||
|
|
||||||
private static final String RESOURCE_PATH = "custom-parsers";
|
private static final String RESOURCE_PATH = "custom-parsers";
|
||||||
private static final String EXTERNAL_PATH = "./custom-parsers";
|
private static final String EXTERNAL_PATH = "./custom-parsers";
|
||||||
|
private static final long MAX_SCRIPT_SIZE_BYTES = 128 * 1024;
|
||||||
|
private static final int MAX_EXTERNAL_SCRIPT_COUNT = 100;
|
||||||
|
|
||||||
// 系统属性配置的外部目录路径
|
// 系统属性配置的外部目录路径
|
||||||
private static final String EXTERNAL_PATH_PROPERTY = "parser.custom-parsers.path";
|
private static final String EXTERNAL_PATH_PROPERTY = "parser.custom-parsers.path";
|
||||||
@@ -81,14 +83,16 @@ public class JsScriptLoader {
|
|||||||
try {
|
try {
|
||||||
InputStream inputStream = JsScriptLoader.class.getClassLoader()
|
InputStream inputStream = JsScriptLoader.class.getClassLoader()
|
||||||
.getResourceAsStream(resourceFile);
|
.getResourceAsStream(resourceFile);
|
||||||
|
|
||||||
if (inputStream != null) {
|
if (inputStream != null) {
|
||||||
String jsCode = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
|
try (inputStream) {
|
||||||
CustomParserConfig config = JsScriptMetadataParser.parseScript(jsCode);
|
String jsCode = readResourceScript(inputStream, resourceFile);
|
||||||
configs.add(config);
|
CustomParserConfig config = JsScriptMetadataParser.parseScript(jsCode);
|
||||||
|
configs.add(config);
|
||||||
String fileName = resourceFile.substring(resourceFile.lastIndexOf('/') + 1);
|
|
||||||
log.debug("从资源目录加载脚本: {}", fileName);
|
String fileName = resourceFile.substring(resourceFile.lastIndexOf('/') + 1);
|
||||||
|
log.debug("从资源目录加载脚本: {}", fileName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("加载资源脚本失败: {}", resourceFile, e);
|
log.warn("加载资源脚本失败: {}", resourceFile, e);
|
||||||
@@ -139,21 +143,20 @@ public class JsScriptLoader {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
String jarPath = jarUrl.getPath().substring(5, jarUrl.getPath().indexOf("!"));
|
String jarPath = jarUrl.getPath().substring(5, jarUrl.getPath().indexOf("!"));
|
||||||
JarFile jarFile = new JarFile(jarPath);
|
|
||||||
|
try (JarFile jarFile = new JarFile(jarPath)) {
|
||||||
Enumeration<JarEntry> entries = jarFile.entries();
|
Enumeration<JarEntry> entries = jarFile.entries();
|
||||||
while (entries.hasMoreElements()) {
|
while (entries.hasMoreElements()) {
|
||||||
JarEntry entry = entries.nextElement();
|
JarEntry entry = entries.nextElement();
|
||||||
String entryName = entry.getName();
|
String entryName = entry.getName();
|
||||||
|
|
||||||
if (entryName.startsWith(RESOURCE_PATH + "/") &&
|
if (entryName.startsWith(RESOURCE_PATH + "/") &&
|
||||||
entryName.endsWith(".js") &&
|
entryName.endsWith(".js") &&
|
||||||
!isExcludedFile(entryName.substring(entryName.lastIndexOf('/') + 1))) {
|
!isExcludedFile(entryName.substring(entryName.lastIndexOf('/') + 1))) {
|
||||||
resourceFiles.add(entryName);
|
resourceFiles.add(entryName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
jarFile.close();
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.debug("解析JAR包资源文件失败", e);
|
log.debug("解析JAR包资源文件失败", e);
|
||||||
}
|
}
|
||||||
@@ -208,8 +211,10 @@ public class JsScriptLoader {
|
|||||||
paths.filter(Files::isRegularFile)
|
paths.filter(Files::isRegularFile)
|
||||||
.filter(path -> path.toString().endsWith(".js"))
|
.filter(path -> path.toString().endsWith(".js"))
|
||||||
.filter(path -> !isExcludedFile(path.getFileName().toString()))
|
.filter(path -> !isExcludedFile(path.getFileName().toString()))
|
||||||
|
.limit(MAX_EXTERNAL_SCRIPT_COUNT)
|
||||||
.forEach(path -> {
|
.forEach(path -> {
|
||||||
try {
|
try {
|
||||||
|
ensureScriptSize(path);
|
||||||
String jsCode = Files.readString(path, StandardCharsets.UTF_8);
|
String jsCode = Files.readString(path, StandardCharsets.UTF_8);
|
||||||
CustomParserConfig config = JsScriptMetadataParser.parseScript(jsCode);
|
CustomParserConfig config = JsScriptMetadataParser.parseScript(jsCode);
|
||||||
configs.add(config);
|
configs.add(config);
|
||||||
@@ -263,6 +268,7 @@ public class JsScriptLoader {
|
|||||||
throw new IllegalArgumentException("文件不存在: " + filePath);
|
throw new IllegalArgumentException("文件不存在: " + filePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ensureScriptSize(path);
|
||||||
String jsCode = Files.readString(path, StandardCharsets.UTF_8);
|
String jsCode = Files.readString(path, StandardCharsets.UTF_8);
|
||||||
return JsScriptMetadataParser.parseScript(jsCode);
|
return JsScriptMetadataParser.parseScript(jsCode);
|
||||||
|
|
||||||
@@ -280,14 +286,16 @@ public class JsScriptLoader {
|
|||||||
try {
|
try {
|
||||||
InputStream inputStream = JsScriptLoader.class.getClassLoader()
|
InputStream inputStream = JsScriptLoader.class.getClassLoader()
|
||||||
.getResourceAsStream(resourcePath);
|
.getResourceAsStream(resourcePath);
|
||||||
|
|
||||||
if (inputStream == null) {
|
if (inputStream == null) {
|
||||||
throw new IllegalArgumentException("资源文件不存在: " + resourcePath);
|
throw new IllegalArgumentException("资源文件不存在: " + resourcePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
String jsCode = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
|
try (inputStream) {
|
||||||
return JsScriptMetadataParser.parseScript(jsCode);
|
String jsCode = readResourceScript(inputStream, resourcePath);
|
||||||
|
return JsScriptMetadataParser.parseScript(jsCode);
|
||||||
|
}
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new RuntimeException("读取资源文件失败: " + resourcePath, e);
|
throw new RuntimeException("读取资源文件失败: " + resourcePath, e);
|
||||||
}
|
}
|
||||||
@@ -347,4 +355,19 @@ public class JsScriptLoader {
|
|||||||
fileName.contains(".test.") ||
|
fileName.contains(".test.") ||
|
||||||
fileName.contains(".spec.");
|
fileName.contains(".spec.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static void ensureScriptSize(Path path) throws IOException {
|
||||||
|
long size = Files.size(path);
|
||||||
|
if (size > MAX_SCRIPT_SIZE_BYTES) {
|
||||||
|
throw new IllegalArgumentException("JavaScript脚本超过128KB限制: " + path.getFileName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String readResourceScript(InputStream inputStream, String name) throws IOException {
|
||||||
|
byte[] bytes = inputStream.readNBytes((int) MAX_SCRIPT_SIZE_BYTES + 1);
|
||||||
|
if (bytes.length > MAX_SCRIPT_SIZE_BYTES) {
|
||||||
|
throw new IllegalArgumentException("JavaScript资源脚本超过128KB限制: " + name);
|
||||||
|
}
|
||||||
|
return new String(bytes, StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package cn.qaiu.parser.customjs;
|
||||||
|
|
||||||
|
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||||
|
|
||||||
|
import javax.script.ScriptEngine;
|
||||||
|
import javax.script.ScriptException;
|
||||||
|
|
||||||
|
final class ParserScriptEngine {
|
||||||
|
private ParserScriptEngine() {}
|
||||||
|
|
||||||
|
static ScriptEngine create() throws ScriptException {
|
||||||
|
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
|
||||||
|
new String[]{"--no-java"}, null, new SecurityClassFilter());
|
||||||
|
// Remove host loaders and scripting-context globals before binding the parser APIs.
|
||||||
|
engine.eval("""
|
||||||
|
(function (global) {
|
||||||
|
["load", "loadWithNewGlobal", "exit", "quit", "engine", "context",
|
||||||
|
"Java", "JavaImporter", "Packages", "java", "javax", "javafx", "org",
|
||||||
|
"com", "edu"].forEach(function (name) {
|
||||||
|
Object.defineProperty(global, name, {
|
||||||
|
value: void 0, writable: false, configurable: false
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})(this);
|
||||||
|
""");
|
||||||
|
return engine;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,118 +1,11 @@
|
|||||||
package cn.qaiu.parser.customjs;
|
package cn.qaiu.parser.customjs;
|
||||||
|
|
||||||
import org.openjdk.nashorn.api.scripting.ClassFilter;
|
import org.openjdk.nashorn.api.scripting.ClassFilter;
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
/**
|
/** Scripts work through the supplied parser APIs and may not resolve Java classes by name. */
|
||||||
* JavaScript执行器安全类过滤器
|
|
||||||
* 用于限制JavaScript代码可以访问的Java类,防止恶意代码执行危险操作
|
|
||||||
*
|
|
||||||
* @author <a href="https://qaiu.top">QAIU</a>
|
|
||||||
*/
|
|
||||||
public class SecurityClassFilter implements ClassFilter {
|
public class SecurityClassFilter implements ClassFilter {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(SecurityClassFilter.class);
|
|
||||||
|
|
||||||
// 危险类黑名单
|
|
||||||
private static final String[] DANGEROUS_CLASSES = {
|
|
||||||
// 系统命令执行
|
|
||||||
"java.lang.Runtime",
|
|
||||||
"java.lang.ProcessBuilder",
|
|
||||||
"java.lang.Process",
|
|
||||||
|
|
||||||
// 文件系统访问
|
|
||||||
"java.io.File",
|
|
||||||
"java.io.FileInputStream",
|
|
||||||
"java.io.FileOutputStream",
|
|
||||||
"java.io.FileReader",
|
|
||||||
"java.io.FileWriter",
|
|
||||||
"java.io.RandomAccessFile",
|
|
||||||
"java.nio.file.Files",
|
|
||||||
"java.nio.file.Paths",
|
|
||||||
"java.nio.file.Path",
|
|
||||||
"java.nio.channels.FileChannel",
|
|
||||||
|
|
||||||
// 系统访问
|
|
||||||
"java.lang.System",
|
|
||||||
"java.lang.SecurityManager",
|
|
||||||
|
|
||||||
// 反射相关
|
|
||||||
"java.lang.Class",
|
|
||||||
"java.lang.reflect.Method",
|
|
||||||
"java.lang.reflect.Field",
|
|
||||||
"java.lang.reflect.Constructor",
|
|
||||||
"java.lang.reflect.AccessibleObject",
|
|
||||||
"java.lang.ClassLoader",
|
|
||||||
|
|
||||||
// 网络访问
|
|
||||||
"java.net.Socket",
|
|
||||||
"java.net.ServerSocket",
|
|
||||||
"java.net.DatagramSocket",
|
|
||||||
"java.net.URL",
|
|
||||||
"java.net.URLConnection",
|
|
||||||
"java.net.HttpURLConnection",
|
|
||||||
"java.net.InetAddress",
|
|
||||||
|
|
||||||
// 线程和并发
|
|
||||||
"java.lang.Thread",
|
|
||||||
"java.lang.ThreadGroup",
|
|
||||||
"java.util.concurrent.Executor",
|
|
||||||
"java.util.concurrent.ExecutorService",
|
|
||||||
|
|
||||||
// 数据库访问
|
|
||||||
"java.sql.Connection",
|
|
||||||
"java.sql.Statement",
|
|
||||||
"java.sql.PreparedStatement",
|
|
||||||
"java.sql.DriverManager",
|
|
||||||
|
|
||||||
// 脚本引擎(防止嵌套执行)
|
|
||||||
"javax.script.ScriptEngine",
|
|
||||||
"javax.script.ScriptEngineManager",
|
|
||||||
|
|
||||||
// JVM控制
|
|
||||||
"java.lang.invoke.MethodHandle",
|
|
||||||
"sun.misc.Unsafe",
|
|
||||||
|
|
||||||
// Nashorn内部类
|
|
||||||
"jdk.nashorn.internal",
|
|
||||||
"jdk.internal",
|
|
||||||
};
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean exposeToScripts(String className) {
|
public boolean exposeToScripts(String className) {
|
||||||
// 检查是否在黑名单中
|
return false;
|
||||||
for (String dangerous : DANGEROUS_CLASSES) {
|
|
||||||
if (className.equals(dangerous) || className.startsWith(dangerous + ".")) {
|
|
||||||
log.warn("🔒 安全拦截: JavaScript尝试访问危险类 - {}", className);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 额外的包级别限制
|
|
||||||
String[] dangerousPackages = {
|
|
||||||
"java.lang.reflect.",
|
|
||||||
"java.io.",
|
|
||||||
"java.nio.",
|
|
||||||
"java.net.",
|
|
||||||
"java.sql.",
|
|
||||||
"javax.script.",
|
|
||||||
"sun.",
|
|
||||||
"jdk.internal.",
|
|
||||||
"jdk.nashorn.internal."
|
|
||||||
};
|
|
||||||
|
|
||||||
for (String pkg : dangerousPackages) {
|
|
||||||
if (className.startsWith(pkg)) {
|
|
||||||
log.warn("🔒 安全拦截: JavaScript尝试访问危险包 - {}", className);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 默认也拒绝(白名单策略更安全,但这里为了兼容性使用黑名单)
|
|
||||||
// 如果要更严格,可以改为 return false
|
|
||||||
log.debug("允许访问类: {}", className);
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
|
|
||||||
|
import javax.crypto.Mac;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ALTCHA v2(PBKDF2/SHA-256)挑战解算。
|
||||||
|
* <p>
|
||||||
|
* 口令是 nonce 的原始字节再拼上大端 uint32 计数器,盐是 salt 的原始字节。
|
||||||
|
* 找到派生密钥以 keyPrefix 开头的计数器后,按官方 widget 的方式拼出
|
||||||
|
* {@code base64({"challenge":{parameters,signature},"solution":{counter,derivedKey,time}})}。
|
||||||
|
* 计算是 CPU 密集的,调用方必须放在 Vert.x worker 上,不能占用 event loop。
|
||||||
|
*/
|
||||||
|
final class AltchaV2Solver {
|
||||||
|
|
||||||
|
static final int DEFAULT_MAX_COUNTER = 200_000;
|
||||||
|
static final long DEFAULT_TIMEOUT_MILLIS = 25_000L;
|
||||||
|
/** 城通当前 cost=1200。更高的 cost 会把解析线程占满,直接拒绝。 */
|
||||||
|
static final int MAX_COST = 20_000;
|
||||||
|
static final int MAX_KEY_LENGTH = 64;
|
||||||
|
private static final int MAX_THREADS = 4;
|
||||||
|
|
||||||
|
private AltchaV2Solver() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static final class Solution {
|
||||||
|
final int counter;
|
||||||
|
final String derivedKeyHex;
|
||||||
|
final long tookMillis;
|
||||||
|
|
||||||
|
Solution(int counter, String derivedKeyHex, long tookMillis) {
|
||||||
|
this.counter = counter;
|
||||||
|
this.derivedKeyHex = derivedKeyHex;
|
||||||
|
this.tookMillis = tookMillis;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Solution solve(JsonObject challenge) {
|
||||||
|
return solve(challenge, DEFAULT_MAX_COUNTER, DEFAULT_TIMEOUT_MILLIS);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Solution solve(JsonObject challenge, int maxCounter, long timeoutMillis) {
|
||||||
|
if (challenge == null || challenge.getJsonObject("parameters") == null) {
|
||||||
|
throw new IllegalArgumentException("ALTCHA 挑战为空");
|
||||||
|
}
|
||||||
|
JsonObject parameters = challenge.getJsonObject("parameters");
|
||||||
|
String algorithm = parameters.getString("algorithm", "");
|
||||||
|
if (!"PBKDF2/SHA-256".equals(algorithm)) {
|
||||||
|
throw new IllegalArgumentException("不支持的 ALTCHA 算法: " + algorithm);
|
||||||
|
}
|
||||||
|
int cost = intValue(parameters.getValue("cost"), -1);
|
||||||
|
int keyLength = intValue(parameters.getValue("keyLength"), 32);
|
||||||
|
if (cost < 1 || cost > MAX_COST) {
|
||||||
|
throw new IllegalArgumentException("ALTCHA cost 超出可解范围: " + cost);
|
||||||
|
}
|
||||||
|
if (keyLength < 16 || keyLength > MAX_KEY_LENGTH) {
|
||||||
|
throw new IllegalArgumentException("ALTCHA keyLength 超出可解范围: " + keyLength);
|
||||||
|
}
|
||||||
|
byte[] nonce = decodeHex(parameters.getString("nonce", ""), "nonce");
|
||||||
|
byte[] salt = decodeHex(parameters.getString("salt", ""), "salt");
|
||||||
|
byte[] prefix = decodeHex(parameters.getString("keyPrefix", ""), "keyPrefix");
|
||||||
|
if (prefix.length == 0 || prefix.length > keyLength) {
|
||||||
|
throw new IllegalArgumentException("ALTCHA keyPrefix 长度无效");
|
||||||
|
}
|
||||||
|
int limit = Math.max(1, maxCounter);
|
||||||
|
long budget = Math.max(1L, timeoutMillis);
|
||||||
|
int threads = Math.min(MAX_THREADS, Math.max(1, Runtime.getRuntime().availableProcessors()));
|
||||||
|
threads = Math.min(threads, limit);
|
||||||
|
|
||||||
|
AtomicInteger winner = new AtomicInteger(-1);
|
||||||
|
AtomicBoolean stop = new AtomicBoolean(false);
|
||||||
|
String[] derivedHex = new String[1];
|
||||||
|
long started = System.nanoTime();
|
||||||
|
long deadline = started + TimeUnit.MILLISECONDS.toNanos(budget);
|
||||||
|
ExecutorService pool = Executors.newFixedThreadPool(threads, runnable -> {
|
||||||
|
Thread thread = new Thread(runnable, "ctfile-altcha");
|
||||||
|
thread.setDaemon(true);
|
||||||
|
return thread;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
Future<?>[] tasks = new Future<?>[threads];
|
||||||
|
for (int i = 0; i < threads; i++) {
|
||||||
|
int start = i;
|
||||||
|
int stride = threads;
|
||||||
|
tasks[i] = pool.submit((Callable<Void>) () -> {
|
||||||
|
search(start, stride, limit, deadline, nonce, salt, prefix, cost, keyLength, winner, stop, derivedHex);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (Future<?> task : tasks) {
|
||||||
|
task.get(budget + 2000L, TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
stop.set(true);
|
||||||
|
throw new IllegalStateException("ALTCHA 解算被中断");
|
||||||
|
} catch (IllegalStateException e) {
|
||||||
|
stop.set(true);
|
||||||
|
throw e;
|
||||||
|
} catch (Exception e) {
|
||||||
|
stop.set(true);
|
||||||
|
throw new IllegalStateException("ALTCHA 解算失败: " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
stop.set(true);
|
||||||
|
pool.shutdownNow();
|
||||||
|
}
|
||||||
|
int counter = winner.get();
|
||||||
|
if (counter < 0 || derivedHex[0] == null) {
|
||||||
|
throw new IllegalStateException("ALTCHA 人机验证解算超时,请稍后重试");
|
||||||
|
}
|
||||||
|
long took = Math.max(1L, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
|
||||||
|
return new Solution(counter, derivedHex[0], took);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 官方 altcha widget 成功后提交的 payload:标准 Base64(含填充),不是 URL-safe。
|
||||||
|
*/
|
||||||
|
static String payload(JsonObject challenge, Solution solution) {
|
||||||
|
JsonObject body = new JsonObject()
|
||||||
|
.put("challenge", new JsonObject()
|
||||||
|
.put("parameters", challenge.getJsonObject("parameters"))
|
||||||
|
.put("signature", challenge.getString("signature")))
|
||||||
|
.put("solution", new JsonObject()
|
||||||
|
.put("counter", solution.counter)
|
||||||
|
.put("derivedKey", solution.derivedKeyHex)
|
||||||
|
.put("time", solution.tookMillis));
|
||||||
|
return Base64.getEncoder().encodeToString(body.encode().getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PBKDF2-HMAC-SHA256,口令是原始字节。
|
||||||
|
* JDK 的 {@code SecretKeyFactory("PBKDF2WithHmacSHA256")} 会把 char[] 口令按 UTF-8 编码,
|
||||||
|
* nonce 里大于 0x7F 的字节会被展开,和 ALTCHA / WebCrypto 的原始字节口令对不上。
|
||||||
|
*/
|
||||||
|
static byte[] pbkdf2(byte[] password, byte[] salt, int cost, int keyLength) {
|
||||||
|
try {
|
||||||
|
Mac mac = Mac.getInstance("HmacSHA256");
|
||||||
|
mac.init(new SecretKeySpec(password, "HmacSHA256"));
|
||||||
|
return pbkdf2(mac, salt, cost, keyLength);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("PBKDF2 计算失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void search(int start, int stride, int limit, long deadline, byte[] nonce, byte[] salt,
|
||||||
|
byte[] prefix, int cost, int keyLength, AtomicInteger winner, AtomicBoolean stop,
|
||||||
|
String[] derivedHex) {
|
||||||
|
Mac mac;
|
||||||
|
try {
|
||||||
|
mac = Mac.getInstance("HmacSHA256");
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("PBKDF2 初始化失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
for (int counter = start; counter < limit && winner.get() < 0 && !stop.get(); counter += stride) {
|
||||||
|
if ((counter & 31) == start && System.nanoTime() > deadline) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
byte[] derived;
|
||||||
|
try {
|
||||||
|
mac.init(new SecretKeySpec(password(nonce, counter), "HmacSHA256"));
|
||||||
|
derived = pbkdf2(mac, salt, cost, keyLength);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new IllegalStateException("PBKDF2 计算失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
if (startsWith(derived, prefix) && winner.compareAndSet(-1, counter)) {
|
||||||
|
derivedHex[0] = toHex(derived);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] pbkdf2(Mac mac, byte[] salt, int iterations, int keyLength) throws Exception {
|
||||||
|
int hashLength = mac.getMacLength();
|
||||||
|
byte[] result = new byte[keyLength];
|
||||||
|
byte[] block = new byte[salt.length + 4];
|
||||||
|
System.arraycopy(salt, 0, block, 0, salt.length);
|
||||||
|
int offset = 0;
|
||||||
|
for (int index = 1; offset < keyLength; index++) {
|
||||||
|
block[salt.length] = (byte) (index >>> 24);
|
||||||
|
block[salt.length + 1] = (byte) (index >>> 16);
|
||||||
|
block[salt.length + 2] = (byte) (index >>> 8);
|
||||||
|
block[salt.length + 3] = (byte) index;
|
||||||
|
byte[] mixed = mac.doFinal(block);
|
||||||
|
byte[] digest = mixed.clone();
|
||||||
|
for (int round = 1; round < iterations; round++) {
|
||||||
|
mixed = mac.doFinal(mixed);
|
||||||
|
for (int i = 0; i < mixed.length; i++) {
|
||||||
|
digest[i] ^= mixed[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int length = Math.min(hashLength, keyLength - offset);
|
||||||
|
System.arraycopy(digest, 0, result, offset, length);
|
||||||
|
offset += length;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] password(byte[] nonce, int counter) {
|
||||||
|
byte[] password = Arrays.copyOf(nonce, nonce.length + 4);
|
||||||
|
password[nonce.length] = (byte) (counter >>> 24);
|
||||||
|
password[nonce.length + 1] = (byte) (counter >>> 16);
|
||||||
|
password[nonce.length + 2] = (byte) (counter >>> 8);
|
||||||
|
password[nonce.length + 3] = (byte) counter;
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean startsWith(byte[] value, byte[] prefix) {
|
||||||
|
if (prefix.length > value.length) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < prefix.length; i++) {
|
||||||
|
if (value[i] != prefix[i]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static byte[] decodeHex(String hex, String name) {
|
||||||
|
if (hex == null || hex.length() % 2 != 0 || !hex.matches("[0-9a-fA-F]*")) {
|
||||||
|
throw new IllegalArgumentException("ALTCHA " + name + " 不是合法十六进制");
|
||||||
|
}
|
||||||
|
byte[] out = new byte[hex.length() / 2];
|
||||||
|
for (int i = 0; i < out.length; i++) {
|
||||||
|
out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String toHex(byte[] bytes) {
|
||||||
|
StringBuilder builder = new StringBuilder(bytes.length * 2);
|
||||||
|
for (byte value : bytes) {
|
||||||
|
builder.append(Character.forDigit((value >> 4) & 0xF, 16));
|
||||||
|
builder.append(Character.forDigit(value & 0xF, 16));
|
||||||
|
}
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int intValue(Object value, int fallback) {
|
||||||
|
if (value instanceof Number) {
|
||||||
|
return ((Number) value).intValue();
|
||||||
|
}
|
||||||
|
if (value == null) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(value.toString());
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,6 +37,7 @@ public class Ce4Tool extends PanBase {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
URL url = new URL(shareLinkInfo.getShareUrl());
|
URL url = new URL(shareLinkInfo.getShareUrl());
|
||||||
|
assertPublicHost(url);
|
||||||
String baseUrl = url.getProtocol() + "://" + url.getHost();
|
String baseUrl = url.getProtocol() + "://" + url.getHost();
|
||||||
// 如果有端口,拼接上端口
|
// 如果有端口,拼接上端口
|
||||||
if (url.getPort() != -1) {
|
if (url.getPort() != -1) {
|
||||||
@@ -110,7 +111,8 @@ public class Ce4Tool extends PanBase {
|
|||||||
private void requestShareDetail(String baseUrl, String key, String pwd, String path) {
|
private void requestShareDetail(String baseUrl, String key, String pwd, String path) {
|
||||||
String shareApiUrl = baseUrl + SHARE_API_PATH + key;
|
String shareApiUrl = baseUrl + SHARE_API_PATH + key;
|
||||||
|
|
||||||
HttpRequest<Buffer> httpRequest = clientSession.getAbs(shareApiUrl);
|
// 禁止跟随重定向:防止公网 host 302 到内网/元数据绕过 assertPublicHost
|
||||||
|
HttpRequest<Buffer> httpRequest = clientNoRedirects.getAbs(shareApiUrl);
|
||||||
if (pwd != null && !pwd.isEmpty()) {
|
if (pwd != null && !pwd.isEmpty()) {
|
||||||
httpRequest.addQueryParam("password", pwd);
|
httpRequest.addQueryParam("password", pwd);
|
||||||
}
|
}
|
||||||
@@ -231,7 +233,7 @@ public class Ce4Tool extends PanBase {
|
|||||||
.put("uris", new JsonArray().add(filePath))
|
.put("uris", new JsonArray().add(filePath))
|
||||||
.put("download", true);
|
.put("download", true);
|
||||||
|
|
||||||
clientSession.postAbs(fileUrlApi)
|
clientNoRedirects.postAbs(fileUrlApi)
|
||||||
.putHeader("Content-Type", "application/json")
|
.putHeader("Content-Type", "application/json")
|
||||||
.sendJsonObject(requestBody)
|
.sendJsonObject(requestBody)
|
||||||
.onSuccess(res -> {
|
.onSuccess(res -> {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package cn.qaiu.parser.impl;
|
|||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import cn.qaiu.parser.IPanTool;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
import io.vertx.core.buffer.Buffer;
|
import io.vertx.core.buffer.Buffer;
|
||||||
@@ -42,6 +43,7 @@ public class CeTool extends PanBase {
|
|||||||
String pwd = shareLinkInfo.getSharePassword();
|
String pwd = shareLinkInfo.getSharePassword();
|
||||||
try {
|
try {
|
||||||
URL url = new URL(shareLinkInfo.getShareUrl());
|
URL url = new URL(shareLinkInfo.getShareUrl());
|
||||||
|
assertPublicHost(url);
|
||||||
String baseUrl = url.getProtocol() + "://" + url.getHost();
|
String baseUrl = url.getProtocol() + "://" + url.getHost();
|
||||||
// 如果有端口,拼接上端口
|
// 如果有端口,拼接上端口
|
||||||
if (url.getPort() != -1) {
|
if (url.getPort() != -1) {
|
||||||
@@ -76,7 +78,8 @@ public class CeTool extends PanBase {
|
|||||||
private void tryV4Ping(String baseUrl, String key, String pwd) {
|
private void tryV4Ping(String baseUrl, String key, String pwd) {
|
||||||
String pingUrlV4 = baseUrl + PING_API_V4_PATH;
|
String pingUrlV4 = baseUrl + PING_API_V4_PATH;
|
||||||
|
|
||||||
clientSession.getAbs(pingUrlV4).send().onSuccess(res -> {
|
// 禁止跟随重定向:assertPublicHost 只校验初始 host,自动 30x 会绕过 SSRF 防护
|
||||||
|
clientNoRedirects.getAbs(pingUrlV4).send().onSuccess(res -> {
|
||||||
if (res.statusCode() == 200) {
|
if (res.statusCode() == 200) {
|
||||||
try {
|
try {
|
||||||
JsonObject json = asJson(res);
|
JsonObject json = asJson(res);
|
||||||
@@ -106,7 +109,7 @@ public class CeTool extends PanBase {
|
|||||||
private void tryV3Ping(String baseUrl, String key, String pwd) {
|
private void tryV3Ping(String baseUrl, String key, String pwd) {
|
||||||
String pingUrlV3 = baseUrl + PING_API_V3_PATH;
|
String pingUrlV3 = baseUrl + PING_API_V3_PATH;
|
||||||
|
|
||||||
clientSession.getAbs(pingUrlV3).send().onSuccess(res -> {
|
clientNoRedirects.getAbs(pingUrlV3).send().onSuccess(res -> {
|
||||||
if (res.statusCode() == 200) {
|
if (res.statusCode() == 200) {
|
||||||
try {
|
try {
|
||||||
JsonObject json = asJson(res);
|
JsonObject json = asJson(res);
|
||||||
@@ -137,7 +140,7 @@ public class CeTool extends PanBase {
|
|||||||
*/
|
*/
|
||||||
private void verifyV3AndParse(String baseUrl, String key, String pwd) {
|
private void verifyV3AndParse(String baseUrl, String key, String pwd) {
|
||||||
String shareApiUrl = baseUrl + SHARE_API_PATH + key;
|
String shareApiUrl = baseUrl + SHARE_API_PATH + key;
|
||||||
HttpRequest<Buffer> httpRequest = clientSession.getAbs(shareApiUrl);
|
HttpRequest<Buffer> httpRequest = clientNoRedirects.getAbs(shareApiUrl);
|
||||||
if (pwd != null && !pwd.isEmpty()) {
|
if (pwd != null && !pwd.isEmpty()) {
|
||||||
httpRequest.addQueryParam("password", pwd);
|
httpRequest.addQueryParam("password", pwd);
|
||||||
}
|
}
|
||||||
@@ -160,6 +163,7 @@ public class CeTool extends PanBase {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.debug("v3 share API解析失败: {}", e.getMessage());
|
log.debug("v3 share API解析失败: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
|
tryV4ShareApi(baseUrl, key, pwd);
|
||||||
}).onFailure(t -> {
|
}).onFailure(t -> {
|
||||||
log.debug("v3 share API请求失败: {}", t.getMessage());
|
log.debug("v3 share API请求失败: {}", t.getMessage());
|
||||||
// 请求失败,尝试 v4 或下一个解析器
|
// 请求失败,尝试 v4 或下一个解析器
|
||||||
@@ -172,7 +176,7 @@ public class CeTool extends PanBase {
|
|||||||
*/
|
*/
|
||||||
private void tryV4ShareApi(String baseUrl, String key, String pwd) {
|
private void tryV4ShareApi(String baseUrl, String key, String pwd) {
|
||||||
String shareApiUrl = baseUrl + "/api/v4/share/info/" + key;
|
String shareApiUrl = baseUrl + "/api/v4/share/info/" + key;
|
||||||
HttpRequest<Buffer> httpRequest = clientSession.getAbs(shareApiUrl);
|
HttpRequest<Buffer> httpRequest = clientNoRedirects.getAbs(shareApiUrl);
|
||||||
if (pwd != null && !pwd.isEmpty()) {
|
if (pwd != null && !pwd.isEmpty()) {
|
||||||
httpRequest.addQueryParam("password", pwd);
|
httpRequest.addQueryParam("password", pwd);
|
||||||
}
|
}
|
||||||
@@ -206,7 +210,8 @@ public class CeTool extends PanBase {
|
|||||||
*/
|
*/
|
||||||
private void delegateToCe4Tool() {
|
private void delegateToCe4Tool() {
|
||||||
log.debug("检测到Cloudreve 4.x,转发到Ce4Tool处理");
|
log.debug("检测到Cloudreve 4.x,转发到Ce4Tool处理");
|
||||||
new Ce4Tool(shareLinkInfo).parse().onComplete(promise);
|
Ce4Tool ce4Tool = new Ce4Tool(shareLinkInfo);
|
||||||
|
IPanTool.closeAfter(ce4Tool, ce4Tool::parse).onComplete(promise);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -287,7 +292,8 @@ public class CeTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void getDownURL(String shareApiUrl) {
|
private void getDownURL(String shareApiUrl) {
|
||||||
clientSession.putAbs(shareApiUrl)
|
// PUT 默认不跟随重定向,但仍统一使用 no-redirect 客户端避免配置漂移
|
||||||
|
clientNoRedirects.putAbs(shareApiUrl)
|
||||||
.putHeader("Referer", shareLinkInfo.getShareUrl())
|
.putHeader("Referer", shareLinkInfo.getShareUrl())
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
JsonObject jsonObject = asJson(res);
|
JsonObject jsonObject = asJson(res);
|
||||||
|
|||||||
@@ -1,112 +1,414 @@
|
|||||||
package cn.qaiu.parser.impl;
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.WebClientVertxInit;
|
||||||
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.util.RandomStringGenerator;
|
import cn.qaiu.parser.impl.CtfileSession.CtfileException;
|
||||||
|
import cn.qaiu.parser.impl.CtfileSession.DirectLink;
|
||||||
|
import cn.qaiu.parser.impl.CtfileSession.ShareTarget;
|
||||||
|
import cn.qaiu.parser.impl.CtfileSession.VerificationMismatch;
|
||||||
|
import cn.qaiu.util.CommonUtils;
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
import io.vertx.core.buffer.Buffer;
|
import io.vertx.core.Promise;
|
||||||
|
import io.vertx.core.WorkerExecutor;
|
||||||
|
import io.vertx.core.json.JsonArray;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import io.vertx.ext.web.client.HttpRequest;
|
|
||||||
import io.vertx.uritemplate.UriTemplate;
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.net.URLEncoder;
|
||||||
import java.util.Map;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* <a href="https://www.ctfile.com">诚通网盘</a>
|
* 城通网盘。免密和带访问密码的分享都先走匿名网页接口和 ALTCHA v2。
|
||||||
|
* 官方客户端 {@code /v4} 只在匿名结果仍是 Turnstile、且调用方自己配置了登录令牌时回退。
|
||||||
*/
|
*/
|
||||||
public class CtTool extends PanBase {
|
public class CtTool extends PanBase {
|
||||||
private static final String API_URL_PREFIX = "https://webapi.ctfile.com";
|
|
||||||
|
|
||||||
// https://webapi.ctfile.com/getfile.php?path=f&f=55050874-1246660795-6464f6&
|
private static final String SHARE_FILE_URL_PREFIX = "https://ctfile.com/file/";
|
||||||
// passcode=7548&token=30wiijxs1fzhb6brw0p9m6&r=0.5885881231735761&
|
private static final int DEFAULT_MAX_LIST_PAGES = 50;
|
||||||
// ref=&url=https%3A%2F%2F474b.com%2Ff%2F55050874-1246660795-6464f6%3Fp%3D7548
|
|
||||||
private static final String API1 = API_URL_PREFIX + "/getfile.php?path={path}" +
|
|
||||||
"&f={shareKey}&passcode={pwd}&token={token}&r={rand}&ref=";
|
|
||||||
|
|
||||||
//https://webapi.ctfile.com/get_file_url.php?uid=55050874&fid=1246660795&folder_id=0&
|
private static final Object WORKER_LOCK = new Object();
|
||||||
// file_chk=054bc20461f5c63ff82015b9e69fb7fc&mb=1&token=30wiijxs1fzhb6brw0p9m6&app=0&
|
private static volatile WorkerExecutor sharedWorker;
|
||||||
// acheck=1&verifycode=&rd=0.965929071503574
|
private static volatile boolean workerShutdown;
|
||||||
private static final String API2 = API_URL_PREFIX + "/get_file_url.php?" +
|
|
||||||
"uid={uid}&fid={fid}&folder_id=0&file_chk={file_chk}&mb=0&token={token}&app=0&acheck=0&verifycode=" +
|
|
||||||
"&rd={rand}";
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 子类重写此构造方法不需要添加额外逻辑
|
|
||||||
* 如:
|
|
||||||
* <blockquote><pre>
|
|
||||||
* public XxTool(String key, String pwd) {
|
|
||||||
* super(key, pwd);
|
|
||||||
* }
|
|
||||||
* </pre></blockquote>
|
|
||||||
*
|
|
||||||
* @param shareLinkInfo 分享链接信息
|
|
||||||
*/
|
|
||||||
public CtTool(ShareLinkInfo shareLinkInfo) {
|
public CtTool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void shutdownWorkerExecutor() {
|
||||||
|
synchronized (WORKER_LOCK) {
|
||||||
|
workerShutdown = true;
|
||||||
|
if (sharedWorker != null) {
|
||||||
|
sharedWorker.close();
|
||||||
|
sharedWorker = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
final String shareKey = shareLinkInfo.getShareKey();
|
String shareKey = shareLinkInfo.getShareKey();
|
||||||
if (shareKey.indexOf('-') == -1) {
|
if (shareKey == null || shareKey.isBlank()) {
|
||||||
fail("shareKey格式不正确找不到'-': {}", shareKey);
|
fail("shareKey为空");
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
String[] split = shareKey.split("-");
|
try {
|
||||||
String uid = split[0], fid = split[1];
|
worker().executeBlocking(() -> {
|
||||||
String token = RandomStringGenerator.generateRandomString();
|
ParsedDownload link = resolveDownload(shareKey);
|
||||||
// 获取url path
|
shareLinkInfo.getOtherParam().put("fileInfo", fileInfoFrom(link.file));
|
||||||
int i1 = shareLinkInfo.getShareUrl().indexOf("com/");
|
if (link.fileDir != null && !link.fileDir.isBlank()) {
|
||||||
int i2 = shareLinkInfo.getShareUrl().lastIndexOf("/");
|
shareLinkInfo.getOtherParam().put("ctFileDir", link.fileDir);
|
||||||
String path = shareLinkInfo.getShareUrl().substring(i1 + 4, i2);
|
}
|
||||||
|
return link;
|
||||||
HttpRequest<Buffer> bufferHttpRequest1 = clientSession.getAbs(UriTemplate.of(API1))
|
}, false).onSuccess(link -> {
|
||||||
.setTemplateParam("path", path)
|
if (link.headers == null || link.headers.isEmpty()) {
|
||||||
.setTemplateParam("shareKey", shareKey)
|
complete(link.url);
|
||||||
.setTemplateParam("pwd", shareLinkInfo.getSharePassword())
|
} else {
|
||||||
.setTemplateParam("token", token)
|
completeWithMeta(link.url, link.headers);
|
||||||
.setTemplateParam("r", Math.random() + "");
|
}
|
||||||
|
}).onFailure(error -> fail("{}", rootMessage(error)));
|
||||||
bufferHttpRequest1
|
} catch (RuntimeException e) {
|
||||||
.send().onSuccess(res -> {
|
fail("{}", e.getMessage());
|
||||||
var resJson = asJson(res);
|
}
|
||||||
if (resJson.containsKey("file")) {
|
|
||||||
var fileJson = resJson.getJsonObject("file");
|
|
||||||
if (fileJson.containsKey("file_chk")) {
|
|
||||||
var file_chk = fileJson.getString("file_chk");
|
|
||||||
HttpRequest<Buffer> bufferHttpRequest2 = clientSession.getAbs(UriTemplate.of(API2))
|
|
||||||
.setTemplateParam("uid", uid)
|
|
||||||
.setTemplateParam("fid", fid)
|
|
||||||
.setTemplateParam("file_chk", file_chk)
|
|
||||||
.setTemplateParam("token", token)
|
|
||||||
.setTemplateParam("rd", Math.random() + "");
|
|
||||||
bufferHttpRequest2
|
|
||||||
.send().onSuccess(res2 -> {
|
|
||||||
JsonObject resJson2 = asJson(res2);
|
|
||||||
if (resJson2.containsKey("downurl")) {
|
|
||||||
String downloadUrl = resJson2.getString("downurl");
|
|
||||||
|
|
||||||
// 存储下载元数据,包括必要的请求头
|
|
||||||
Map<String, String> headers = new HashMap<>();
|
|
||||||
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
|
|
||||||
headers.put("Referer", shareLinkInfo.getShareUrl());
|
|
||||||
|
|
||||||
// 使用新的 completeWithMeta 方法
|
|
||||||
completeWithMeta(downloadUrl, headers);
|
|
||||||
} else {
|
|
||||||
fail("解析失败, 可能分享已失效: json: {} 字段 {} 不存在", resJson2, "downurl");
|
|
||||||
}
|
|
||||||
}).onFailure(handleFail(bufferHttpRequest1.queryParams().toString()));
|
|
||||||
} else {
|
|
||||||
fail("解析失败, file_chk找不到, 可能分享已失效或者分享密码不对: {}", fileJson);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
fail("解析失败, 文件信息为空, 可能分享已失效");
|
|
||||||
}
|
|
||||||
}).onFailure(handleFail(bufferHttpRequest1.queryParams().toString()));
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Future<List<FileInfo>> parseFileList() {
|
||||||
|
Promise<List<FileInfo>> listPromise = Promise.promise();
|
||||||
|
String shareKey = shareLinkInfo.getShareKey();
|
||||||
|
if (shareKey == null || shareKey.isBlank()) {
|
||||||
|
listPromise.fail(baseMsg() + " - 解析异常: shareKey为空");
|
||||||
|
return listPromise.future();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
worker().executeBlocking(() -> listDirectory(shareKey), false)
|
||||||
|
.onSuccess(listPromise::complete)
|
||||||
|
.onFailure(error -> {
|
||||||
|
if (!listPromise.future().isComplete()) {
|
||||||
|
listPromise.fail(baseMsg() + " - 解析异常: " + rootMessage(error));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
listPromise.fail(baseMsg() + " - 解析异常: " + e.getMessage());
|
||||||
|
}
|
||||||
|
return listPromise.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Future<String> parseById() {
|
||||||
|
Object paramValue = shareLinkInfo.getOtherParam().get("paramJson");
|
||||||
|
if (!(paramValue instanceof JsonObject)) {
|
||||||
|
fail("缺少下载参数paramJson");
|
||||||
|
return promise.future();
|
||||||
|
}
|
||||||
|
if (!applyFileParam(shareLinkInfo, (JsonObject) paramValue)) {
|
||||||
|
fail("下载参数id为空");
|
||||||
|
return promise.future();
|
||||||
|
}
|
||||||
|
return parse();
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean applyFileParam(ShareLinkInfo shareLinkInfo, JsonObject paramJson) {
|
||||||
|
String fileShareKey = paramJson.getString("id");
|
||||||
|
if (fileShareKey == null || fileShareKey.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
shareLinkInfo.setSharePassword(paramJson.getString("pwd", ""));
|
||||||
|
String xtlink = paramJson.getString("xtlink", "");
|
||||||
|
if (!xtlink.isBlank()) {
|
||||||
|
shareLinkInfo.getOtherParam().put("ctXtlink", xtlink);
|
||||||
|
shareLinkInfo.getOtherParam().put("ctV4FileId", fileShareKey);
|
||||||
|
String parentKey = paramJson.getString("shareKey", "");
|
||||||
|
if (!parentKey.isBlank()) {
|
||||||
|
shareLinkInfo.setShareKey(parentKey);
|
||||||
|
} else if (shareLinkInfo.getShareKey() == null || shareLinkInfo.getShareKey().isBlank()) {
|
||||||
|
shareLinkInfo.setShareKey(fileShareKey);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
shareLinkInfo.setShareKey(fileShareKey);
|
||||||
|
shareLinkInfo.setShareUrl(SHARE_FILE_URL_PREFIX + fileShareKey);
|
||||||
|
shareLinkInfo.setStandardUrl(SHARE_FILE_URL_PREFIX + fileShareKey);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ParsedDownload resolveDownload(String shareKey) throws Exception {
|
||||||
|
if (requiresV4()) {
|
||||||
|
return downloadWithV4(shareKey);
|
||||||
|
}
|
||||||
|
VerificationMismatch mismatch = null;
|
||||||
|
for (int attempt = 0; attempt < 2; attempt++) {
|
||||||
|
try (CtfileSession session = CtfileSession.open(shareLinkInfo)) {
|
||||||
|
try {
|
||||||
|
return downloadOnce(session, shareKey);
|
||||||
|
} catch (VerificationMismatch retryable) {
|
||||||
|
// verifycode 和签发它的那次连接绑在一起。换一个客户端再取一次。
|
||||||
|
mismatch = retryable;
|
||||||
|
} catch (CtfileException e) {
|
||||||
|
if (turnstile(e) && CtfileV4Client.hasCredentials(shareLinkInfo)) {
|
||||||
|
return downloadWithV4(shareKey);
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw mismatch == null ? new CtfileException("未返回下载地址") : mismatch;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ParsedDownload downloadWithV4(String shareKey) throws Exception {
|
||||||
|
if (!CtfileV4Client.hasCredentials(shareLinkInfo)) {
|
||||||
|
throw new CtfileException(CtfileV4Client.missingAccountMessage());
|
||||||
|
}
|
||||||
|
CtfileV4Client.DirectLink link = new CtfileV4Client(shareLinkInfo).downloadShare(shareKey, directoryShare());
|
||||||
|
return new ParsedDownload(link.url, java.util.Map.of(), link.file, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 只有 v4 目录列表生成的文件参数才直接走客户端协议。访问密码本身不触发登录。 */
|
||||||
|
static boolean requiresV4(ShareLinkInfo info) {
|
||||||
|
if (info == null || info.getOtherParam() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Object fileId = info.getOtherParam().get("ctV4FileId");
|
||||||
|
return fileId != null && !fileId.toString().isBlank();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean requiresV4() {
|
||||||
|
return requiresV4(shareLinkInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean turnstile(CtfileException error) {
|
||||||
|
return error.getMessage() != null && error.getMessage().contains("Turnstile");
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean directoryShare() {
|
||||||
|
String type = shareLinkInfo.getType();
|
||||||
|
if (type != null && type.equalsIgnoreCase("ctd")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
String url = shareLinkInfo.getShareUrl();
|
||||||
|
return url != null && url.matches("(?i).*/d/[^/].*");
|
||||||
|
}
|
||||||
|
|
||||||
|
private ParsedDownload downloadOnce(CtfileSession session, String shareKey) throws Exception {
|
||||||
|
String password = shareLinkInfo.getSharePassword();
|
||||||
|
ShareTarget target = ShareTarget.from(shareLinkInfo);
|
||||||
|
JsonObject resource = session.loadResource("file", shareKey, target, password, turnstileToken());
|
||||||
|
JsonObject data = CtfileSession.dataOf(resource);
|
||||||
|
JsonObject file = data == null ? null : data.getJsonObject("file");
|
||||||
|
if (file == null) {
|
||||||
|
throw new CtfileException("下载参数不完整:上游没有返回文件信息");
|
||||||
|
}
|
||||||
|
DirectLink link = session.download(shareKey, target, password, resource);
|
||||||
|
return new ParsedDownload(link.url, link.headers, file, file.getString("file_dir", ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<FileInfo> listDirectory(String shareKey) throws Exception {
|
||||||
|
String password = shareLinkInfo.getSharePassword();
|
||||||
|
ShareTarget target = ShareTarget.from(shareLinkInfo);
|
||||||
|
int maxPages = maxListPages();
|
||||||
|
try (CtfileSession session = CtfileSession.open(shareLinkInfo)) {
|
||||||
|
JsonObject resource = session.loadResource("dir", shareKey, target, password, turnstileToken());
|
||||||
|
List<FileInfo> files = new ArrayList<>();
|
||||||
|
int start = 0;
|
||||||
|
for (int page = 0; page < maxPages; page++) {
|
||||||
|
JsonObject listing = session.listing("dir", shareKey, target, password, resource, start,
|
||||||
|
CtfileSession.pageSize());
|
||||||
|
int code = CtfileSession.intValue(listing.getValue("code"), 200);
|
||||||
|
if (code != 200) {
|
||||||
|
throw new CtfileException(CtfileSession.classify(listing, code, password).message);
|
||||||
|
}
|
||||||
|
JsonArray rows = CtfileSession.rowsOf(listing);
|
||||||
|
for (int i = 0; i < rows.size(); i++) {
|
||||||
|
if (rows.getValue(i) instanceof JsonObject row) {
|
||||||
|
FileInfo info = toFileInfo(row, shareLinkInfo);
|
||||||
|
if (info != null) {
|
||||||
|
files.add(info);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rows.isEmpty() || !CtfileSession.hasMore(listing, rows.size())) {
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
start += rows.size();
|
||||||
|
}
|
||||||
|
if (maxPages != DEFAULT_MAX_LIST_PAGES || shareLinkInfo.getOtherParam().containsKey("ctMaxListPages")) {
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
throw new CtfileException("目录文件过多,已超过 " + maxPages + " 页");
|
||||||
|
} catch (CtfileException e) {
|
||||||
|
if (turnstile(e) && CtfileV4Client.hasCredentials(shareLinkInfo)) {
|
||||||
|
return new CtfileV4Client(shareLinkInfo).listShare(shareKey, target.folderId, maxPages);
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static FileInfo toFileInfo(JsonObject row, ShareLinkInfo info) {
|
||||||
|
if (row == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String name = row.getString("name", "").trim();
|
||||||
|
if (name.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String kind = row.getString("kind", "");
|
||||||
|
String password = info.getSharePassword() == null ? "" : info.getSharePassword();
|
||||||
|
FileInfo fileInfo = new FileInfo()
|
||||||
|
.setFileName(name)
|
||||||
|
.setPanType(info.getType())
|
||||||
|
.setCreateBy(CtfileSession.text(row.getValue("ownerId")));
|
||||||
|
String date = row.getString("date", "");
|
||||||
|
if (!date.isBlank()) {
|
||||||
|
fileInfo.setCreateTime(date).setUpdateTime(date);
|
||||||
|
}
|
||||||
|
if ("folder".equals(kind)) {
|
||||||
|
String folderId = CtfileSession.text(row.getValue("folderId"));
|
||||||
|
if (folderId.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String folderKey = row.getString("folderKey", "");
|
||||||
|
fileInfo.setFileId(folderId)
|
||||||
|
.setFileType("folder")
|
||||||
|
.setSize(0L)
|
||||||
|
.setSizeStr("0B")
|
||||||
|
.setParserUrl(buildFolderParserUrl(info, folderId + ":" + (folderKey == null ? "" : folderKey), password));
|
||||||
|
return fileInfo;
|
||||||
|
}
|
||||||
|
if (!"file".equals(kind)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String fileKey = fileKeyFromHref(row.getString("href", ""));
|
||||||
|
if (fileKey.isBlank()) {
|
||||||
|
fileKey = CtfileSession.text(row.getValue("fileId"));
|
||||||
|
}
|
||||||
|
if (fileKey.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
long size = CtfileSession.longValue(row.getValue("size_bytes"), 0L);
|
||||||
|
JsonObject param = new JsonObject()
|
||||||
|
.put("id", fileKey)
|
||||||
|
.put("fileName", name)
|
||||||
|
.put("pwd", password);
|
||||||
|
String encoded = CommonUtils.urlBase64Encode(param.encode());
|
||||||
|
String domain = info.getOtherParam() == null ? "" : info.getOtherParam().getOrDefault("domainName", "").toString();
|
||||||
|
fileInfo.setFileId(CtfileSession.firstNonBlank(CtfileSession.text(row.getValue("fileId")), fileKey))
|
||||||
|
.setFileType(CtfileSession.firstNonBlank(row.getString("extension"), "file"))
|
||||||
|
.setSize(size)
|
||||||
|
.setSizeStr(row.getString("size", ""))
|
||||||
|
.setParserUrl(domain + "/v2/redirectUrl/" + info.getType() + "/" + encoded);
|
||||||
|
return fileInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String buildFolderParserUrl(ShareLinkInfo info, String dirId, String password) {
|
||||||
|
String domain = info.getOtherParam() == null ? "" : info.getOtherParam().getOrDefault("domainName", "").toString();
|
||||||
|
String shareUrl = info.getShareUrl() == null ? "" : info.getShareUrl();
|
||||||
|
String url = domain + "/v2/getFileList?url=" + urlEncode(shareUrl) + "&dirId=" + urlEncode(dirId);
|
||||||
|
if (password != null && !password.isBlank()) {
|
||||||
|
url += "&pwd=" + urlEncode(password);
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String fileKeyFromHref(String href) {
|
||||||
|
if (href == null || href.isBlank()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
int marker = href.indexOf("/f/");
|
||||||
|
int skip = 3;
|
||||||
|
if (marker < 0) {
|
||||||
|
marker = href.indexOf("/file/");
|
||||||
|
skip = 6;
|
||||||
|
}
|
||||||
|
if (marker < 0) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String rest = href.substring(marker + skip);
|
||||||
|
int cut = rest.length();
|
||||||
|
for (int i = 0; i < rest.length(); i++) {
|
||||||
|
char c = rest.charAt(i);
|
||||||
|
if (c == '?' || c == '#' || c == '/') {
|
||||||
|
cut = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rest.substring(0, cut);
|
||||||
|
}
|
||||||
|
|
||||||
|
private FileInfo fileInfoFrom(JsonObject file) {
|
||||||
|
long size = CtfileSession.longValue(file.getValue("file_size_bytes"), 0L);
|
||||||
|
FileInfo info = new FileInfo()
|
||||||
|
.setFileName(file.getString("file_name", ""))
|
||||||
|
.setFileId(CtfileSession.text(file.getValue("file_id")))
|
||||||
|
.setSize(size)
|
||||||
|
.setSizeStr(file.getString("file_size", ""))
|
||||||
|
.setFileType("file")
|
||||||
|
.setCreateBy(file.getString("username", ""))
|
||||||
|
.setPanType(shareLinkInfo.getType());
|
||||||
|
String created = file.getString("file_time", "");
|
||||||
|
if (!created.isBlank()) {
|
||||||
|
info.setCreateTime(created);
|
||||||
|
}
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String turnstileToken() {
|
||||||
|
if (shareLinkInfo.getOtherParam() == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
Object value = shareLinkInfo.getOtherParam().get("turnstileToken");
|
||||||
|
return value == null ? "" : value.toString().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private int maxListPages() {
|
||||||
|
if (shareLinkInfo.getOtherParam() == null || !shareLinkInfo.getOtherParam().containsKey("ctMaxListPages")) {
|
||||||
|
return DEFAULT_MAX_LIST_PAGES;
|
||||||
|
}
|
||||||
|
int configured = CtfileSession.intValue(shareLinkInfo.getOtherParam().get("ctMaxListPages"), DEFAULT_MAX_LIST_PAGES);
|
||||||
|
return configured < 1 ? 1 : configured;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String rootMessage(Throwable error) {
|
||||||
|
Throwable current = error;
|
||||||
|
while (current.getCause() != null && current.getCause() != current
|
||||||
|
&& (current.getMessage() == null || current.getMessage().isBlank()
|
||||||
|
|| current.getClass().getName().contains("CompletionException")
|
||||||
|
|| current.getClass().getName().contains("ExecutionException"))) {
|
||||||
|
current = current.getCause();
|
||||||
|
}
|
||||||
|
String message = current.getMessage();
|
||||||
|
return message == null || message.isBlank() ? current.getClass().getSimpleName() : message;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String urlEncode(String value) {
|
||||||
|
return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WorkerExecutor worker() {
|
||||||
|
synchronized (WORKER_LOCK) {
|
||||||
|
if (workerShutdown) {
|
||||||
|
throw new IllegalStateException("城通解析线程池已关闭");
|
||||||
|
}
|
||||||
|
if (sharedWorker == null) {
|
||||||
|
sharedWorker = WebClientVertxInit.get().createSharedWorkerExecutor("ctfile-worker", 4);
|
||||||
|
}
|
||||||
|
return sharedWorker;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class ParsedDownload {
|
||||||
|
final String url;
|
||||||
|
final java.util.Map<String, String> headers;
|
||||||
|
final JsonObject file;
|
||||||
|
final String fileDir;
|
||||||
|
|
||||||
|
ParsedDownload(String url, java.util.Map<String, String> headers, JsonObject file, String fileDir) {
|
||||||
|
this.url = url;
|
||||||
|
this.headers = headers;
|
||||||
|
this.file = file;
|
||||||
|
this.fileDir = fileDir;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,692 @@
|
|||||||
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import io.vertx.core.json.JsonArray;
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.Authenticator;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.net.PasswordAuthentication;
|
||||||
|
import java.net.ProxySelector;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URLDecoder;
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 城通新版分享接口(api.ctfile.com/url/*)。
|
||||||
|
* <p>
|
||||||
|
* 一次解析专用一个 HttpClient:资源接口签发的 verifycode 绑定本次连接的出口 IP,
|
||||||
|
* 下载必须跟在同一次连接上的 resource 之后。访问令牌 access_pass 约 24 小时、按分享者复用,
|
||||||
|
* 用来跳过重复的 ALTCHA 计算。
|
||||||
|
*/
|
||||||
|
final class CtfileSession implements AutoCloseable {
|
||||||
|
|
||||||
|
static final String API = "https://api.ctfile.com";
|
||||||
|
private static final String CHALLENGE_PATH = "/url/captcha/altcha?captcha_action=share_passcode";
|
||||||
|
private static final String UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||||
|
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
|
||||||
|
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(20);
|
||||||
|
private static final int PAGE_SIZE = 200;
|
||||||
|
private static final long PASS_SKEW_MILLIS = 60_000L;
|
||||||
|
|
||||||
|
private static final ConcurrentHashMap<String, CachedPass> ACCESS_PASSES = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private final HttpClient client;
|
||||||
|
private final String origin;
|
||||||
|
private final String referer;
|
||||||
|
|
||||||
|
private CtfileSession(HttpClient client, String origin, String referer) {
|
||||||
|
this.client = client;
|
||||||
|
this.origin = origin;
|
||||||
|
this.referer = referer;
|
||||||
|
}
|
||||||
|
|
||||||
|
static CtfileSession open(ShareLinkInfo info) {
|
||||||
|
String shareUrl = info == null ? "" : info.getShareUrl();
|
||||||
|
String origin = originOf(shareUrl);
|
||||||
|
if (origin.isBlank()) {
|
||||||
|
origin = "https://www.ctfile.com";
|
||||||
|
}
|
||||||
|
String referer = shareUrl == null || shareUrl.isBlank() ? origin + "/" : shareUrl;
|
||||||
|
return new CtfileSession(newClient(info), origin, referer);
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonObject loadResource(String kind, String id, ShareTarget target, String password, String turnstileToken)
|
||||||
|
throws Exception {
|
||||||
|
JsonObject body = getResource(kind, id, target, password, null, null, null);
|
||||||
|
Decision decision = classify(body, 200, password);
|
||||||
|
if (decision.kind == Kind.OK) {
|
||||||
|
remember(decision, password, null);
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
// 带密码分享的首次响应经常标成 turnstile,但提交一次 ALTCHA 后正确密码会直接 200。
|
||||||
|
// 过期的 access_pass 同样会回到这个分支,丢弃后重新计算。
|
||||||
|
if (shouldSolveAltcha(decision)) {
|
||||||
|
String cached = cachedPass(decision.ownerId, password);
|
||||||
|
if (cached != null) {
|
||||||
|
JsonObject retry = getResource(kind, id, target, password, null, null, cached);
|
||||||
|
Decision again = classify(retry, 200, password);
|
||||||
|
if (again.kind == Kind.OK) {
|
||||||
|
remember(again, password, cached);
|
||||||
|
return retry;
|
||||||
|
}
|
||||||
|
forget(decision.ownerId, password);
|
||||||
|
}
|
||||||
|
JsonObject challenge = challenge();
|
||||||
|
if (expiresSoon(challenge)) {
|
||||||
|
challenge = challenge();
|
||||||
|
}
|
||||||
|
AltchaV2Solver.Solution solution = AltchaV2Solver.solve(challenge);
|
||||||
|
String token = AltchaV2Solver.payload(challenge, solution);
|
||||||
|
JsonObject retry = getResource(kind, id, target, password, token, null, null);
|
||||||
|
Decision solved = classify(retry, 200, password);
|
||||||
|
if (solved.kind == Kind.OK) {
|
||||||
|
remember(solved, password, null);
|
||||||
|
return retry;
|
||||||
|
}
|
||||||
|
if (solved.kind == Kind.ALTCHA) {
|
||||||
|
throw new CtfileException("ALTCHA 人机验证未通过,请重试");
|
||||||
|
}
|
||||||
|
if (solved.kind == Kind.TURNSTILE && turnstileToken != null && !turnstileToken.isBlank()) {
|
||||||
|
JsonObject withTurnstile = getResource(kind, id, target, password, null, turnstileToken, null);
|
||||||
|
Decision afterTurnstile = classify(withTurnstile, 200, password);
|
||||||
|
if (afterTurnstile.kind == Kind.OK) {
|
||||||
|
remember(afterTurnstile, password, null);
|
||||||
|
return withTurnstile;
|
||||||
|
}
|
||||||
|
throw new CtfileException(afterTurnstile.message);
|
||||||
|
}
|
||||||
|
throw new CtfileException(solved.message);
|
||||||
|
}
|
||||||
|
throw new CtfileException(decision.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 匿名分享优先解 ALTCHA。首次响应写成 turnstile 时,正确密码仍可能被 ALTCHA 放行。 */
|
||||||
|
static boolean shouldSolveAltcha(Decision decision) {
|
||||||
|
return decision != null && (decision.kind == Kind.ALTCHA || decision.kind == Kind.TURNSTILE);
|
||||||
|
}
|
||||||
|
|
||||||
|
DirectLink download(String id, ShareTarget target, String password, JsonObject resource) throws Exception {
|
||||||
|
JsonObject data = dataOf(resource);
|
||||||
|
JsonObject file = data == null ? null : data.getJsonObject("file");
|
||||||
|
if (file == null) {
|
||||||
|
throw new CtfileException("下载参数不完整:上游没有返回文件信息");
|
||||||
|
}
|
||||||
|
String pass = firstNonBlank(data.getString("access_pass"), cachedPass(ownerId(data), password));
|
||||||
|
return postDownload(id, target, password, file, pass, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonObject listing(String kind, String id, ShareTarget target, String password, JsonObject resource,
|
||||||
|
int start, int length) throws Exception {
|
||||||
|
JsonObject data = dataOf(resource);
|
||||||
|
String pass = data == null ? null : firstNonBlank(data.getString("access_pass"), cachedPass(ownerId(data), password));
|
||||||
|
Map<String, String> query = resourceQuery(kind, id, target, password, null, null, pass);
|
||||||
|
query.put("start", String.valueOf(Math.max(0, start)));
|
||||||
|
query.put("length", String.valueOf(Math.max(1, length)));
|
||||||
|
return exchange("GET", "/url/listing?" + form(query), null, origin, referer);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int pageSize() {
|
||||||
|
return PAGE_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private DirectLink postDownload(String id, ShareTarget target, String password, JsonObject file, String pass,
|
||||||
|
int waitedSeconds) throws Exception {
|
||||||
|
if (waitedSeconds > 120) {
|
||||||
|
throw new CtfileException("下载需要等待的时间过长");
|
||||||
|
}
|
||||||
|
String verify = file.getString("verifycode", "");
|
||||||
|
String fileChk = file.getString("file_chk", "");
|
||||||
|
if (verify.isBlank() || fileChk.isBlank() || file.getValue("file_id") == null || file.getValue("userid") == null) {
|
||||||
|
throw new CtfileException("下载参数不完整:缺少 file_chk 或 verifycode");
|
||||||
|
}
|
||||||
|
JsonObject context = new JsonObject()
|
||||||
|
.put("kind", "file")
|
||||||
|
.put("id", id)
|
||||||
|
.put("folder_id", target.folderId)
|
||||||
|
.put("fk", target.fk)
|
||||||
|
.put("passcode", password == null ? "" : password)
|
||||||
|
.put("type_id", target.typeId);
|
||||||
|
if (pass != null && !pass.isBlank()) {
|
||||||
|
context.put("access_pass", pass);
|
||||||
|
}
|
||||||
|
JsonObject original = new JsonObject()
|
||||||
|
.put("file_id", file.getValue("file_id"))
|
||||||
|
.put("userid", file.getValue("userid"))
|
||||||
|
.put("file_chk", fileChk)
|
||||||
|
.put("start_time", file.getValue("start_time"))
|
||||||
|
.put("wait_seconds", file.getValue("wait_seconds"));
|
||||||
|
JsonObject body = new JsonObject()
|
||||||
|
.put("context", context)
|
||||||
|
.put("app", false)
|
||||||
|
.put("verifycode", verify)
|
||||||
|
.put("original_file", original)
|
||||||
|
.put("carrier", 0);
|
||||||
|
JsonObject response = exchange("POST", "/url/download", body.encode().getBytes(StandardCharsets.UTF_8),
|
||||||
|
origin, referer);
|
||||||
|
int top = codeOf(response, 200);
|
||||||
|
JsonObject data = dataOf(response);
|
||||||
|
int code = data != null && data.getValue("code") != null ? codeOf(data, top) : top;
|
||||||
|
String message = firstNonBlank(response.getString("msg"), response.getString("message"),
|
||||||
|
data == null ? "" : firstNonBlank(data.getString("msg"), data.getString("message")));
|
||||||
|
if (code == 218) {
|
||||||
|
int remaining = intValue(data == null ? null : data.getValue("remaining_seconds"),
|
||||||
|
intValue(response.getValue("remaining_seconds"), 1));
|
||||||
|
remaining = Math.max(1, Math.min(remaining, 30));
|
||||||
|
sleepSeconds(remaining);
|
||||||
|
return postDownload(id, target, password, file, pass, waitedSeconds + remaining);
|
||||||
|
}
|
||||||
|
if (code == 219) {
|
||||||
|
throw new CtfileException("需要登录后才能下载");
|
||||||
|
}
|
||||||
|
if (code == 403 && message.toLowerCase().contains("verification")) {
|
||||||
|
throw new VerificationMismatch("下载校验未通过或已过期,请重试");
|
||||||
|
}
|
||||||
|
String downurl = data == null ? null : data.getString("downurl");
|
||||||
|
if (code != 200 || downurl == null || downurl.isBlank()) {
|
||||||
|
throw new CtfileException(message.isBlank()
|
||||||
|
? "未返回下载地址 (code=" + code + ")"
|
||||||
|
: "未返回下载地址: " + message);
|
||||||
|
}
|
||||||
|
Map<String, String> headers = new LinkedHashMap<>();
|
||||||
|
if (data.getValue("headers") instanceof JsonObject headerJson) {
|
||||||
|
for (String key : headerJson.fieldNames()) {
|
||||||
|
Object value = headerJson.getValue(key);
|
||||||
|
if (key != null && value != null && !value.toString().isBlank()) {
|
||||||
|
headers.put(key, value.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new DirectLink(downurl, headers);
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonObject getResource(String kind, String id, ShareTarget target, String password,
|
||||||
|
String altchaToken, String turnstileToken, String accessPass) throws Exception {
|
||||||
|
Map<String, String> params = resourceQuery(kind, id, target, password, altchaToken, turnstileToken, accessPass);
|
||||||
|
return exchange("GET", "/url/resource?" + form(params), null, origin, referer);
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonObject challenge() throws Exception {
|
||||||
|
return exchange("GET", CHALLENGE_PATH, null, "https://h5.ctfile.com",
|
||||||
|
"https://h5.ctfile.com/captcha/altcha.html");
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonObject exchange(String method, String path, byte[] body, String requestOrigin, String requestReferer)
|
||||||
|
throws Exception {
|
||||||
|
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(API + path))
|
||||||
|
.timeout(REQUEST_TIMEOUT)
|
||||||
|
.header("User-Agent", UA)
|
||||||
|
.header("Accept", "application/json, text/plain, */*")
|
||||||
|
.header("Origin", requestOrigin)
|
||||||
|
.header("Referer", requestReferer);
|
||||||
|
if (body == null) {
|
||||||
|
builder.method(method, HttpRequest.BodyPublishers.noBody());
|
||||||
|
} else {
|
||||||
|
builder.header("Content-Type", "application/json");
|
||||||
|
builder.method(method, HttpRequest.BodyPublishers.ofByteArray(body));
|
||||||
|
}
|
||||||
|
HttpResponse<String> response;
|
||||||
|
try {
|
||||||
|
response = client.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new CtfileException("请求被中断");
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new CtfileException("请求失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
String text = response.body();
|
||||||
|
if (text == null || text.isBlank()) {
|
||||||
|
throw new CtfileException("上游返回空响应 (HTTP " + response.statusCode() + ")");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return new JsonObject(text);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new CtfileException("上游返回了无法识别的响应 (HTTP " + response.statusCode() + ")");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Map<String, String> resourceQuery(String kind, String id, ShareTarget target, String password,
|
||||||
|
String altchaToken, String turnstileToken, String accessPass) {
|
||||||
|
Map<String, String> query = new LinkedHashMap<>();
|
||||||
|
query.put("kind", kind == null || kind.isBlank() ? "file" : kind);
|
||||||
|
query.put("id", id == null ? "" : id);
|
||||||
|
query.put("folder_id", target.folderId);
|
||||||
|
query.put("fk", target.fk);
|
||||||
|
query.put("passcode", password == null ? "" : password);
|
||||||
|
query.put("type_id", target.typeId);
|
||||||
|
if (altchaToken != null && !altchaToken.isBlank()) {
|
||||||
|
query.put("altcha_token", altchaToken);
|
||||||
|
}
|
||||||
|
if (turnstileToken != null && !turnstileToken.isBlank()) {
|
||||||
|
query.put("turnstile_token", turnstileToken);
|
||||||
|
}
|
||||||
|
if (accessPass != null && !accessPass.isBlank()) {
|
||||||
|
query.put("access_pass", accessPass);
|
||||||
|
}
|
||||||
|
return query;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String form(Map<String, String> query) {
|
||||||
|
StringBuilder builder = new StringBuilder();
|
||||||
|
for (Map.Entry<String, String> entry : query.entrySet()) {
|
||||||
|
if (entry.getValue() == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (builder.length() > 0) {
|
||||||
|
builder.append('&');
|
||||||
|
}
|
||||||
|
builder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
|
||||||
|
builder.append('=');
|
||||||
|
builder.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
return builder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
static Decision classify(JsonObject body, int httpStatus, String password) {
|
||||||
|
int code = codeOf(body, httpStatus);
|
||||||
|
JsonObject data = dataOf(body);
|
||||||
|
String message = firstNonBlank(body == null ? "" : body.getString("msg"),
|
||||||
|
body == null ? "" : body.getString("message"));
|
||||||
|
String errorType = data == null ? "" : text(data.getValue("error_type"));
|
||||||
|
String captcha = data == null ? "" : text(data.getValue("captcha_type"));
|
||||||
|
JsonObject capabilities = data == null ? null : data.getJsonObject("capabilities");
|
||||||
|
boolean passcodeRequired = capabilities != null && Boolean.TRUE.equals(capabilities.getValue("passcodeRequired"));
|
||||||
|
String owner = capabilities == null ? "" : text(capabilities.getValue("ownerId"));
|
||||||
|
boolean passwordMissing = password == null || password.isBlank();
|
||||||
|
boolean captchaAsked = "captcha_required".equals(errorType) || errorType.startsWith("captcha_");
|
||||||
|
|
||||||
|
if (code == 200) {
|
||||||
|
return Decision.ok(owner, accessPass(data));
|
||||||
|
}
|
||||||
|
if (code == 404) {
|
||||||
|
return Decision.of(Kind.NOT_FOUND, owner, "分享不存在或已过期" + suffix(message));
|
||||||
|
}
|
||||||
|
if (code == 403) {
|
||||||
|
return Decision.of(Kind.INVALID, owner, "分享链接无效或已失效" + suffix(message));
|
||||||
|
}
|
||||||
|
if (code == 423) {
|
||||||
|
if ("passcode_incorrect".equals(errorType)) {
|
||||||
|
return Decision.of(Kind.BAD_PASSWORD, owner, "访问密码不正确" + suffix(message));
|
||||||
|
}
|
||||||
|
if (passwordMissing && passcodeRequired && !captchaAsked) {
|
||||||
|
return Decision.of(Kind.NEED_PASSWORD, owner, "需要访问密码");
|
||||||
|
}
|
||||||
|
if ("turnstile".equalsIgnoreCase(captcha)) {
|
||||||
|
return Decision.of(Kind.TURNSTILE, owner, "触发 Cloudflare Turnstile 人机验证,暂不支持服务端自动通过");
|
||||||
|
}
|
||||||
|
if ("altcha".equalsIgnoreCase(captcha)) {
|
||||||
|
return Decision.of(Kind.ALTCHA, owner, "需要完成 ALTCHA 人机验证");
|
||||||
|
}
|
||||||
|
if (passwordMissing && passcodeRequired) {
|
||||||
|
return Decision.of(Kind.NEED_PASSWORD, owner, "需要访问密码");
|
||||||
|
}
|
||||||
|
return Decision.of(Kind.OTHER, owner, "分享暂时无法访问" + suffix(message) + " (code=423)");
|
||||||
|
}
|
||||||
|
return Decision.of(Kind.OTHER, owner,
|
||||||
|
"上游返回异常 (code=" + code + ")" + suffix(message));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void remember(Decision decision, String password, String fallbackPass) {
|
||||||
|
String token = firstNonBlank(decision.accessPass, fallbackPass);
|
||||||
|
if (decision.ownerId == null || decision.ownerId.isBlank() || token == null || token.isBlank()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
long expiry = passExpiry(token);
|
||||||
|
if (expiry < System.currentTimeMillis() + PASS_SKEW_MILLIS) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ACCESS_PASSES.put(cacheKey(decision.ownerId, password), new CachedPass(token, expiry));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String cachedPass(String ownerId, String password) {
|
||||||
|
if (ownerId == null || ownerId.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
CachedPass cached = ACCESS_PASSES.get(cacheKey(ownerId, password));
|
||||||
|
if (cached == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (cached.expiresAtMillis < System.currentTimeMillis() + PASS_SKEW_MILLIS) {
|
||||||
|
ACCESS_PASSES.remove(cacheKey(ownerId, password), cached);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return cached.token;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void forget(String ownerId, String password) {
|
||||||
|
if (ownerId != null && !ownerId.isBlank()) {
|
||||||
|
ACCESS_PASSES.remove(cacheKey(ownerId, password));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void clearCachedPasses() {
|
||||||
|
ACCESS_PASSES.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String cacheKey(String ownerId, String password) {
|
||||||
|
return ownerId + "\n" + (password == null ? "" : password);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long passExpiry(String token) {
|
||||||
|
try {
|
||||||
|
String[] parts = token.split("\\.");
|
||||||
|
if (parts.length < 2) {
|
||||||
|
return System.currentTimeMillis() + Duration.ofMinutes(30).toMillis();
|
||||||
|
}
|
||||||
|
byte[] json = Base64.getUrlDecoder().decode(padBase64(parts[1]));
|
||||||
|
JsonObject payload = new JsonObject(new String(json, StandardCharsets.UTF_8));
|
||||||
|
Object expiry = payload.getValue("e");
|
||||||
|
if (expiry instanceof Number) {
|
||||||
|
return ((Number) expiry).longValue() * 1000L;
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// 解析不了有效期时按半小时使用,失效后会重新计算 ALTCHA。
|
||||||
|
}
|
||||||
|
return System.currentTimeMillis() + Duration.ofMinutes(30).toMillis();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean expiresSoon(JsonObject challenge) {
|
||||||
|
JsonObject parameters = challenge.getJsonObject("parameters");
|
||||||
|
if (parameters == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Object expiry = parameters.getValue("expiresAt");
|
||||||
|
if (!(expiry instanceof Number)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
long expiresAtMillis = ((Number) expiry).longValue() * 1000L;
|
||||||
|
return expiresAtMillis < System.currentTimeMillis() + 15_000L;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String accessPass(JsonObject data) {
|
||||||
|
return data == null ? "" : text(data.getValue("access_pass"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String ownerId(JsonObject data) {
|
||||||
|
if (data == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
JsonObject capabilities = data.getJsonObject("capabilities");
|
||||||
|
return capabilities == null ? "" : text(capabilities.getValue("ownerId"));
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonObject dataOf(JsonObject body) {
|
||||||
|
if (body == null || !(body.getValue("data") instanceof JsonObject)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return body.getJsonObject("data");
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonArray rowsOf(JsonObject listing) {
|
||||||
|
JsonObject data = dataOf(listing);
|
||||||
|
if (data == null || !(data.getValue("rows") instanceof JsonArray)) {
|
||||||
|
return new JsonArray();
|
||||||
|
}
|
||||||
|
return data.getJsonArray("rows");
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean hasMore(JsonObject listing, int rowCount) {
|
||||||
|
JsonObject data = dataOf(listing);
|
||||||
|
if (data != null && data.getValue("hasMore") instanceof Boolean) {
|
||||||
|
return data.getBoolean("hasMore");
|
||||||
|
}
|
||||||
|
return rowCount >= PAGE_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int codeOf(JsonObject body, int fallback) {
|
||||||
|
if (body == null) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
return intValue(body.getValue("code"), fallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int intValue(Object value, int fallback) {
|
||||||
|
if (value instanceof Number) {
|
||||||
|
return ((Number) value).intValue();
|
||||||
|
}
|
||||||
|
if (value == null) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(value.toString());
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static long longValue(Object value, long fallback) {
|
||||||
|
if (value instanceof Number) {
|
||||||
|
return ((Number) value).longValue();
|
||||||
|
}
|
||||||
|
if (value == null) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Long.parseLong(value.toString());
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String suffix(String message) {
|
||||||
|
return message == null || message.isBlank() ? "" : "(" + message + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
static String text(Object value) {
|
||||||
|
return value == null ? "" : value.toString().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
static String firstNonBlank(String... values) {
|
||||||
|
if (values == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
for (String value : values) {
|
||||||
|
if (value != null && !value.isBlank()) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String padBase64(String value) {
|
||||||
|
int mod = value.length() % 4;
|
||||||
|
if (mod == 0) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return value + "=".repeat(4 - mod);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void sleepSeconds(int seconds) throws CtfileException {
|
||||||
|
try {
|
||||||
|
Thread.sleep(seconds * 1000L);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new CtfileException("下载等待被中断");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String originOf(String shareUrl) {
|
||||||
|
if (shareUrl == null || shareUrl.isBlank()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
URI uri = URI.create(shareUrl);
|
||||||
|
if (uri.getScheme() == null || uri.getHost() == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String origin = uri.getScheme() + "://" + uri.getHost();
|
||||||
|
return uri.getPort() > 0 ? origin + ":" + uri.getPort() : origin;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static String queryParam(String url, String name) {
|
||||||
|
if (url == null || name == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
int query = url.indexOf('?');
|
||||||
|
if (query < 0) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String raw = url.substring(query + 1);
|
||||||
|
int hash = raw.indexOf('#');
|
||||||
|
if (hash >= 0) {
|
||||||
|
raw = raw.substring(0, hash);
|
||||||
|
}
|
||||||
|
for (String part : raw.split("&")) {
|
||||||
|
int eq = part.indexOf('=');
|
||||||
|
if (eq <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String key = decode(part.substring(0, eq));
|
||||||
|
if (name.equals(key)) {
|
||||||
|
return decode(part.substring(eq + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String decode(String value) {
|
||||||
|
try {
|
||||||
|
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static HttpClient newClient(ShareLinkInfo info) {
|
||||||
|
HttpClient.Builder builder = HttpClient.newBuilder()
|
||||||
|
.version(HttpClient.Version.HTTP_1_1)
|
||||||
|
.connectTimeout(Duration.ofSeconds(10))
|
||||||
|
.followRedirects(HttpClient.Redirect.NEVER);
|
||||||
|
Object proxyValue = info == null || info.getOtherParam() == null ? null : info.getOtherParam().get("proxy");
|
||||||
|
if (proxyValue instanceof JsonObject proxy) {
|
||||||
|
String host = proxy.getString("host");
|
||||||
|
Integer port = proxy.getInteger("port");
|
||||||
|
if (host != null && !host.isBlank() && port != null) {
|
||||||
|
builder.proxy(ProxySelector.of(new InetSocketAddress(host, port)));
|
||||||
|
String username = proxy.getString("username");
|
||||||
|
String password = proxy.getString("password", "");
|
||||||
|
if (username != null && !username.isBlank()) {
|
||||||
|
builder.authenticator(new Authenticator() {
|
||||||
|
@Override
|
||||||
|
protected PasswordAuthentication getPasswordAuthentication() {
|
||||||
|
if (getRequestorType() == RequestorType.PROXY) {
|
||||||
|
return new PasswordAuthentication(username, password.toCharArray());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return builder.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
try {
|
||||||
|
client.getClass().getMethod("close").invoke(client);
|
||||||
|
} catch (NoSuchMethodException ignored) {
|
||||||
|
// JDK 17 的 HttpClient 还不能关闭,连接会按空闲超时回收。
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// 关闭失败不影响解析结果。
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static final class ShareTarget {
|
||||||
|
final String folderId;
|
||||||
|
final String fk;
|
||||||
|
final String typeId;
|
||||||
|
|
||||||
|
ShareTarget(String folderId, String fk, String typeId) {
|
||||||
|
this.folderId = folderId == null || folderId.isBlank() ? "0" : folderId;
|
||||||
|
this.fk = fk == null ? "" : fk;
|
||||||
|
this.typeId = typeId == null || typeId.isBlank() ? "0" : typeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
static ShareTarget from(ShareLinkInfo info) {
|
||||||
|
String dirId = "";
|
||||||
|
if (info.getOtherParam() != null && info.getOtherParam().get("dirId") != null) {
|
||||||
|
dirId = decode(info.getOtherParam().get("dirId").toString().trim());
|
||||||
|
}
|
||||||
|
if (!dirId.isBlank()) {
|
||||||
|
String[] parts = dirId.split(":", 2);
|
||||||
|
return new ShareTarget(parts[0], parts.length > 1 ? parts[1] : "",
|
||||||
|
queryParam(info.getShareUrl(), "type_id"));
|
||||||
|
}
|
||||||
|
String shareUrl = info.getShareUrl();
|
||||||
|
String folderId = firstNonBlank(queryParam(shareUrl, "folder_id"), queryParam(shareUrl, "d"));
|
||||||
|
return new ShareTarget(folderId, queryParam(shareUrl, "fk"), queryParam(shareUrl, "type_id"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static final class DirectLink {
|
||||||
|
final String url;
|
||||||
|
final Map<String, String> headers;
|
||||||
|
|
||||||
|
DirectLink(String url, Map<String, String> headers) {
|
||||||
|
this.url = url;
|
||||||
|
this.headers = headers;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Kind {
|
||||||
|
OK, NOT_FOUND, INVALID, NEED_PASSWORD, BAD_PASSWORD, TURNSTILE, ALTCHA, OTHER
|
||||||
|
}
|
||||||
|
|
||||||
|
static final class Decision {
|
||||||
|
final Kind kind;
|
||||||
|
final String ownerId;
|
||||||
|
final String accessPass;
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
private Decision(Kind kind, String ownerId, String accessPass, String message) {
|
||||||
|
this.kind = kind;
|
||||||
|
this.ownerId = ownerId == null ? "" : ownerId;
|
||||||
|
this.accessPass = accessPass == null ? "" : accessPass;
|
||||||
|
this.message = message == null ? "" : message;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Decision ok(String ownerId, String accessPass) {
|
||||||
|
return new Decision(Kind.OK, ownerId, accessPass, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
static Decision of(Kind kind, String ownerId, String message) {
|
||||||
|
return new Decision(kind, ownerId, "", message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static class CtfileException extends Exception {
|
||||||
|
CtfileException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static final class VerificationMismatch extends CtfileException {
|
||||||
|
VerificationMismatch(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class CachedPass {
|
||||||
|
final String token;
|
||||||
|
final long expiresAtMillis;
|
||||||
|
|
||||||
|
CachedPass(String token, long expiresAtMillis) {
|
||||||
|
this.token = token;
|
||||||
|
this.expiresAtMillis = expiresAtMillis;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,679 @@
|
|||||||
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.WebClientVertxInit;
|
||||||
|
import cn.qaiu.entity.FileInfo;
|
||||||
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import cn.qaiu.parser.TokenCache;
|
||||||
|
import cn.qaiu.parser.impl.CtfileSession.CtfileException;
|
||||||
|
import cn.qaiu.util.CommonUtils;
|
||||||
|
import io.vertx.core.MultiMap;
|
||||||
|
import io.vertx.core.json.JsonArray;
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 城通官方客户端协议 {@code /v4}。匿名 ALTCHA 仍被 Turnstile 拦住时的可选回退,
|
||||||
|
* 需要调用方自己的登录令牌。带访问密码的分享默认不走这里。
|
||||||
|
*/
|
||||||
|
final class CtfileV4Client {
|
||||||
|
|
||||||
|
static final String API = "https://api.ctfile.com";
|
||||||
|
private static final String UA = "Mozilla/5.0 CTFileApp/5.1.24";
|
||||||
|
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(20);
|
||||||
|
private static final long EXPIRY_SKEW_MILLIS = 60_000L;
|
||||||
|
private static final int PAGE_SIZE = 100;
|
||||||
|
|
||||||
|
private static final ConcurrentHashMap<String, Session> SESSIONS = new ConcurrentHashMap<>();
|
||||||
|
private static final HttpClient HTTP = HttpClient.newBuilder()
|
||||||
|
.connectTimeout(Duration.ofSeconds(10))
|
||||||
|
.followRedirects(HttpClient.Redirect.NEVER)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
private final ShareLinkInfo shareLinkInfo;
|
||||||
|
|
||||||
|
CtfileV4Client(ShareLinkInfo shareLinkInfo) {
|
||||||
|
this.shareLinkInfo = shareLinkInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean hasCredentials(ShareLinkInfo info) {
|
||||||
|
return credentials(info).usable();
|
||||||
|
}
|
||||||
|
|
||||||
|
static String missingAccountMessage() {
|
||||||
|
return "匿名解析仍被 Cloudflare Turnstile 拦住,且未配置城通账号。"
|
||||||
|
+ "可在 app-dev.yml 配置 auths.ct.refresh_token 作为可选回退,或在请求 auth 中传入。"
|
||||||
|
+ "refresh_token 来自浏览器登录 pan.ctfile.com 后 Session Storage 中的 refresh_token;"
|
||||||
|
+ "token 可填当前 access token。目录类型 ctd 未单独配置时回退使用 ct。";
|
||||||
|
}
|
||||||
|
|
||||||
|
DirectLink downloadShare(String shareKey, boolean directory) throws Exception {
|
||||||
|
String explicitFileId = text(shareLinkInfo.getOtherParam().get("ctV4FileId"));
|
||||||
|
String xtlink = text(shareLinkInfo.getOtherParam().get("ctXtlink"));
|
||||||
|
if (xtlink.isBlank()) {
|
||||||
|
xtlink = CtfileXtlink.fromShare(shareKey, shareLinkInfo.getSharePassword(), directory && explicitFileId.isBlank());
|
||||||
|
}
|
||||||
|
if (xtlink == null) {
|
||||||
|
throw new CtfileException("这个分享标识不能转换成官方 xtlink");
|
||||||
|
}
|
||||||
|
String fileId = explicitFileId.isBlank()
|
||||||
|
? CtfileXtlink.prefixedId(shareId(shareKey), false)
|
||||||
|
: CtfileXtlink.prefixedId(explicitFileId, false);
|
||||||
|
if (fileId.isBlank()) {
|
||||||
|
throw new CtfileException("分享标识里没有文件 id,无法取直链");
|
||||||
|
}
|
||||||
|
String token = accessToken(false);
|
||||||
|
JsonObject listed = null;
|
||||||
|
try {
|
||||||
|
listed = post("/v4/public/browser/list", listBody(xtlink, "0", 0, 20), token);
|
||||||
|
} catch (V4CallException e) {
|
||||||
|
if (e.authenticationFailure()) {
|
||||||
|
token = recoverAuth(e, token);
|
||||||
|
try {
|
||||||
|
listed = post("/v4/public/browser/list", listBody(xtlink, "0", 0, 20), token);
|
||||||
|
} catch (V4CallException again) {
|
||||||
|
if (terminal(again)) {
|
||||||
|
throw again;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (terminal(e)) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
JsonObject matched = listed == null ? null : findItem(listed, fileId);
|
||||||
|
String url = fetchDownloadUrl(xtlink, fileId, token);
|
||||||
|
JsonObject file = new JsonObject()
|
||||||
|
.put("file_name", matched == null ? shareLinkInfo.getShareKey() : itemName(matched))
|
||||||
|
.put("file_id", CtfileXtlink.bareId(fileId))
|
||||||
|
.put("file_size_bytes", matched == null ? 0 : itemSize(matched))
|
||||||
|
.put("file_size", matched == null ? "" : String.valueOf(itemSize(matched)))
|
||||||
|
.put("username", "");
|
||||||
|
if (matched != null && !itemDate(matched).isBlank()) {
|
||||||
|
file.put("file_time", itemDate(matched));
|
||||||
|
}
|
||||||
|
return new DirectLink(url, file);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<FileInfo> listShare(String shareKey, String folderId, int maxPages) throws Exception {
|
||||||
|
boolean directory = true;
|
||||||
|
String xtlink = CtfileXtlink.fromShare(shareKey, shareLinkInfo.getSharePassword(), directory);
|
||||||
|
if (xtlink == null) {
|
||||||
|
throw new CtfileException("这个分享标识不能转换成官方 xtlink");
|
||||||
|
}
|
||||||
|
String token = accessToken(false);
|
||||||
|
List<FileInfo> files = new ArrayList<>();
|
||||||
|
int start = 0;
|
||||||
|
String apiFolder = folderId == null || folderId.isBlank() || "0".equals(folderId) ? "0" : CtfileXtlink.bareId(folderId);
|
||||||
|
for (int page = 0; page < maxPages; page++) {
|
||||||
|
JsonObject body;
|
||||||
|
try {
|
||||||
|
body = post("/v4/public/browser/list", listBody(xtlink, apiFolder, start, PAGE_SIZE), token);
|
||||||
|
} catch (V4CallException e) {
|
||||||
|
token = recoverAuth(e, token);
|
||||||
|
body = post("/v4/public/browser/list", listBody(xtlink, apiFolder, start, PAGE_SIZE), token);
|
||||||
|
}
|
||||||
|
JsonArray rows = resultsOf(body);
|
||||||
|
if (rows.isEmpty()) {
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < rows.size(); i++) {
|
||||||
|
if (rows.getValue(i) instanceof JsonObject row) {
|
||||||
|
FileInfo info = toFileInfo(row, shareLinkInfo, xtlink);
|
||||||
|
if (info != null) {
|
||||||
|
files.add(info);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int total = totalOf(body);
|
||||||
|
start += rows.size();
|
||||||
|
if (rows.size() < PAGE_SIZE || (total >= 0 && start >= total)) {
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String fetchDownloadUrl(String xtlink, String fileId, String token) throws Exception {
|
||||||
|
JsonObject auth;
|
||||||
|
try {
|
||||||
|
auth = post("/v4/public/browser/create-download-auth", authBody(xtlink, CtfileXtlink.prefixedId(fileId, false)), token);
|
||||||
|
} catch (V4CallException e) {
|
||||||
|
token = recoverAuth(e, token);
|
||||||
|
auth = post("/v4/public/browser/create-download-auth", authBody(xtlink, CtfileXtlink.prefixedId(fileId, false)), token);
|
||||||
|
}
|
||||||
|
String signature = signatureOf(auth);
|
||||||
|
if (signature.isBlank()) {
|
||||||
|
throw new CtfileException("城通没有返回下载签名,可能是密码错误、分享失效或账号没有下载权限");
|
||||||
|
}
|
||||||
|
JsonObject fetched;
|
||||||
|
try {
|
||||||
|
fetched = post("/v4/public/browser/fetch-url", fetchBody(xtlink, CtfileXtlink.bareId(fileId), signature), token);
|
||||||
|
} catch (V4CallException e) {
|
||||||
|
token = recoverAuth(e, token);
|
||||||
|
fetched = post("/v4/public/browser/fetch-url", fetchBody(xtlink, CtfileXtlink.bareId(fileId), signature), token);
|
||||||
|
}
|
||||||
|
String url = downloadUrlOf(fetched);
|
||||||
|
if (url.isBlank()) {
|
||||||
|
throw new CtfileException("城通没有返回下载直链");
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String recoverAuth(V4CallException error, String currentToken) throws Exception {
|
||||||
|
if (!error.authenticationFailure()) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
String refreshed = accessToken(true);
|
||||||
|
if (refreshed == null || refreshed.isBlank() || refreshed.equals(currentToken)) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return refreshed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String accessToken(boolean forceRefresh) throws Exception {
|
||||||
|
Credentials credentials = credentials(shareLinkInfo);
|
||||||
|
if (!credentials.usable()) {
|
||||||
|
throw new CtfileException(missingAccountMessage());
|
||||||
|
}
|
||||||
|
Session session = SESSIONS.computeIfAbsent(credentials.accountKey, key -> new Session());
|
||||||
|
synchronized (session) {
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
if ((session.refreshToken == null || session.refreshToken.isBlank()) && credentials.refreshToken != null) {
|
||||||
|
session.refreshToken = credentials.refreshToken;
|
||||||
|
}
|
||||||
|
if ((session.accessToken == null || session.accessToken.isBlank()) && credentials.accessToken != null) {
|
||||||
|
session.accessToken = credentials.accessToken;
|
||||||
|
}
|
||||||
|
if (!forceRefresh && session.accessToken != null && !session.accessToken.isBlank()
|
||||||
|
&& (session.expiresAtMillis == 0 || session.expiresAtMillis - EXPIRY_SKEW_MILLIS > now)) {
|
||||||
|
return session.accessToken;
|
||||||
|
}
|
||||||
|
if (session.refreshToken == null || session.refreshToken.isBlank()) {
|
||||||
|
if (session.accessToken != null && !session.accessToken.isBlank() && !forceRefresh) {
|
||||||
|
session.expiresAtMillis = 0;
|
||||||
|
return session.accessToken;
|
||||||
|
}
|
||||||
|
throw new CtfileException("城通 access token 已失效,且没有可用的 refresh_token。请重新登录后更新配置。");
|
||||||
|
}
|
||||||
|
RefreshResult refreshed = refresh(session.refreshToken);
|
||||||
|
session.accessToken = refreshed.accessToken;
|
||||||
|
session.expiresAtMillis = now + refreshed.expiresInSeconds * 1000L;
|
||||||
|
if (refreshed.refreshToken != null && !refreshed.refreshToken.isBlank()
|
||||||
|
&& !refreshed.refreshToken.equals(session.refreshToken)) {
|
||||||
|
session.refreshToken = refreshed.refreshToken;
|
||||||
|
rememberRefreshToken(credentials, refreshed.refreshToken);
|
||||||
|
} else {
|
||||||
|
session.refreshToken = refreshed.refreshToken == null || refreshed.refreshToken.isBlank()
|
||||||
|
? session.refreshToken : refreshed.refreshToken;
|
||||||
|
}
|
||||||
|
TokenCache.putToken(credentials.cacheKey(), session.accessToken);
|
||||||
|
TokenCache.putExpire(credentials.cacheKey(), session.expiresAtMillis);
|
||||||
|
TokenCache.queueCachedTokenPersist(credentials.cacheKey(), session.accessToken, session.expiresAtMillis);
|
||||||
|
return session.accessToken;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private RefreshResult refresh(String refreshToken) throws Exception {
|
||||||
|
V4CallException first = null;
|
||||||
|
try {
|
||||||
|
return readRefresh(post("/v4/user/auth/refresh-token", refreshBody(refreshToken, false), null), refreshToken);
|
||||||
|
} catch (V4CallException e) {
|
||||||
|
first = e;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return readRefresh(post("/v4/user/auth/refresh-token", refreshBody(refreshToken, true), null), refreshToken);
|
||||||
|
} catch (V4CallException e) {
|
||||||
|
throw first.messageKey.contains("invalid_refresh") ? first : e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonObject post(String path, JsonObject body, String accessToken) throws Exception {
|
||||||
|
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(API + path))
|
||||||
|
.timeout(REQUEST_TIMEOUT)
|
||||||
|
.header("User-Agent", UA)
|
||||||
|
.header("Accept", "application/json")
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.header("X-Client-Type", "native")
|
||||||
|
.header("X-Client-Version", "5.1.24")
|
||||||
|
.header("X-Client-Platform", "linux")
|
||||||
|
.header("X-Client-OS-Version", "6.1.0")
|
||||||
|
.header("X-Client-Arch", "x64")
|
||||||
|
.header("X-Client-Captcha", "image,turnstile,altcha,cap")
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofString(body.encode()));
|
||||||
|
if (accessToken != null && !accessToken.isBlank()) {
|
||||||
|
builder.header("Authorization", "Bearer " + accessToken);
|
||||||
|
}
|
||||||
|
HttpResponse<String> response;
|
||||||
|
try {
|
||||||
|
response = HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new CtfileException("城通客户端请求被中断");
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new CtfileException("城通客户端请求失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
String text = response.body() == null ? "" : response.body();
|
||||||
|
JsonObject json;
|
||||||
|
try {
|
||||||
|
json = new JsonObject(text);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new CtfileException("城通客户端返回了无法识别的响应 (HTTP " + response.statusCode() + ")");
|
||||||
|
}
|
||||||
|
int code = CtfileSession.intValue(json.getValue("code"), response.statusCode());
|
||||||
|
if (code != 200) {
|
||||||
|
throw new V4CallException(code, json.getString("message", ""), json.getString("message_key", ""));
|
||||||
|
}
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void rememberRefreshToken(Credentials credentials, String refreshToken) {
|
||||||
|
if (credentials.auths != null) {
|
||||||
|
credentials.auths.set("refresh_token", refreshToken);
|
||||||
|
}
|
||||||
|
TokenCache.queueCredentialUpdate(credentials.cacheKey(), refreshToken);
|
||||||
|
try {
|
||||||
|
Object auths = WebClientVertxInit.get().sharedData().getLocalMap("local").get("auths");
|
||||||
|
if (auths instanceof JsonObject json) {
|
||||||
|
for (String type : new String[] {"ct", "ctd"}) {
|
||||||
|
JsonObject config = json.getJsonObject(type);
|
||||||
|
if (config != null && config.containsKey("refresh_token")) {
|
||||||
|
config.put("refresh_token", refreshToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (RuntimeException ignored) {
|
||||||
|
// 单测或未启动服务时没有共享配置,进程内的 TokenCache 仍然保存新令牌。
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonObject listBody(String xtlink, String folderId, int start, int pageSize) {
|
||||||
|
Object folder = folderId != null && folderId.matches("\\d+") ? Long.parseLong(folderId) : folderId;
|
||||||
|
return new JsonObject()
|
||||||
|
.put("xtlink", xtlink)
|
||||||
|
.put("folder_id", folder)
|
||||||
|
.put("start", start)
|
||||||
|
.put("pagesize", pageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonObject authBody(String xtlink, String ids) {
|
||||||
|
return new JsonObject().put("xtlink", xtlink).put("ids", ids);
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonObject fetchBody(String xtlink, String fileId, String signature) {
|
||||||
|
return new JsonObject()
|
||||||
|
.put("file_id", fileId)
|
||||||
|
.put("download_sign", signature)
|
||||||
|
.put("xtlink", xtlink)
|
||||||
|
.put("carrier", 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonObject refreshBody(String refreshToken, boolean rotate) {
|
||||||
|
JsonObject body = new JsonObject().put("refresh_token", refreshToken);
|
||||||
|
if (rotate) {
|
||||||
|
body.put("rotate_token", true);
|
||||||
|
}
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String describeFailure(int code, String message, String messageKey) {
|
||||||
|
String text = message == null ? "" : message;
|
||||||
|
String key = messageKey == null ? "" : messageKey;
|
||||||
|
String lower = (text + " " + key).toLowerCase();
|
||||||
|
if (lower.contains("invalid_refresh") || lower.contains("refresh token") || text.contains("refresh token")) {
|
||||||
|
return "城通 refresh_token 无效或已过期,请重新登录 pan.ctfile.com 后更新 auths.ct.refresh_token";
|
||||||
|
}
|
||||||
|
if (text.contains("扫码") || text.contains("登录保护") || lower.contains("qr") || lower.contains("captcha_required")) {
|
||||||
|
return "城通账号需要扫码或完成登录保护后,再更新 refresh_token";
|
||||||
|
}
|
||||||
|
if (text.contains("锁定") && !text.contains("无效的令牌") && !text.contains("令牌无效")) {
|
||||||
|
return "城通账号已锁定";
|
||||||
|
}
|
||||||
|
if (code == 401 || text.contains("无效的令牌") || text.contains("未登录") || text.contains("令牌无效")) {
|
||||||
|
return "城通登录令牌无效或账号已锁定";
|
||||||
|
}
|
||||||
|
if (code == 404 || text.contains("不存在") || text.contains("失效") || lower.contains("not found")) {
|
||||||
|
return "分享不存在或已过期";
|
||||||
|
}
|
||||||
|
if (text.contains("密码") || lower.contains("passcode") || lower.contains("password")) {
|
||||||
|
return "访问密码不正确";
|
||||||
|
}
|
||||||
|
if (code == 403) {
|
||||||
|
return "城通拒绝了这次下载" + (text.isBlank() ? "" : "(" + text + ")");
|
||||||
|
}
|
||||||
|
return "城通客户端接口返回错误 (code=" + code + ")" + (text.isBlank() ? "" : ":" + text);
|
||||||
|
}
|
||||||
|
|
||||||
|
static FileInfo toFileInfo(JsonObject item, ShareLinkInfo info, String xtlink) {
|
||||||
|
if (item == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String name = itemName(item);
|
||||||
|
if (name.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String key = itemKey(item);
|
||||||
|
boolean folder = isFolder(item, key);
|
||||||
|
String password = info.getSharePassword() == null ? "" : info.getSharePassword();
|
||||||
|
FileInfo fileInfo = new FileInfo()
|
||||||
|
.setFileName(name)
|
||||||
|
.setPanType(info.getType())
|
||||||
|
.setFileId(CtfileXtlink.bareId(key));
|
||||||
|
String date = itemDate(item);
|
||||||
|
if (!date.isBlank()) {
|
||||||
|
fileInfo.setCreateTime(date).setUpdateTime(date);
|
||||||
|
}
|
||||||
|
String domain = info.getOtherParam() == null ? "" : String.valueOf(info.getOtherParam().getOrDefault("domainName", ""));
|
||||||
|
if (folder) {
|
||||||
|
return fileInfo.setFileType("folder")
|
||||||
|
.setSize(0L)
|
||||||
|
.setSizeStr("0B")
|
||||||
|
.setParserUrl(domain + "/v2/getFileList?url=" + url(info.getShareUrl())
|
||||||
|
+ "&dirId=" + url(CtfileXtlink.bareId(key))
|
||||||
|
+ (password.isBlank() ? "" : "&pwd=" + url(password)));
|
||||||
|
}
|
||||||
|
long size = itemSize(item);
|
||||||
|
JsonObject param = new JsonObject()
|
||||||
|
.put("id", CtfileXtlink.prefixedId(key, false))
|
||||||
|
.put("pwd", password)
|
||||||
|
.put("fileName", name)
|
||||||
|
.put("xtlink", xtlink)
|
||||||
|
.put("shareKey", info.getShareKey() == null ? "" : info.getShareKey());
|
||||||
|
String kind = CtfileSession.firstNonBlank(text(item.getValue("icon")), text(item.getValue("ext")), "file");
|
||||||
|
return fileInfo.setFileType(kind)
|
||||||
|
.setSize(size)
|
||||||
|
.setSizeStr(size > 0 ? size + "B" : text(item.getValue("size")))
|
||||||
|
.setParserUrl(domain + "/v2/redirectUrl/" + info.getType() + "/"
|
||||||
|
+ CommonUtils.urlBase64Encode(param.encode()));
|
||||||
|
}
|
||||||
|
|
||||||
|
static Credentials credentials(ShareLinkInfo info) {
|
||||||
|
MultiMap auths = null;
|
||||||
|
if (info != null && info.getOtherParam() != null && info.getOtherParam().get("auths") instanceof MultiMap map) {
|
||||||
|
auths = map;
|
||||||
|
}
|
||||||
|
String refresh = firstAuth(auths, "refresh_token", "refreshToken");
|
||||||
|
String access = firstAuth(auths, "token", "authorization", "access_token", "accessToken");
|
||||||
|
String accountId = firstAuth(auths, "_configId");
|
||||||
|
if ((refresh == null || refresh.isBlank()) && (access == null || access.isBlank())) {
|
||||||
|
JsonObject shared = sharedAuth(info == null ? "" : info.getType());
|
||||||
|
if (shared != null) {
|
||||||
|
refresh = firstJson(shared, "refresh_token", "refreshToken");
|
||||||
|
access = firstJson(shared, "token", "authorization", "access_token", "accessToken");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (accountId == null || accountId.isBlank()) {
|
||||||
|
accountId = refresh != null && !refresh.isBlank() ? "refresh" : "access";
|
||||||
|
}
|
||||||
|
return new Credentials(auths, accountId, blankToNull(refresh), blankToNull(stripBearer(access)));
|
||||||
|
}
|
||||||
|
|
||||||
|
static void clearSessions() {
|
||||||
|
SESSIONS.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static JsonObject sharedAuth(String type) {
|
||||||
|
try {
|
||||||
|
Object auths = WebClientVertxInit.get().sharedData().getLocalMap("local").get("auths");
|
||||||
|
if (!(auths instanceof JsonObject json)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
JsonObject config = type == null ? null : json.getJsonObject(type);
|
||||||
|
if ((config == null || config.isEmpty()) && "ctd".equalsIgnoreCase(type)) {
|
||||||
|
config = json.getJsonObject("ct");
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RefreshResult readRefresh(JsonObject json, String previous) throws CtfileException {
|
||||||
|
String token = firstJson(json, "token", "access_token", "accessToken");
|
||||||
|
JsonObject data = json.getJsonObject("data");
|
||||||
|
if ((token == null || token.isBlank()) && data != null) {
|
||||||
|
token = firstJson(data, "token", "access_token", "accessToken");
|
||||||
|
}
|
||||||
|
if (token == null || token.isBlank()) {
|
||||||
|
throw new CtfileException("刷新城通登录状态失败:上游没有返回 access token");
|
||||||
|
}
|
||||||
|
String rotated = firstJson(json, "refresh_token", "refreshToken");
|
||||||
|
if ((rotated == null || rotated.isBlank()) && data != null) {
|
||||||
|
rotated = firstJson(data, "refresh_token", "refreshToken");
|
||||||
|
}
|
||||||
|
int expires = CtfileSession.intValue(json.getValue("expires_in"), -1);
|
||||||
|
if (expires < 0 && data != null) {
|
||||||
|
expires = CtfileSession.intValue(data.getValue("expires_in"), 900);
|
||||||
|
}
|
||||||
|
if (expires < 0) {
|
||||||
|
expires = 900;
|
||||||
|
}
|
||||||
|
return new RefreshResult(token, rotated == null || rotated.isBlank() ? previous : rotated, expires);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String signatureOf(JsonObject json) {
|
||||||
|
JsonObject data = json.getJsonObject("data");
|
||||||
|
String signature = data == null ? "" : data.getString("download_signature", "");
|
||||||
|
if (signature.isBlank()) {
|
||||||
|
signature = json.getString("download_signature", "");
|
||||||
|
}
|
||||||
|
return signature;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String downloadUrlOf(JsonObject json) {
|
||||||
|
JsonObject data = json.getJsonObject("data");
|
||||||
|
String url = data == null ? "" : data.getString("download_url", "");
|
||||||
|
if (url.isBlank() && data != null) {
|
||||||
|
url = data.getString("url", "");
|
||||||
|
}
|
||||||
|
if (url.isBlank()) {
|
||||||
|
url = json.getString("download_url", "");
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static JsonArray resultsOf(JsonObject json) {
|
||||||
|
JsonObject data = json.getJsonObject("data");
|
||||||
|
if (data != null && data.getValue("results") instanceof JsonArray rows) {
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
if (json.getValue("results") instanceof JsonArray rows) {
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
return new JsonArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int totalOf(JsonObject json) {
|
||||||
|
JsonObject data = json.getJsonObject("data");
|
||||||
|
if (data == null) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int total = CtfileSession.intValue(data.getValue("totalNum"), -1);
|
||||||
|
return total >= 0 ? total : CtfileSession.intValue(data.getValue("num"), -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static JsonObject findItem(JsonObject listed, String fileId) {
|
||||||
|
String bare = CtfileXtlink.bareId(fileId);
|
||||||
|
for (int i = 0; i < resultsOf(listed).size(); i++) {
|
||||||
|
if (!(resultsOf(listed).getValue(i) instanceof JsonObject row)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (bare.equals(CtfileXtlink.bareId(itemKey(row)))) {
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
JsonArray rows = resultsOf(listed);
|
||||||
|
if (rows.size() == 1 && rows.getValue(0) instanceof JsonObject only && !isFolder(only, itemKey(only))) {
|
||||||
|
return only;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isFolder(JsonObject item, String key) {
|
||||||
|
if (Boolean.TRUE.equals(item.getValue("is_folder"))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
String type = item.getString("type", "");
|
||||||
|
String icon = item.getString("icon", "");
|
||||||
|
String ext = item.getString("ext", "");
|
||||||
|
return "folder".equalsIgnoreCase(type) || "folder".equalsIgnoreCase(icon) || "folder".equalsIgnoreCase(ext)
|
||||||
|
|| (key != null && key.startsWith("d"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String itemKey(JsonObject item) {
|
||||||
|
return CtfileSession.firstNonBlank(text(item.getValue("fid")), text(item.getValue("key")), text(item.getValue("id")));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String itemName(JsonObject item) {
|
||||||
|
return item.getString("name", "").trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long itemSize(JsonObject item) {
|
||||||
|
long size = CtfileSession.longValue(item.getValue("size_bytes"), -1);
|
||||||
|
if (size >= 0) {
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
return CtfileSession.longValue(item.getValue("size"), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String itemDate(JsonObject item) {
|
||||||
|
return CtfileSession.firstNonBlank(text(item.getValue("date")), text(item.getValue("file_time")));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String shareId(String shareKey) {
|
||||||
|
if (shareKey == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String[] parts = shareKey.split("-");
|
||||||
|
return parts.length >= 2 ? parts[1] : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String firstAuth(MultiMap auths, String... keys) {
|
||||||
|
if (auths == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (String key : keys) {
|
||||||
|
String value = auths.get(key);
|
||||||
|
if (value != null && !value.isBlank()) {
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String firstJson(JsonObject json, String... keys) {
|
||||||
|
if (json == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (String key : keys) {
|
||||||
|
String value = json.getString(key);
|
||||||
|
if (value != null && !value.isBlank()) {
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String stripBearer(String token) {
|
||||||
|
if (token == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String value = token.trim();
|
||||||
|
if (value.regionMatches(true, 0, "Bearer ", 0, 7)) {
|
||||||
|
return value.substring(7).trim();
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String blankToNull(String value) {
|
||||||
|
return value == null || value.isBlank() ? null : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String text(Object value) {
|
||||||
|
return value == null ? "" : value.toString().trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String url(String value) {
|
||||||
|
return java.net.URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
static final class Credentials {
|
||||||
|
final MultiMap auths;
|
||||||
|
final String accountId;
|
||||||
|
final String refreshToken;
|
||||||
|
final String accessToken;
|
||||||
|
final String accountKey;
|
||||||
|
|
||||||
|
Credentials(MultiMap auths, String accountId, String refreshToken, String accessToken) {
|
||||||
|
this.auths = auths;
|
||||||
|
this.accountId = accountId;
|
||||||
|
this.refreshToken = refreshToken;
|
||||||
|
this.accessToken = accessToken;
|
||||||
|
this.accountKey = accountId == null ? "default" : accountId;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean usable() {
|
||||||
|
return (refreshToken != null && !refreshToken.isBlank()) || (accessToken != null && !accessToken.isBlank());
|
||||||
|
}
|
||||||
|
|
||||||
|
String cacheKey() {
|
||||||
|
return TokenCache.key("ct", accountKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static final class DirectLink {
|
||||||
|
final String url;
|
||||||
|
final JsonObject file;
|
||||||
|
|
||||||
|
DirectLink(String url, JsonObject file) {
|
||||||
|
this.url = url;
|
||||||
|
this.file = file;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Session {
|
||||||
|
String refreshToken;
|
||||||
|
String accessToken;
|
||||||
|
long expiresAtMillis;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class RefreshResult {
|
||||||
|
final String accessToken;
|
||||||
|
final String refreshToken;
|
||||||
|
final int expiresInSeconds;
|
||||||
|
|
||||||
|
RefreshResult(String accessToken, String refreshToken, int expiresInSeconds) {
|
||||||
|
this.accessToken = accessToken;
|
||||||
|
this.refreshToken = refreshToken;
|
||||||
|
this.expiresInSeconds = expiresInSeconds;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static final class V4CallException extends CtfileException {
|
||||||
|
final int code;
|
||||||
|
final String messageKey;
|
||||||
|
|
||||||
|
V4CallException(int code, String message, String messageKey) {
|
||||||
|
super(describeFailure(code, message, messageKey));
|
||||||
|
this.code = code;
|
||||||
|
this.messageKey = messageKey == null ? "" : messageKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean authenticationFailure() {
|
||||||
|
return code == 401 || getMessage().contains("令牌") || getMessage().contains("锁定");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean terminal(V4CallException error) {
|
||||||
|
String message = error.getMessage() == null ? "" : error.getMessage();
|
||||||
|
return message.contains("密码") || message.contains("不存在") || message.contains("已过期") || message.contains("失效");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把网页分享 key 转成官方客户端 xtlink。
|
||||||
|
* 免密是 {@code xturl{userid}-{f|d}{id}[-checksum]},
|
||||||
|
* 带密码是 {@code xtc{userid}-{f|d}{id}-{checksum}-{password}}。
|
||||||
|
*/
|
||||||
|
final class CtfileXtlink {
|
||||||
|
|
||||||
|
private CtfileXtlink() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static String fromShare(String shareKey, String password, boolean directory) {
|
||||||
|
if (shareKey == null || shareKey.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("分享标识为空,无法生成 xtlink");
|
||||||
|
}
|
||||||
|
String key = shareKey.trim();
|
||||||
|
if (key.startsWith("ctfile://")) {
|
||||||
|
key = key.substring("ctfile://".length());
|
||||||
|
}
|
||||||
|
if (key.startsWith("xturl") || key.startsWith("xtc")) {
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
if (key.startsWith("t-")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String[] parts = key.split("-");
|
||||||
|
if (parts.length < 2 || parts[0].isBlank() || parts[1].isBlank()) {
|
||||||
|
throw new IllegalArgumentException("分享标识无法转换成 xtlink: " + shareKey);
|
||||||
|
}
|
||||||
|
String userId = parts[0];
|
||||||
|
String rawId = parts[1];
|
||||||
|
String checksum = parts.length >= 3 ? parts[2] : "";
|
||||||
|
if (!rawId.matches("[fd]\\d+")) {
|
||||||
|
rawId = (directory ? "d" : "f") + rawId;
|
||||||
|
}
|
||||||
|
boolean hasPassword = password != null && !password.isBlank();
|
||||||
|
if (!hasPassword) {
|
||||||
|
return checksum.isEmpty()
|
||||||
|
? "xturl" + userId + "-" + rawId
|
||||||
|
: "xturl" + userId + "-" + rawId + "-" + checksum;
|
||||||
|
}
|
||||||
|
if (checksum.isEmpty()) {
|
||||||
|
return "xtc" + userId + "-" + rawId + "-" + password;
|
||||||
|
}
|
||||||
|
return "xtc" + userId + "-" + rawId + "-" + checksum + "-" + password;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String prefixedId(String fileId, boolean directory) {
|
||||||
|
if (fileId == null || fileId.isBlank()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String value = fileId.trim();
|
||||||
|
if (value.matches("[fd]\\d+")) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
String digits = value.replaceAll("\\D", "");
|
||||||
|
if (digits.isEmpty()) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return (directory || value.startsWith("d") ? "d" : "f") + digits;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String bareId(String fileId) {
|
||||||
|
String prefixed = prefixedId(fileId, false);
|
||||||
|
if (prefixed.matches("[fd]\\d+")) {
|
||||||
|
return prefixed.substring(1);
|
||||||
|
}
|
||||||
|
return prefixed;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,9 +22,14 @@ public class FcTool extends PanBase {
|
|||||||
|
|
||||||
public static final String SHARE_URL_PREFIX = "https://v2.fangcloud.com/sharing/";
|
public static final String SHARE_URL_PREFIX = "https://v2.fangcloud.com/sharing/";
|
||||||
public static final String SHARE_URL_PREFIX2 = "https://v2.fangcloud.cn/sharing/";
|
public static final String SHARE_URL_PREFIX2 = "https://v2.fangcloud.cn/sharing/";
|
||||||
|
private static final String SHARE_INFO_URL = "https://v2.fangcloud.cn/apps/share_links/info/";
|
||||||
private static final String DOWN_REQUEST_URL = "https://v2.fangcloud.cn/apps/files/download?file_id={fid}" +
|
private static final String DOWN_REQUEST_URL = "https://v2.fangcloud.cn/apps/files/download?file_id={fid}" +
|
||||||
"&scenario=share&unique_name={uname}";
|
"&scenario=share&unique_name={uname}";
|
||||||
|
|
||||||
|
// 静态编译的正则表达式,避免每次调用都重新编译
|
||||||
|
private static final Pattern REQUEST_TOKEN_PATTERN = Pattern.compile("name=\"requesttoken\"\\s+value=\"([a-zA-Z0-9_+=]+)\"");
|
||||||
|
private static final Pattern TYPED_ID_PATTERN = Pattern.compile("id=\"typed_id\"\\s+value=\"file_(\\d+)\"");
|
||||||
|
|
||||||
public FcTool(ShareLinkInfo shareLinkInfo) {
|
public FcTool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
}
|
}
|
||||||
@@ -34,6 +39,25 @@ public class FcTool extends PanBase {
|
|||||||
final String dataKey = shareLinkInfo.getShareKey();
|
final String dataKey = shareLinkInfo.getShareKey();
|
||||||
final String pwd = shareLinkInfo.getSharePassword();
|
final String pwd = shareLinkInfo.getSharePassword();
|
||||||
WebClientSession sClient = WebClientSession.create(client);
|
WebClientSession sClient = WebClientSession.create(client);
|
||||||
|
// 先查询分享有效性, 避免分享已失效/已过期时仍去解析HTML, 报出令人困惑的技术错误
|
||||||
|
sClient.getAbs(SHARE_INFO_URL + dataKey).send().onSuccess(infoRes -> {
|
||||||
|
JsonObject infoJson = asJson(infoRes);
|
||||||
|
if (promise.future().isComplete()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JsonObject process = infoJson.getJsonObject("process");
|
||||||
|
boolean isClosed = process != null && Boolean.TRUE.equals(process.getBoolean("is_closed"));
|
||||||
|
boolean isExpired = process != null && Boolean.TRUE.equals(process.getBoolean("is_expired"));
|
||||||
|
if (process == null || isClosed || isExpired) {
|
||||||
|
fail("分享已失效或不存在");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
doParse(dataKey, pwd, sClient);
|
||||||
|
}).onFailure(handleFail(SHARE_INFO_URL + dataKey));
|
||||||
|
return promise.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void doParse(String dataKey, String pwd, WebClientSession sClient) {
|
||||||
// 第一次请求 自动重定向
|
// 第一次请求 自动重定向
|
||||||
sClient.getAbs(SHARE_URL_PREFIX + dataKey).send().onSuccess(res -> {
|
sClient.getAbs(SHARE_URL_PREFIX + dataKey).send().onSuccess(res -> {
|
||||||
|
|
||||||
@@ -41,8 +65,7 @@ public class FcTool extends PanBase {
|
|||||||
if (StringUtils.isNotEmpty(pwd)) {
|
if (StringUtils.isNotEmpty(pwd)) {
|
||||||
// 获取requesttoken
|
// 获取requesttoken
|
||||||
String html = res.bodyAsString();
|
String html = res.bodyAsString();
|
||||||
Pattern compile = Pattern.compile("name=\"requesttoken\"\\s+value=\"([a-zA-Z0-9_+=]+)\"");
|
Matcher matcher = REQUEST_TOKEN_PATTERN.matcher(html);
|
||||||
Matcher matcher = compile.matcher(html);
|
|
||||||
if (!matcher.find()) {
|
if (!matcher.find()) {
|
||||||
fail(SHARE_URL_PREFIX + " 未匹配到加密分享的密码输入页面的requesttoken");
|
fail(SHARE_URL_PREFIX + " 未匹配到加密分享的密码输入页面的requesttoken");
|
||||||
return;
|
return;
|
||||||
@@ -64,15 +87,13 @@ public class FcTool extends PanBase {
|
|||||||
}
|
}
|
||||||
getDownURL(dataKey, promise, res, sClient);
|
getDownURL(dataKey, promise, res, sClient);
|
||||||
}).onFailure(handleFail(SHARE_URL_PREFIX + dataKey));
|
}).onFailure(handleFail(SHARE_URL_PREFIX + dataKey));
|
||||||
return promise.future();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void getDownURL(String dataKey, Promise<String> promise, HttpResponse<Buffer> res,
|
private void getDownURL(String dataKey, Promise<String> promise, HttpResponse<Buffer> res,
|
||||||
WebClientSession sClient) {
|
WebClientSession sClient) {
|
||||||
// 从HTML中找到文件id
|
// 从HTML中找到文件id
|
||||||
String html = res.bodyAsString();
|
String html = res.bodyAsString();
|
||||||
Pattern compile = Pattern.compile("id=\"typed_id\"\\s+value=\"file_(\\d+)\"");
|
Matcher matcher = TYPED_ID_PATTERN.matcher(html);
|
||||||
Matcher matcher = compile.matcher(html);
|
|
||||||
if (!matcher.find()) {
|
if (!matcher.find()) {
|
||||||
fail(SHARE_URL_PREFIX + " 未匹配到文件id(typed_id)");
|
fail(SHARE_URL_PREFIX + " 未匹配到文件id(typed_id)");
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.util.AESUtils;
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
final class FjDownloadParams {
|
||||||
|
private FjDownloadParams() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static JsonObject create(String fileId, String userId, String uuid, String shareId, long timestamp) {
|
||||||
|
if (StringUtils.isBlank(fileId) || StringUtils.isBlank(shareId)) {
|
||||||
|
throw new IllegalArgumentException("缺少 fileId 或 shareId");
|
||||||
|
}
|
||||||
|
return JsonObject.of("fileId", fileId,
|
||||||
|
"fidEncode", AESUtils.encrypt2Hex(fileId + "|" + StringUtils.defaultString(userId)),
|
||||||
|
"uuid", uuid, "shareId", shareId,
|
||||||
|
"ts", AESUtils.encrypt2Hex(Long.toString(timestamp)),
|
||||||
|
"auth", AESUtils.encrypt2Hex(fileId + "|" + timestamp));
|
||||||
|
}
|
||||||
|
|
||||||
|
static String fileId(JsonObject params) throws Exception {
|
||||||
|
String fileId = params.getString("fileId");
|
||||||
|
if (StringUtils.isNotBlank(fileId)) {
|
||||||
|
return fileId;
|
||||||
|
}
|
||||||
|
// 兼容已生成的目录链接,但不再复用其中的身份和过期签名。
|
||||||
|
String decoded = AESUtils.decryptByHexAES(params.getString("fidEncode"), AESUtils.CIPHER_AES0);
|
||||||
|
int separator = decoded.indexOf('|');
|
||||||
|
if (separator <= 0) {
|
||||||
|
throw new IllegalArgumentException("无效的 fidEncode");
|
||||||
|
}
|
||||||
|
return decoded.substring(0, separator);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String ownerId(JsonObject params) throws Exception {
|
||||||
|
Object id = params.getValue("userId");
|
||||||
|
if (id != null && StringUtils.isNotBlank(id.toString())) {
|
||||||
|
return id.toString();
|
||||||
|
}
|
||||||
|
String encoded = params.getString("fidEncode");
|
||||||
|
if (StringUtils.isBlank(encoded)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String decoded = AESUtils.decryptByHexAES(encoded, AESUtils.CIPHER_AES0);
|
||||||
|
int separator = decoded.indexOf('|');
|
||||||
|
String owner = separator < 0 ? null : decoded.substring(separator + 1);
|
||||||
|
return StringUtils.isBlank(owner) || "null".equals(owner) ? null : owner;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String missingLocation(int status, String body) {
|
||||||
|
String message = "未获取到下载重定向地址, HTTP " + status;
|
||||||
|
if (StringUtils.isBlank(body)) {
|
||||||
|
return message + ", 响应体为空";
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
JsonObject json = new JsonObject(body);
|
||||||
|
if (StringUtils.isNotBlank(json.getString("msg"))) {
|
||||||
|
return message + ", 上游返回: " + preview(json.getString("msg"))
|
||||||
|
+ " (code=" + json.getValue("code") + ")";
|
||||||
|
}
|
||||||
|
} catch (RuntimeException ignored) {
|
||||||
|
// 非 JSON 错误页同样保留有限长度的诊断内容。
|
||||||
|
}
|
||||||
|
return message + ", 响应体: " + preview(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String preview(String value) {
|
||||||
|
return value.length() > 500 ? value.substring(0, 500) + "..." : value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package cn.qaiu.parser.impl;
|
|||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import cn.qaiu.parser.FolderPaging;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.util.*;
|
import cn.qaiu.util.*;
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
@@ -60,7 +61,10 @@ public class FjTool extends PanBase {
|
|||||||
|
|
||||||
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
||||||
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
||||||
"={folderId}&offset=1&limit=60";
|
"={folderId}&offset={offset}&limit={limit}";
|
||||||
|
|
||||||
|
/** share/list 每页条数;offset 是从 1 开始的页码。 */
|
||||||
|
static final int LIST_LIMIT = 60;
|
||||||
|
|
||||||
private static final MultiMap header;
|
private static final MultiMap header;
|
||||||
private static final MultiMap header0;
|
private static final MultiMap header0;
|
||||||
@@ -109,9 +113,9 @@ public class FjTool extends PanBase {
|
|||||||
|
|
||||||
// String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
|
// String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
|
||||||
|
|
||||||
static String token = null;
|
static volatile String token = null;
|
||||||
static String userId = null;
|
static volatile String userId = null;
|
||||||
public static boolean authFlag = true;
|
public static volatile boolean authFlag = true;
|
||||||
|
|
||||||
public FjTool(ShareLinkInfo shareLinkInfo) {
|
public FjTool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
@@ -129,8 +133,6 @@ public class FjTool extends PanBase {
|
|||||||
if (auths.contains("userId")) {
|
if (auths.contains("userId")) {
|
||||||
FjTool.userId = auths.get("userId");
|
FjTool.userId = auths.get("userId");
|
||||||
log.info("已配置用户ID: {}", FjTool.userId);
|
log.info("已配置用户ID: {}", FjTool.userId);
|
||||||
} else {
|
|
||||||
log.warn("未配置用户ID, 可能会导致解析失败");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,8 +171,13 @@ public class FjTool extends PanBase {
|
|||||||
|
|
||||||
// 文件Id
|
// 文件Id
|
||||||
JsonObject fileInfo = resJson.getJsonArray("list").getJsonObject(0);
|
JsonObject fileInfo = resJson.getJsonArray("list").getJsonObject(0);
|
||||||
|
JsonArray fileListArray = fileInfo.getJsonArray("fileList");
|
||||||
|
if (fileListArray == null || fileListArray.isEmpty()) {
|
||||||
|
fail(FIRST_REQUEST_URL + " 文件列表为空: " + fileInfo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
// 如果是目录返回目录ID
|
// 如果是目录返回目录ID
|
||||||
JsonObject fileList = fileInfo.getJsonArray("fileList").getJsonObject(0);
|
JsonObject fileList = fileListArray.getJsonObject(0);
|
||||||
if (fileList.getInteger("fileType") == 2) {
|
if (fileList.getInteger("fileType") == 2) {
|
||||||
promise.complete(fileList.getInteger("folderId").toString());
|
promise.complete(fileList.getInteger("folderId").toString());
|
||||||
return;
|
return;
|
||||||
@@ -194,7 +201,7 @@ public class FjTool extends PanBase {
|
|||||||
// 其他参数
|
// 其他参数
|
||||||
long nowTs2 = System.currentTimeMillis();
|
long nowTs2 = System.currentTimeMillis();
|
||||||
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
||||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId);
|
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
||||||
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
||||||
|
|
||||||
// 检查是否有认证信息
|
// 检查是否有认证信息
|
||||||
@@ -218,7 +225,7 @@ public class FjTool extends PanBase {
|
|||||||
log.warn("登录失败: {}", failRes.getMessage());
|
log.warn("登录失败: {}", failRes.getMessage());
|
||||||
fail(failRes.getMessage());
|
fail(failRes.getMessage());
|
||||||
}).onSuccess(r-> {
|
}).onSuccess(r-> {
|
||||||
httpRequest.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId))
|
httpRequest.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + userId))
|
||||||
.putHeaders(header);
|
.putHeaders(header);
|
||||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||||
});
|
});
|
||||||
@@ -240,7 +247,7 @@ public class FjTool extends PanBase {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
httpRequest
|
httpRequest
|
||||||
.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId))
|
.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + userId))
|
||||||
.putHeaders(header);
|
.putHeaders(header);
|
||||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||||
}
|
}
|
||||||
@@ -289,12 +296,14 @@ public class FjTool extends PanBase {
|
|||||||
JsonObject json = asJson(res2);
|
JsonObject json = asJson(res2);
|
||||||
if (json.getInteger("code") == 200) {
|
if (json.getInteger("code") == 200) {
|
||||||
token = json.getJsonObject("data").getString("appToken");
|
token = json.getJsonObject("data").getString("appToken");
|
||||||
header0.set("appToken", token);
|
MultiMap h0 = MultiMap.caseInsensitiveMultiMap();
|
||||||
log.info("登录成功 token: {}", token);
|
h0.addAll(header0);
|
||||||
|
h0.set("appToken", token);
|
||||||
|
log.info("登录成功 token: {}...", token != null ? token.substring(0, Math.min(8, token.length())) : "null");
|
||||||
client.postAbs(UriTemplate.of(TOKEN_VERIFY_URL))
|
client.postAbs(UriTemplate.of(TOKEN_VERIFY_URL))
|
||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode2)
|
.setTemplateParam("ts", tsEncode2)
|
||||||
.putHeaders(header0).send().onSuccess(res -> {
|
.putHeaders(h0).send().onSuccess(res -> {
|
||||||
if (asJson(res).getInteger("code") == 200) {
|
if (asJson(res).getInteger("code") == 200) {
|
||||||
if (FjTool.userId == null) {
|
if (FjTool.userId == null) {
|
||||||
FjTool.userId = asJson(res).getJsonObject("map").getString("userId");
|
FjTool.userId = asJson(res).getJsonObject("map").getString("userId");
|
||||||
@@ -437,8 +446,15 @@ public class FjTool extends PanBase {
|
|||||||
|
|
||||||
private void down(HttpResponse<Buffer> res2) {
|
private void down(HttpResponse<Buffer> res2) {
|
||||||
MultiMap headers = res2.headers();
|
MultiMap headers = res2.headers();
|
||||||
if (!headers.contains("Location") || headers.get("Location") == null) {
|
if (StringUtils.isBlank(headers.get("Location"))) {
|
||||||
fail("找不到下载链接可能服务器已被禁止或者配置的认证信息有误: " + res2.bodyAsString());
|
String body;
|
||||||
|
try {
|
||||||
|
body = asText(res2);
|
||||||
|
} catch (IllegalArgumentException | UnsupportedOperationException e) {
|
||||||
|
fail(e, "读取下载错误响应失败, HTTP {}", res2.statusCode());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fail("{}", FjDownloadParams.missingLocation(res2.statusCode(), body));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
promise.complete(headers.get("Location"));
|
promise.complete(headers.get("Location"));
|
||||||
@@ -454,7 +470,10 @@ public class FjTool extends PanBase {
|
|||||||
// 如果参数里的目录ID不为空,则直接解析目录
|
// 如果参数里的目录ID不为空,则直接解析目录
|
||||||
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
|
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
|
||||||
if (dirId != null && !dirId.isEmpty()) {
|
if (dirId != null && !dirId.isEmpty()) {
|
||||||
uuid = shareLinkInfo.getOtherParam().get("uuid").toString();
|
Object uuidObj = shareLinkInfo.getOtherParam().get("uuid");
|
||||||
|
if (uuidObj != null) {
|
||||||
|
uuid = uuidObj.toString();
|
||||||
|
}
|
||||||
parserDir(dirId, shareId, promise0);
|
parserDir(dirId, shareId, promise0);
|
||||||
return promise0.future();
|
return promise0.future();
|
||||||
}
|
}
|
||||||
@@ -477,7 +496,11 @@ public class FjTool extends PanBase {
|
|||||||
.setParserUrl(id)
|
.setParserUrl(id)
|
||||||
.setPanType(shareLinkInfo.getType());
|
.setPanType(shareLinkInfo.getType());
|
||||||
List<FileInfo> result = new ArrayList<>();
|
List<FileInfo> result = new ArrayList<>();
|
||||||
result.add(fileInfo);
|
int page = FolderPaging.pageOrFirst(shareLinkInfo);
|
||||||
|
if (page == 1) {
|
||||||
|
result.add(fileInfo);
|
||||||
|
}
|
||||||
|
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -491,84 +514,101 @@ public class FjTool extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
|
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
||||||
|
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
JsonArray list;
|
JsonArray list;
|
||||||
|
JsonObject jsonObject;
|
||||||
try {
|
try {
|
||||||
JsonObject jsonObject = asJson(res);
|
jsonObject = asJson(res);
|
||||||
System.out.println(jsonObject.encodePrettily());
|
log.debug("目录列表: {}", jsonObject.encodePrettily());
|
||||||
list = jsonObject.getJsonArray("list");
|
list = jsonObject.getJsonArray("list");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("解析目录失败: {}", res.bodyAsString());
|
log.error("解析目录失败: {}", res.bodyAsString());
|
||||||
|
promise.tryFail("目录解析失败: 响应不是 JSON");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (list == null) {
|
||||||
|
promise.tryFail("目录解析失败: 响应缺少 list 字段: " + jsonObject);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ArrayList<FileInfo> result = new ArrayList<>();
|
ArrayList<FileInfo> result = new ArrayList<>();
|
||||||
list.forEach(item->{
|
try {
|
||||||
JsonObject fileJson = (JsonObject) item;
|
list.forEach(item->{
|
||||||
FileInfo fileInfo = new FileInfo();
|
JsonObject fileJson = (JsonObject) item;
|
||||||
|
FileInfo fileInfo = new FileInfo();
|
||||||
|
|
||||||
// 映射已知字段fileInfo
|
// 映射已知字段fileInfo
|
||||||
String fileId = fileJson.getString("fileId");
|
String fileId = fileJson.getString("fileId");
|
||||||
String userId = fileJson.getString("userId");
|
String userId = fileJson.getString("userId");
|
||||||
|
|
||||||
// 其他参数
|
// 其他参数
|
||||||
long nowTs2 = System.currentTimeMillis();
|
long nowTs2 = System.currentTimeMillis();
|
||||||
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
||||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId);
|
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
||||||
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
||||||
|
|
||||||
// 回传用到的参数
|
// 回传用到的参数
|
||||||
//"fidEncode", paramJson.getString("fidEncode"))
|
//"fidEncode", paramJson.getString("fidEncode"))
|
||||||
//"uuid", paramJson.getString("uuid"))
|
//"uuid", paramJson.getString("uuid"))
|
||||||
//"ts", paramJson.getString("ts"))
|
//"ts", paramJson.getString("ts"))
|
||||||
//"auth", paramJson.getString("auth"))
|
//"auth", paramJson.getString("auth"))
|
||||||
//"shareId", paramJson.getString("shareId"))
|
//"shareId", paramJson.getString("shareId"))
|
||||||
JsonObject entries = JsonObject.of(
|
JsonObject entries = JsonObject.of(
|
||||||
"fidEncode", fidEncode,
|
"fileId", fileId,
|
||||||
"uuid", uuid,
|
"userId", userId,
|
||||||
"ts", tsEncode2,
|
"fidEncode", fidEncode,
|
||||||
"auth", auth,
|
"uuid", uuid,
|
||||||
"shareId", shareId);
|
"ts", tsEncode2,
|
||||||
String param = CommonUtils.urlBase64Encode(entries.encode());
|
"auth", auth,
|
||||||
|
"shareId", shareId);
|
||||||
|
String param = CommonUtils.urlBase64Encode(entries.encode());
|
||||||
|
|
||||||
if (fileJson.getInteger("fileType") == 2) {
|
if (fileJson.getInteger("fileType") == 2) {
|
||||||
// 如果是目录
|
// 如果是目录
|
||||||
fileInfo.setFileName(fileJson.getString("name"))
|
fileInfo.setFileName(fileJson.getString("name"))
|
||||||
.setFileId(fileJson.getString("folderId"))
|
.setFileId(fileJson.getString("folderId"))
|
||||||
.setCreateTime(fileJson.getString("updTime"))
|
.setCreateTime(fileJson.getString("updTime"))
|
||||||
.setFileType("folder")
|
.setFileType("folder")
|
||||||
.setSize(0L)
|
.setSize(0L)
|
||||||
.setSizeStr("0B")
|
.setSizeStr("0B")
|
||||||
|
.setCreateBy(fileJson.getLong("userId").toString())
|
||||||
|
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
||||||
|
.setCreateTime(fileJson.getString("updTime"))
|
||||||
|
.setFileIcon(fileJson.getString("fileIcon"))
|
||||||
|
.setPanType(shareLinkInfo.getType())
|
||||||
|
// 设置目录解析的URL
|
||||||
|
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&uuid=%s", getDomainName(),
|
||||||
|
shareLinkInfo.getShareUrl(), fileJson.getString("folderId"), uuid));
|
||||||
|
result.add(fileInfo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
long fileSize = fileJson.getLong("fileSize") * 1024;
|
||||||
|
fileInfo.setFileName(fileJson.getString("fileName"))
|
||||||
|
.setFileId(fileJson.getString("fileId"))
|
||||||
|
.setCreateTime(fileJson.getString("createTime"))
|
||||||
|
.setFileType("file")
|
||||||
|
.setSize(fileSize)
|
||||||
|
.setSizeStr(FileSizeConverter.convertToReadableSize(fileSize))
|
||||||
.setCreateBy(fileJson.getLong("userId").toString())
|
.setCreateBy(fileJson.getLong("userId").toString())
|
||||||
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
||||||
.setCreateTime(fileJson.getString("updTime"))
|
.setCreateTime(fileJson.getString("updTime"))
|
||||||
.setFileIcon(fileJson.getString("fileIcon"))
|
.setFileIcon(fileJson.getString("fileIcon"))
|
||||||
.setPanType(shareLinkInfo.getType())
|
.setPanType(shareLinkInfo.getType())
|
||||||
// 设置目录解析的URL
|
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(),
|
||||||
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&uuid=%s", getDomainName(),
|
shareLinkInfo.getType(), param))
|
||||||
shareLinkInfo.getShareUrl(), fileJson.getString("folderId"), uuid));
|
.setPreviewUrl(String.format("%s/v2/viewUrl/%s/%s", getDomainName(),
|
||||||
|
shareLinkInfo.getType(), param));
|
||||||
result.add(fileInfo);
|
result.add(fileInfo);
|
||||||
return;
|
});
|
||||||
}
|
} catch (Exception e) {
|
||||||
long fileSize = fileJson.getLong("fileSize") * 1024;
|
log.error("目录列表条目解析失败: {}", jsonObject, e);
|
||||||
fileInfo.setFileName(fileJson.getString("fileName"))
|
promise.tryFail("目录解析失败: 列表条目格式异常 " + e);
|
||||||
.setFileId(fileJson.getString("fileId"))
|
return;
|
||||||
.setCreateTime(fileJson.getString("createTime"))
|
}
|
||||||
.setFileType("file")
|
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
|
||||||
.setSize(fileSize)
|
|
||||||
.setSizeStr(FileSizeConverter.convertToReadableSize(fileSize))
|
|
||||||
.setCreateBy(fileJson.getLong("userId").toString())
|
|
||||||
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
|
||||||
.setCreateTime(fileJson.getString("updTime"))
|
|
||||||
.setFileIcon(fileJson.getString("fileIcon"))
|
|
||||||
.setPanType(shareLinkInfo.getType())
|
|
||||||
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(),
|
|
||||||
shareLinkInfo.getType(), param))
|
|
||||||
.setPreviewUrl(String.format("%s/v2/viewUrl/%s/%s", getDomainName(),
|
|
||||||
shareLinkInfo.getType(), param));
|
|
||||||
result.add(fileInfo);
|
|
||||||
});
|
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
});
|
}).onFailure(err -> promise.tryFail("目录解析失败: " + err.getMessage()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -576,20 +616,28 @@ public class FjTool extends PanBase {
|
|||||||
|
|
||||||
// 第二次请求
|
// 第二次请求
|
||||||
JsonObject paramJson = (JsonObject)shareLinkInfo.getOtherParam().get("paramJson");
|
JsonObject paramJson = (JsonObject)shareLinkInfo.getOtherParam().get("paramJson");
|
||||||
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
if (paramJson == null) {
|
||||||
.setTemplateParam("fidEncode", paramJson.getString("fidEncode"))
|
promise.fail("缺少 paramJson 参数");
|
||||||
.setTemplateParam("uuid", paramJson.getString("uuid"))
|
return promise.future();
|
||||||
.setTemplateParam("ts", paramJson.getString("ts"))
|
}
|
||||||
.setTemplateParam("auth", paramJson.getString("auth"))
|
try {
|
||||||
.setTemplateParam("dataKey", paramJson.getString("shareId"))
|
String ownerId = FjDownloadParams.ownerId(paramJson);
|
||||||
.putHeaders(header).send().onSuccess(res2 -> {
|
if (StringUtils.isBlank(ownerId) || "null".equals(ownerId)) {
|
||||||
MultiMap headers = res2.headers();
|
fail("目录下载参数缺少分享者 userId,请刷新文件列表后重试");
|
||||||
if (!headers.contains("Location")) {
|
return promise.future();
|
||||||
fail(SECOND_REQUEST_URL_VIP + " 未找到重定向URL: \n" + res2.headers());
|
}
|
||||||
return;
|
JsonObject params = FjDownloadParams.create(FjDownloadParams.fileId(paramJson), ownerId,
|
||||||
}
|
paramJson.getString("uuid"), paramJson.getString("shareId"), System.currentTimeMillis());
|
||||||
promise.complete(headers.get("Location"));
|
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
||||||
}).onFailure(handleFail(SECOND_REQUEST_URL_VIP));
|
.setTemplateParam("fidEncode", params.getString("fidEncode"))
|
||||||
|
.setTemplateParam("uuid", params.getString("uuid"))
|
||||||
|
.setTemplateParam("ts", params.getString("ts"))
|
||||||
|
.setTemplateParam("auth", params.getString("auth"))
|
||||||
|
.setTemplateParam("dataKey", params.getString("shareId"))
|
||||||
|
.putHeaders(header).send().onSuccess(this::down).onFailure(handleFail("下载请求"));
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail(e, "下载参数无效");
|
||||||
|
}
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -389,6 +389,10 @@ public class FsTool extends PanBase {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
JsonObject paramJson = (JsonObject) shareLinkInfo.getOtherParam().get("paramJson");
|
JsonObject paramJson = (JsonObject) shareLinkInfo.getOtherParam().get("paramJson");
|
||||||
|
if (paramJson == null) {
|
||||||
|
parsePromise.fail("缺少 paramJson 参数");
|
||||||
|
return parsePromise.future();
|
||||||
|
}
|
||||||
String shareUrl = paramJson.getString("shareUrl");
|
String shareUrl = paramJson.getString("shareUrl");
|
||||||
String objToken = paramJson.getString("objToken");
|
String objToken = paramJson.getString("objToken");
|
||||||
String tenant = extractTenant(shareUrl);
|
String tenant = extractTenant(shareUrl);
|
||||||
@@ -444,7 +448,7 @@ public class FsTool extends PanBase {
|
|||||||
if (m1.find()) {
|
if (m1.find()) {
|
||||||
try {
|
try {
|
||||||
return URLDecoder.decode(m1.group(1).trim(), StandardCharsets.UTF_8);
|
return URLDecoder.decode(m1.group(1).trim(), StandardCharsets.UTF_8);
|
||||||
} catch (Exception ignored) {
|
} catch (IllegalArgumentException ignored) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -453,7 +457,7 @@ public class FsTool extends PanBase {
|
|||||||
if (m2.find()) {
|
if (m2.find()) {
|
||||||
try {
|
try {
|
||||||
return URLDecoder.decode(m2.group(1).trim(), StandardCharsets.UTF_8);
|
return URLDecoder.decode(m2.group(1).trim(), StandardCharsets.UTF_8);
|
||||||
} catch (Exception ignored) {
|
} catch (IllegalArgumentException ignored) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package cn.qaiu.parser.impl;
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.util.Base64Encoder;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import io.netty.handler.codec.http.cookie.Cookie;
|
import io.netty.handler.codec.http.cookie.Cookie;
|
||||||
@@ -14,7 +15,6 @@ import org.slf4j.LoggerFactory;
|
|||||||
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@@ -31,10 +31,12 @@ public class GenShortUrl extends PanBase {
|
|||||||
private static final String WRAPPER_URL = "https://www.so.com/link?m=ewgUSYiFWXIoTybC3fJH8YoJy8y10iRquo6cazgINwWjTn3HvVJ92TrCJu0PmMUR0RMDfOAucP3wa4G8j64SrhNH9Z0Cr0PEyn9ASuvpkUGmAjjUEGJkO5%2BIDGWVrEkPHsL7UsoKO6%2BlT%2BD6r&ccc=";
|
private static final String WRAPPER_URL = "https://www.so.com/link?m=ewgUSYiFWXIoTybC3fJH8YoJy8y10iRquo6cazgINwWjTn3HvVJ92TrCJu0PmMUR0RMDfOAucP3wa4G8j64SrhNH9Z0Cr0PEyn9ASuvpkUGmAjjUEGJkO5%2BIDGWVrEkPHsL7UsoKO6%2BlT%2BD6r&ccc=";
|
||||||
private static final String MID = "5095144728824883"; // 微博的mid
|
private static final String MID = "5095144728824883"; // 微博的mid
|
||||||
|
|
||||||
|
private static final Pattern SHORT_URL_PATTERN = Pattern.compile("(https?)://t.cn/\\w+");
|
||||||
|
private static final Pattern COMMENT_ID_PATTERN = Pattern.compile("comment_id=\"(\\d+)\"");
|
||||||
|
|
||||||
private static final MultiMap HEADER = HeadersMultiMap.headers()
|
private static final MultiMap HEADER = HeadersMultiMap.headers()
|
||||||
.add("Content-Type", "application/x-www-form-urlencoded")
|
.add("Content-Type", "application/x-www-form-urlencoded")
|
||||||
.add("Referer", "https://www.weibo.com")
|
.add("Referer", "https://www.weibo.com")
|
||||||
.add("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
|
.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
|
||||||
|
|
||||||
Cookie cookie = new DefaultCookie("SUB", "_2A25KJE5vDeRhGeRJ6lsR9SjJzDuIHXVpWM-nrDV8PUJbkNAbLVPlkW1NUmJm3GjYtRHBsHdMUKafkdTL_YheMEmu");
|
Cookie cookie = new DefaultCookie("SUB", "_2A25KJE5vDeRhGeRJ6lsR9SjJzDuIHXVpWM-nrDV8PUJbkNAbLVPlkW1NUmJm3GjYtRHBsHdMUKafkdTL_YheMEmu");
|
||||||
@@ -46,7 +48,7 @@ public class GenShortUrl extends PanBase {
|
|||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
String longUrl = shareLinkInfo.getShareUrl();
|
String longUrl = shareLinkInfo.getShareUrl();
|
||||||
|
|
||||||
String url = WRAPPER_URL + Base64.getEncoder().encodeToString(longUrl.getBytes());
|
String url = WRAPPER_URL + Base64Encoder.encode(longUrl.getBytes());
|
||||||
|
|
||||||
String payload = "mid=" + MID + "&content=" + URLEncoder.encode(url, StandardCharsets.UTF_8);
|
String payload = "mid=" + MID + "&content=" + URLEncoder.encode(url, StandardCharsets.UTF_8);
|
||||||
clientSession.cookieStore().put(cookie);
|
clientSession.cookieStore().put(cookie);
|
||||||
@@ -64,11 +66,12 @@ public class GenShortUrl extends PanBase {
|
|||||||
String shortUrl = extractShortUrl(comment);
|
String shortUrl = extractShortUrl(comment);
|
||||||
if (shortUrl != null) {
|
if (shortUrl != null) {
|
||||||
log.info("生成的短链:{}", shortUrl);
|
log.info("生成的短链:{}", shortUrl);
|
||||||
|
// 先完成 promise,返回短链
|
||||||
|
promise.complete(shortUrl);
|
||||||
|
// 异步清理评论(best-effort,不影响结果)
|
||||||
String commentId = extractCommentId(comment);
|
String commentId = extractCommentId(comment);
|
||||||
if (commentId != null) {
|
if (commentId != null) {
|
||||||
deleteComment(commentId);
|
deleteComment(commentId);
|
||||||
} else {
|
|
||||||
promise.fail("未能提取评论ID");
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
promise.fail("未能生成短链");
|
promise.fail("未能生成短链");
|
||||||
@@ -103,8 +106,7 @@ public class GenShortUrl extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String extractShortUrl(String comment) {
|
private String extractShortUrl(String comment) {
|
||||||
Pattern pattern = Pattern.compile("(https?)://t.cn/\\w+");
|
Matcher matcher = SHORT_URL_PATTERN.matcher(comment);
|
||||||
Matcher matcher = pattern.matcher(comment);
|
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
return matcher.group(0);
|
return matcher.group(0);
|
||||||
}
|
}
|
||||||
@@ -112,8 +114,7 @@ public class GenShortUrl extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String extractCommentId(String comment) {
|
private String extractCommentId(String comment) {
|
||||||
Pattern pattern = Pattern.compile("comment_id=\"(\\d+)\"");
|
Matcher matcher = COMMENT_ID_PATTERN.matcher(comment);
|
||||||
Matcher matcher = pattern.matcher(comment);
|
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
return matcher.group(1);
|
return matcher.group(1);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,4 +52,14 @@ public class IzSelectorTool implements IPanTool {
|
|||||||
public Future<String> parseById() {
|
public Future<String> parseById() {
|
||||||
return selectedTool.parseById();
|
return selectedTool.parseById();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ShareLinkInfo getShareLinkInfo() {
|
||||||
|
return selectedTool.getShareLinkInfo();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
IPanTool.closeQuietly(selectedTool);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,9 @@ package cn.qaiu.parser.impl;
|
|||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import cn.qaiu.parser.FolderPaging;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
|
import cn.qaiu.parser.TokenCache;
|
||||||
import cn.qaiu.util.AESUtils;
|
import cn.qaiu.util.AESUtils;
|
||||||
import cn.qaiu.util.AcwScV2Generator;
|
import cn.qaiu.util.AcwScV2Generator;
|
||||||
import cn.qaiu.util.CommonUtils;
|
import cn.qaiu.util.CommonUtils;
|
||||||
@@ -55,7 +57,10 @@ public class IzTool extends PanBase {
|
|||||||
|
|
||||||
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
||||||
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
||||||
"={folderId}&offset=1&limit=60";
|
"={folderId}&offset={offset}&limit={limit}";
|
||||||
|
|
||||||
|
/** share/list 每页条数;offset 是从 1 开始的页码。 */
|
||||||
|
static final int LIST_LIMIT = 60;
|
||||||
|
|
||||||
|
|
||||||
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
||||||
@@ -85,12 +90,31 @@ public class IzTool extends PanBase {
|
|||||||
}
|
}
|
||||||
public IzTool(ShareLinkInfo shareLinkInfo) {
|
public IzTool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
|
IzXffHeader.apply(header);
|
||||||
|
String accountId = "_default";
|
||||||
|
if (shareLinkInfo.getOtherParam().containsKey("auths")) {
|
||||||
|
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
||||||
|
if (auths.contains("_configId")) {
|
||||||
|
accountId = auths.get("_configId");
|
||||||
|
} else if (auths.contains("username")) {
|
||||||
|
accountId = auths.get("username");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.cacheKey = TokenCache.key("iz", accountId);
|
||||||
}
|
}
|
||||||
|
|
||||||
String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
|
String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
|
||||||
|
|
||||||
public static String token = null;
|
// 多账号隔离:用 TokenCache 代替 static 变量
|
||||||
public static boolean authFlag = true;
|
private final String cacheKey;
|
||||||
|
|
||||||
|
private String token() {
|
||||||
|
return TokenCache.getToken(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean authFlag() {
|
||||||
|
return TokenCache.getFlag(cacheKey, true);
|
||||||
|
}
|
||||||
|
|
||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
|
|
||||||
@@ -101,24 +125,23 @@ public class IzTool extends PanBase {
|
|||||||
// 检查并输出认证状态
|
// 检查并输出认证状态
|
||||||
if (shareLinkInfo.getOtherParam().containsKey("auths")) {
|
if (shareLinkInfo.getOtherParam().containsKey("auths")) {
|
||||||
boolean isTempAuth = shareLinkInfo.getOtherParam().containsKey("__TEMP_AUTH_ADDED");
|
boolean isTempAuth = shareLinkInfo.getOtherParam().containsKey("__TEMP_AUTH_ADDED");
|
||||||
log.info("文件解析检测到认证信息: isTempAuth={}, authFlag={}, token={}",
|
String token = token();
|
||||||
isTempAuth, authFlag, token != null ? "已登录(" + token.substring(0, Math.min(10, token.length())) + "...)" : "未登录");
|
log.info("文件解析检测到认证信息: isTempAuth={}, authFlag={}, token={}",
|
||||||
|
isTempAuth, authFlag(), token != null ? "已登录(" + token.substring(0, Math.min(8, token.length())) + "...)" : "未登录");
|
||||||
|
|
||||||
// 如果需要认证但还没有token,先执行登录
|
// 如果需要认证但还没有token,先执行登录
|
||||||
if ((isTempAuth || authFlag) && token == null) {
|
if ((isTempAuth || authFlag()) && token == null) {
|
||||||
log.info("文件解析需要登录,开始执行登录流程...");
|
log.info("文件解析需要登录,开始执行登录流程...");
|
||||||
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
||||||
return login(tsEncode, auths)
|
return login(tsEncode, auths)
|
||||||
.compose(v -> {
|
.recover(err -> {
|
||||||
log.info("文件解析预登录成功,继续解析流程");
|
// 预登录失败不终止解析,继续走免登录
|
||||||
return parseWithAuth(shareId, tsEncode);
|
log.warn("文件解析预登录失败: {},使用免登录模式", err.getMessage());
|
||||||
|
return Future.succeededFuture();
|
||||||
})
|
})
|
||||||
.onFailure(err -> {
|
.compose(v -> parseWithAuth(shareId, tsEncode));
|
||||||
log.warn("文件解析预登录失败: {},尝试使用免登录模式", err.getMessage());
|
|
||||||
// 登录失败,继续使用免登录模式
|
|
||||||
});
|
|
||||||
} else if (token != null) {
|
} else if (token != null) {
|
||||||
log.info("文件解析使用已有token: {}...", token.substring(0, Math.min(10, token.length())));
|
log.info("文件解析使用已有token: {}...", token.substring(0, Math.min(8, token.length())));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.debug("文件解析无认证信息,使用免登录模式");
|
log.debug("文件解析无认证信息,使用免登录模式");
|
||||||
@@ -231,8 +254,8 @@ public class IzTool extends PanBase {
|
|||||||
// 检查是否为临时认证(临时认证每次都尝试登录)
|
// 检查是否为临时认证(临时认证每次都尝试登录)
|
||||||
boolean isTempAuth = shareLinkInfo.getOtherParam().containsKey("__TEMP_AUTH_ADDED");
|
boolean isTempAuth = shareLinkInfo.getOtherParam().containsKey("__TEMP_AUTH_ADDED");
|
||||||
// 如果是临时认证,或者是后台配置且authFlag为true,则尝试使用认证
|
// 如果是临时认证,或者是后台配置且authFlag为true,则尝试使用认证
|
||||||
if (isTempAuth || authFlag) {
|
if (isTempAuth || authFlag()) {
|
||||||
log.debug("尝试使用认证信息解析, isTempAuth={}, authFlag={}", isTempAuth, authFlag);
|
log.debug("尝试使用认证信息解析, isTempAuth={}, authFlag={}", isTempAuth, authFlag());
|
||||||
HttpRequest<Buffer> httpRequest =
|
HttpRequest<Buffer> httpRequest =
|
||||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
||||||
.setTemplateParam("fidEncode", fidEncode)
|
.setTemplateParam("fidEncode", fidEncode)
|
||||||
@@ -241,18 +264,19 @@ public class IzTool extends PanBase {
|
|||||||
.setTemplateParam("auth", auth)
|
.setTemplateParam("auth", auth)
|
||||||
.setTemplateParam("dataKey", dataKey);
|
.setTemplateParam("dataKey", dataKey);
|
||||||
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
||||||
if (token == null) {
|
if (token() == null) {
|
||||||
// 执行登录
|
// 执行登录,失败则回退免登录
|
||||||
login(tsEncode2, auths).onFailure(failRes-> {
|
login(tsEncode2, auths).onFailure(failRes-> {
|
||||||
log.warn("登录失败: {}", failRes.getMessage());
|
log.warn("登录失败,回退免登录: {}", failRes.getMessage());
|
||||||
fail(failRes.getMessage());
|
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||||
}).onSuccess(r-> {
|
}).onSuccess(r-> {
|
||||||
httpRequest.setTemplateParam("appToken", header.get("appToken"))
|
httpRequest.setTemplateParam("appToken", token())
|
||||||
.putHeaders(header);
|
.putHeaders(header);
|
||||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// 验证token
|
// 验证token — 先从缓存恢复到 header
|
||||||
|
header.set("appToken", token());
|
||||||
webClientSession.postAbs(UriTemplate.of(TOKEN_VERIFY_URL))
|
webClientSession.postAbs(UriTemplate.of(TOKEN_VERIFY_URL))
|
||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode2)
|
.setTemplateParam("ts", tsEncode2)
|
||||||
@@ -260,15 +284,15 @@ public class IzTool extends PanBase {
|
|||||||
// log.info("res: {}",asJson(res));
|
// log.info("res: {}",asJson(res));
|
||||||
if (asJson(res).getInteger("code") != 200) {
|
if (asJson(res).getInteger("code") != 200) {
|
||||||
login(tsEncode2, auths).onFailure(failRes -> {
|
login(tsEncode2, auths).onFailure(failRes -> {
|
||||||
log.warn("重新登录失败: {}", failRes.getMessage());
|
log.warn("重新登录失败,回退免登录: {}", failRes.getMessage());
|
||||||
fail(failRes.getMessage());
|
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||||
}).onSuccess(r-> {
|
}).onSuccess(r-> {
|
||||||
httpRequest.setTemplateParam("appToken", header.get("appToken"))
|
httpRequest.setTemplateParam("appToken", token())
|
||||||
.putHeaders(header);
|
.putHeaders(header);
|
||||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
httpRequest.setTemplateParam("appToken", header.get("appToken"))
|
httpRequest.setTemplateParam("appToken", token())
|
||||||
.putHeaders(header);
|
.putHeaders(header);
|
||||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||||
}
|
}
|
||||||
@@ -277,29 +301,27 @@ public class IzTool extends PanBase {
|
|||||||
} else {
|
} else {
|
||||||
// authFlag 为 false,使用免登录解析
|
// authFlag 为 false,使用免登录解析
|
||||||
log.debug("authFlag=false,使用免登录解析");
|
log.debug("authFlag=false,使用免登录解析");
|
||||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||||
.putHeaders(header)
|
|
||||||
.setTemplateParam("fidEncode", fidEncode)
|
|
||||||
.setTemplateParam("uuid", uuid)
|
|
||||||
.setTemplateParam("ts", tsEncode2)
|
|
||||||
.setTemplateParam("auth", auth)
|
|
||||||
.setTemplateParam("dataKey", dataKey).send()
|
|
||||||
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 没有认证信息,使用免登录解析
|
// 没有认证信息,使用免登录解析
|
||||||
log.debug("无认证信息,使用免登录解析");
|
log.debug("无认证信息,使用免登录解析");
|
||||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||||
.putHeaders(header)
|
|
||||||
.setTemplateParam("fidEncode", fidEncode)
|
|
||||||
.setTemplateParam("uuid", uuid)
|
|
||||||
.setTemplateParam("ts", tsEncode2)
|
|
||||||
.setTemplateParam("auth", auth)
|
|
||||||
.setTemplateParam("dataKey", dataKey).send()
|
|
||||||
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void downloadAnonymous(String fidEncode, String tsEncode2, String auth, String dataKey) {
|
||||||
|
log.debug("使用免登录解析");
|
||||||
|
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
||||||
|
.putHeaders(header)
|
||||||
|
.setTemplateParam("fidEncode", fidEncode)
|
||||||
|
.setTemplateParam("uuid", uuid)
|
||||||
|
.setTemplateParam("ts", tsEncode2)
|
||||||
|
.setTemplateParam("auth", auth)
|
||||||
|
.setTemplateParam("dataKey", dataKey).send()
|
||||||
|
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||||
|
}
|
||||||
|
|
||||||
private Future<Void> login(String tsEncode2, MultiMap auths) {
|
private Future<Void> login(String tsEncode2, MultiMap auths) {
|
||||||
Promise<Void> promise1 = Promise.promise();
|
Promise<Void> promise1 = Promise.promise();
|
||||||
webClientSession.postAbs(UriTemplate.of(LOGIN_URL))
|
webClientSession.postAbs(UriTemplate.of(LOGIN_URL))
|
||||||
@@ -310,9 +332,13 @@ public class IzTool extends PanBase {
|
|||||||
.onSuccess(res2->{
|
.onSuccess(res2->{
|
||||||
JsonObject json = asJson(res2);
|
JsonObject json = asJson(res2);
|
||||||
if (json.getInteger("code") == 200) {
|
if (json.getInteger("code") == 200) {
|
||||||
token = json.getJsonObject("data").getString("appToken");
|
String loginToken = json.getJsonObject("data").getString("appToken");
|
||||||
header.set("appToken", token);
|
TokenCache.putToken(cacheKey, loginToken);
|
||||||
log.info("登录成功 token: {}", token);
|
TokenCache.queueCachedTokenPersist(cacheKey, loginToken, System.currentTimeMillis() + 24 * 60 * 60 * 1000L);
|
||||||
|
if (loginToken != null) {
|
||||||
|
header.set("appToken", loginToken);
|
||||||
|
}
|
||||||
|
log.info("登录成功 token: {}...", loginToken != null ? loginToken.substring(0, Math.min(8, loginToken.length())) : "null");
|
||||||
promise1.complete();
|
promise1.complete();
|
||||||
} else {
|
} else {
|
||||||
// 检查是否为临时认证
|
// 检查是否为临时认证
|
||||||
@@ -324,7 +350,7 @@ public class IzTool extends PanBase {
|
|||||||
} else {
|
} else {
|
||||||
// 后台配置的认证失败,设置authFlag并返回失败,让下次请求使用免登陆解析
|
// 后台配置的认证失败,设置authFlag并返回失败,让下次请求使用免登陆解析
|
||||||
log.warn("后台配置认证失败: {}, authFlag将设为false,请重新解析", json.getString("msg"));
|
log.warn("后台配置认证失败: {}, authFlag将设为false,请重新解析", json.getString("msg"));
|
||||||
authFlag = false;
|
TokenCache.putFlag(cacheKey, false);
|
||||||
promise1.fail("认证失败: " + json.getString("msg") + ", 请重新解析将使用免登陆模式");
|
promise1.fail("认证失败: " + json.getString("msg") + ", 请重新解析将使用免登陆模式");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -446,11 +472,70 @@ public class IzTool extends PanBase {
|
|||||||
|
|
||||||
private void down(HttpResponse<Buffer> res2) {
|
private void down(HttpResponse<Buffer> res2) {
|
||||||
MultiMap headers = res2.headers();
|
MultiMap headers = res2.headers();
|
||||||
if (!headers.contains("Location") || StringUtils.isBlank(headers.get("Location"))) {
|
String location = headers.get("Location");
|
||||||
fail("找不到下载链接可能服务器已被禁止或者配置的认证信息有误");
|
if (StringUtils.isBlank(location)) {
|
||||||
|
fail("{}", buildMissingLocationMessage(res2));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
promise.complete(headers.get("Location"));
|
promise.complete(location);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String buildMissingLocationMessage(HttpResponse<Buffer> response) {
|
||||||
|
StringBuilder message = new StringBuilder("未获取到下载重定向地址");
|
||||||
|
message.append(", HTTP ").append(response.statusCode());
|
||||||
|
|
||||||
|
String body = null;
|
||||||
|
try {
|
||||||
|
body = asText(response);
|
||||||
|
} catch (Exception e) {
|
||||||
|
body = "<响应体读取失败: " + e.getMessage() + ">";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(body)) {
|
||||||
|
try {
|
||||||
|
JsonObject json = new JsonObject(body);
|
||||||
|
String upstreamMsg = json.getString("msg");
|
||||||
|
Object code = json.getValue("code");
|
||||||
|
if (StringUtils.isNotBlank(upstreamMsg)) {
|
||||||
|
message.append(", 上游返回: ").append(upstreamMsg);
|
||||||
|
if (code != null) {
|
||||||
|
message.append(" (code=").append(code).append(")");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
message.append(", 响应体: ").append(previewBody(body));
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
message.append(", 响应体: ").append(previewBody(body));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
message.append(", 响应体为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
Object fileName = shareLinkInfo.getOtherParam().get("fileName");
|
||||||
|
Object fileSize = shareLinkInfo.getOtherParam().get("fileSizeFormat");
|
||||||
|
if (fileName != null) {
|
||||||
|
message.append(", 文件: ").append(fileName);
|
||||||
|
}
|
||||||
|
if (fileSize != null) {
|
||||||
|
message.append(", 大小: ").append(fileSize);
|
||||||
|
}
|
||||||
|
if (!hasConfiguredAuth()) {
|
||||||
|
message.append(", 当前为免登录解析,上游可能要求登录、会员或人工处理");
|
||||||
|
}
|
||||||
|
return message.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasConfiguredAuth() {
|
||||||
|
Object authObj = shareLinkInfo.getOtherParam().get("auths");
|
||||||
|
if (!(authObj instanceof MultiMap auths)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return StringUtils.isNotBlank(auths.get("username")) && StringUtils.isNotBlank(auths.get("password"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String previewBody(String body) {
|
||||||
|
int maxLength = 500;
|
||||||
|
return body.length() <= maxLength ? body : body.substring(0, maxLength) + "...";
|
||||||
}
|
}
|
||||||
|
|
||||||
// 目录解析
|
// 目录解析
|
||||||
@@ -463,7 +548,10 @@ public class IzTool extends PanBase {
|
|||||||
// 如果参数里的目录ID不为空,则直接解析目录
|
// 如果参数里的目录ID不为空,则直接解析目录
|
||||||
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
|
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
|
||||||
if (dirId != null && !dirId.isEmpty()) {
|
if (dirId != null && !dirId.isEmpty()) {
|
||||||
uuid = shareLinkInfo.getOtherParam().get("uuid").toString();
|
Object uuidObj = shareLinkInfo.getOtherParam().get("uuid");
|
||||||
|
if (uuidObj != null) {
|
||||||
|
uuid = uuidObj.toString();
|
||||||
|
}
|
||||||
parserDir(dirId, shareId, promise);
|
parserDir(dirId, shareId, promise);
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
@@ -485,7 +573,11 @@ public class IzTool extends PanBase {
|
|||||||
.setParserUrl(id)
|
.setParserUrl(id)
|
||||||
.setPanType(shareLinkInfo.getType());
|
.setPanType(shareLinkInfo.getType());
|
||||||
List<FileInfo> result = new ArrayList<>();
|
List<FileInfo> result = new ArrayList<>();
|
||||||
result.add(fileInfo);
|
int page = FolderPaging.pageOrFirst(shareLinkInfo);
|
||||||
|
if (page == 1) {
|
||||||
|
result.add(fileInfo);
|
||||||
|
}
|
||||||
|
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -502,6 +594,8 @@ public class IzTool extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
|
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
||||||
|
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
String resBody = asText(res);
|
String resBody = asText(res);
|
||||||
// 检查是否包含 cookie 验证
|
// 检查是否包含 cookie 验证
|
||||||
@@ -516,6 +610,8 @@ public class IzTool extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
|
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
||||||
|
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
||||||
.send().onSuccess(res2 -> {
|
.send().onSuccess(res2 -> {
|
||||||
processDirResponse(res2, shareId, promise);
|
processDirResponse(res2, shareId, promise);
|
||||||
}).onFailure(err -> {
|
}).onFailure(err -> {
|
||||||
@@ -607,6 +703,7 @@ public class IzTool extends PanBase {
|
|||||||
shareLinkInfo.getType(), param));
|
shareLinkInfo.getType(), param));
|
||||||
result.add(fileInfo);
|
result.add(fileInfo);
|
||||||
});
|
});
|
||||||
|
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
||||||
@@ -630,7 +727,6 @@ public class IzTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static void resetToken() {
|
public static void resetToken() {
|
||||||
token = null;
|
TokenCache.removeByDiskType("iz");
|
||||||
authFlag = true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ package cn.qaiu.parser.impl;
|
|||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import cn.qaiu.parser.FolderPaging;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.util.AESUtils;
|
import cn.qaiu.util.AESUtils;
|
||||||
import cn.qaiu.util.AcwScV2Generator;
|
import cn.qaiu.util.AcwScV2Generator;
|
||||||
@@ -54,7 +55,10 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
|
|
||||||
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
||||||
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
||||||
"={folderId}&offset=1&limit=60";
|
"={folderId}&offset={offset}&limit={limit}";
|
||||||
|
|
||||||
|
/** share/list 每页条数;offset 是从 1 开始的页码。 */
|
||||||
|
static final int LIST_LIMIT = 60;
|
||||||
|
|
||||||
|
|
||||||
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
||||||
@@ -84,12 +88,13 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
}
|
}
|
||||||
public IzToolWithAuth(ShareLinkInfo shareLinkInfo) {
|
public IzToolWithAuth(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
|
IzXffHeader.apply(header);
|
||||||
}
|
}
|
||||||
|
|
||||||
String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
|
String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
|
||||||
|
|
||||||
public static String token = null;
|
public static volatile String token = null;
|
||||||
public static boolean authFlag = true;
|
public static volatile boolean authFlag = true;
|
||||||
|
|
||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
|
|
||||||
@@ -213,10 +218,10 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
if (token == null) {
|
if (token == null) {
|
||||||
// 执行登录
|
// 执行登录
|
||||||
login(tsEncode2, auths).onFailure(failRes-> {
|
login(tsEncode2, auths).onFailure(failRes-> {
|
||||||
log.warn("登录失败: {}", failRes.getMessage());
|
log.warn("登录失败,回退免登录: {}", failRes.getMessage());
|
||||||
fail(failRes.getMessage());
|
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||||
}).onSuccess(r-> {
|
}).onSuccess(r-> {
|
||||||
httpRequest.setTemplateParam("appToken", header.get("appToken"))
|
httpRequest.setTemplateParam("appToken", token)
|
||||||
.putHeaders(header);
|
.putHeaders(header);
|
||||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||||
});
|
});
|
||||||
@@ -229,15 +234,15 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
// log.info("res: {}",asJson(res));
|
// log.info("res: {}",asJson(res));
|
||||||
if (asJson(res).getInteger("code") != 200) {
|
if (asJson(res).getInteger("code") != 200) {
|
||||||
login(tsEncode2, auths).onFailure(failRes -> {
|
login(tsEncode2, auths).onFailure(failRes -> {
|
||||||
log.warn("重新登录失败: {}", failRes.getMessage());
|
log.warn("重新登录失败,回退免登录: {}", failRes.getMessage());
|
||||||
fail(failRes.getMessage());
|
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||||
}).onSuccess(r-> {
|
}).onSuccess(r-> {
|
||||||
httpRequest.setTemplateParam("appToken", header.get("appToken"))
|
httpRequest.setTemplateParam("appToken", token)
|
||||||
.putHeaders(header);
|
.putHeaders(header);
|
||||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
httpRequest.setTemplateParam("appToken", header.get("appToken"))
|
httpRequest.setTemplateParam("appToken", token)
|
||||||
.putHeaders(header);
|
.putHeaders(header);
|
||||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||||
}
|
}
|
||||||
@@ -246,29 +251,27 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
} else {
|
} else {
|
||||||
// authFlag 为 false,使用免登录解析
|
// authFlag 为 false,使用免登录解析
|
||||||
log.debug("authFlag=false,使用免登录解析");
|
log.debug("authFlag=false,使用免登录解析");
|
||||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||||
.putHeaders(header)
|
|
||||||
.setTemplateParam("fidEncode", fidEncode)
|
|
||||||
.setTemplateParam("uuid", uuid)
|
|
||||||
.setTemplateParam("ts", tsEncode2)
|
|
||||||
.setTemplateParam("auth", auth)
|
|
||||||
.setTemplateParam("dataKey", dataKey).send()
|
|
||||||
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 没有认证信息,使用免登录解析
|
// 没有认证信息,使用免登录解析
|
||||||
log.debug("无认证信息,使用免登录解析");
|
log.debug("无认证信息,使用免登录解析");
|
||||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||||
.putHeaders(header)
|
|
||||||
.setTemplateParam("fidEncode", fidEncode)
|
|
||||||
.setTemplateParam("uuid", uuid)
|
|
||||||
.setTemplateParam("ts", tsEncode2)
|
|
||||||
.setTemplateParam("auth", auth)
|
|
||||||
.setTemplateParam("dataKey", dataKey).send()
|
|
||||||
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void downloadAnonymous(String fidEncode, String tsEncode2, String auth, String dataKey) {
|
||||||
|
log.debug("使用免登录解析");
|
||||||
|
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
||||||
|
.putHeaders(header)
|
||||||
|
.setTemplateParam("fidEncode", fidEncode)
|
||||||
|
.setTemplateParam("uuid", uuid)
|
||||||
|
.setTemplateParam("ts", tsEncode2)
|
||||||
|
.setTemplateParam("auth", auth)
|
||||||
|
.setTemplateParam("dataKey", dataKey).send()
|
||||||
|
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||||
|
}
|
||||||
|
|
||||||
private Future<Void> login(String tsEncode2, MultiMap auths) {
|
private Future<Void> login(String tsEncode2, MultiMap auths) {
|
||||||
Promise<Void> promise1 = Promise.promise();
|
Promise<Void> promise1 = Promise.promise();
|
||||||
webClientSession.postAbs(UriTemplate.of(LOGIN_URL))
|
webClientSession.postAbs(UriTemplate.of(LOGIN_URL))
|
||||||
@@ -280,8 +283,7 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
JsonObject json = asJson(res2);
|
JsonObject json = asJson(res2);
|
||||||
if (json.getInteger("code") == 200) {
|
if (json.getInteger("code") == 200) {
|
||||||
token = json.getJsonObject("data").getString("appToken");
|
token = json.getJsonObject("data").getString("appToken");
|
||||||
header.set("appToken", token);
|
log.info("登录成功 token: {}...", token != null ? token.substring(0, Math.min(8, token.length())) : "null");
|
||||||
log.info("登录成功 token: {}", token);
|
|
||||||
promise1.complete();
|
promise1.complete();
|
||||||
} else {
|
} else {
|
||||||
// 检查是否为临时认证
|
// 检查是否为临时认证
|
||||||
@@ -415,11 +417,70 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
|
|
||||||
private void down(HttpResponse<Buffer> res2) {
|
private void down(HttpResponse<Buffer> res2) {
|
||||||
MultiMap headers = res2.headers();
|
MultiMap headers = res2.headers();
|
||||||
if (!headers.contains("Location") || StringUtils.isBlank(headers.get("Location"))) {
|
String location = headers.get("Location");
|
||||||
fail("找不到下载链接可能服务器已被禁止或者配置的认证信息有误");
|
if (StringUtils.isBlank(location)) {
|
||||||
|
fail("{}", buildMissingLocationMessage(res2));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
promise.complete(headers.get("Location"));
|
promise.complete(location);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String buildMissingLocationMessage(HttpResponse<Buffer> response) {
|
||||||
|
StringBuilder message = new StringBuilder("未获取到下载重定向地址");
|
||||||
|
message.append(", HTTP ").append(response.statusCode());
|
||||||
|
|
||||||
|
String body = null;
|
||||||
|
try {
|
||||||
|
body = asText(response);
|
||||||
|
} catch (Exception e) {
|
||||||
|
body = "<响应体读取失败: " + e.getMessage() + ">";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StringUtils.isNotBlank(body)) {
|
||||||
|
try {
|
||||||
|
JsonObject json = new JsonObject(body);
|
||||||
|
String upstreamMsg = json.getString("msg");
|
||||||
|
Object code = json.getValue("code");
|
||||||
|
if (StringUtils.isNotBlank(upstreamMsg)) {
|
||||||
|
message.append(", 上游返回: ").append(upstreamMsg);
|
||||||
|
if (code != null) {
|
||||||
|
message.append(" (code=").append(code).append(")");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
message.append(", 响应体: ").append(previewBody(body));
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
message.append(", 响应体: ").append(previewBody(body));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
message.append(", 响应体为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
Object fileName = shareLinkInfo.getOtherParam().get("fileName");
|
||||||
|
Object fileSize = shareLinkInfo.getOtherParam().get("fileSizeFormat");
|
||||||
|
if (fileName != null) {
|
||||||
|
message.append(", 文件: ").append(fileName);
|
||||||
|
}
|
||||||
|
if (fileSize != null) {
|
||||||
|
message.append(", 大小: ").append(fileSize);
|
||||||
|
}
|
||||||
|
if (!hasConfiguredAuth()) {
|
||||||
|
message.append(", 当前为免登录解析,上游可能要求登录、会员或人工处理");
|
||||||
|
}
|
||||||
|
return message.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean hasConfiguredAuth() {
|
||||||
|
Object authObj = shareLinkInfo.getOtherParam().get("auths");
|
||||||
|
if (!(authObj instanceof MultiMap auths)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return StringUtils.isNotBlank(auths.get("username")) && StringUtils.isNotBlank(auths.get("password"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String previewBody(String body) {
|
||||||
|
int maxLength = 500;
|
||||||
|
return body.length() <= maxLength ? body : body.substring(0, maxLength) + "...";
|
||||||
}
|
}
|
||||||
|
|
||||||
// 目录解析
|
// 目录解析
|
||||||
@@ -432,7 +493,8 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
// 如果参数里的目录ID不为空,则直接解析目录
|
// 如果参数里的目录ID不为空,则直接解析目录
|
||||||
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
|
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
|
||||||
if (dirId != null && !dirId.isEmpty()) {
|
if (dirId != null && !dirId.isEmpty()) {
|
||||||
uuid = shareLinkInfo.getOtherParam().get("uuid").toString();
|
Object uuidObj = shareLinkInfo.getOtherParam().get("uuid");
|
||||||
|
uuid = uuidObj != null ? uuidObj.toString() : null;
|
||||||
parserDir(dirId, shareId, promise);
|
parserDir(dirId, shareId, promise);
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
@@ -454,7 +516,11 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
.setParserUrl(id)
|
.setParserUrl(id)
|
||||||
.setPanType(shareLinkInfo.getType());
|
.setPanType(shareLinkInfo.getType());
|
||||||
List<FileInfo> result = new ArrayList<>();
|
List<FileInfo> result = new ArrayList<>();
|
||||||
result.add(fileInfo);
|
int page = FolderPaging.pageOrFirst(shareLinkInfo);
|
||||||
|
if (page == 1) {
|
||||||
|
result.add(fileInfo);
|
||||||
|
}
|
||||||
|
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -480,7 +546,7 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
requestDirList(id, shareId, tsEncode, promise);
|
requestDirList(id, shareId, tsEncode, promise);
|
||||||
})
|
})
|
||||||
.onSuccess(r -> {
|
.onSuccess(r -> {
|
||||||
log.info("目录解析登录成功,token={}, 使用 VIP 模式", token != null ? token.substring(0, 10) + "..." : "null");
|
log.info("目录解析登录成功,token={}, 使用 VIP 模式", token != null ? token.substring(0, Math.min(8, token.length())) + "..." : "null");
|
||||||
requestDirList(id, shareId, tsEncode, promise);
|
requestDirList(id, shareId, tsEncode, promise);
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
@@ -507,6 +573,8 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
|
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
||||||
|
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
String resBody = asText(res);
|
String resBody = asText(res);
|
||||||
// 检查是否包含 cookie 验证
|
// 检查是否包含 cookie 验证
|
||||||
@@ -521,6 +589,8 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
|
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
||||||
|
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
||||||
.send().onSuccess(res2 -> {
|
.send().onSuccess(res2 -> {
|
||||||
processDirResponse(res2, shareId, promise);
|
processDirResponse(res2, shareId, promise);
|
||||||
}).onFailure(err -> {
|
}).onFailure(err -> {
|
||||||
@@ -613,6 +683,7 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
shareLinkInfo.getType(), param));
|
shareLinkInfo.getType(), param));
|
||||||
result.add(fileInfo);
|
result.add(fileInfo);
|
||||||
});
|
});
|
||||||
|
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
||||||
@@ -627,7 +698,7 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
|
|
||||||
// 如果有 token,使用 VIP 接口
|
// 如果有 token,使用 VIP 接口
|
||||||
if (StringUtils.isNotBlank(appToken)) {
|
if (StringUtils.isNotBlank(appToken)) {
|
||||||
log.debug("parseById 使用 VIP 接口, appToken={}", appToken.substring(0, Math.min(10, appToken.length())) + "...");
|
log.debug("parseById 使用 VIP 接口, appToken={}", appToken.substring(0, Math.min(8, appToken.length())) + "...");
|
||||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
||||||
.putHeaders(header)
|
.putHeaders(header)
|
||||||
.setTemplateParam("fidEncode", paramJson.getString("fidEncode"))
|
.setTemplateParam("fidEncode", paramJson.getString("fidEncode"))
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import io.vertx.core.MultiMap;
|
||||||
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 蓝奏云优享 X-Forwarded-For 配置。
|
||||||
|
* <p>
|
||||||
|
* 读取系统属性 {@code nfd.iz.xff},其次环境变量 {@code NFD_IZ_XFF}:
|
||||||
|
* <ul>
|
||||||
|
* <li>未设置 / 空 / {@code off}:不发送该头(默认)</li>
|
||||||
|
* <li>{@code random}:每次创建解析器时随机一个国内常见网段 IP</li>
|
||||||
|
* <li>其它值:原样作为头的值,例如 {@code 113.96.181.18}</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
public final class IzXffHeader {
|
||||||
|
|
||||||
|
public static final String PROP = "nfd.iz.xff";
|
||||||
|
public static final String ENV = "NFD_IZ_XFF";
|
||||||
|
private static final String HEADER = "X-Forwarded-For";
|
||||||
|
|
||||||
|
/** 国内运营商常见 /8 段首字节 */
|
||||||
|
private static final int[] CN_PREFIX = {36, 39, 42, 58, 59, 60, 61, 101, 106, 110, 111, 112, 113, 114,
|
||||||
|
115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 175, 180, 182, 183, 202, 210, 211, 218, 219, 220, 221, 222, 223};
|
||||||
|
|
||||||
|
private IzXffHeader() {
|
||||||
|
}
|
||||||
|
|
||||||
|
static String configured() {
|
||||||
|
String v = System.getProperty(PROP);
|
||||||
|
if (StringUtils.isBlank(v)) {
|
||||||
|
v = System.getenv(ENV);
|
||||||
|
}
|
||||||
|
return v == null ? "" : v.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 根据配置得到头的值,返回 null 表示不发送 */
|
||||||
|
static String resolve(String mode) {
|
||||||
|
if (StringUtils.isBlank(mode) || "off".equalsIgnoreCase(mode)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if ("random".equalsIgnoreCase(mode)) {
|
||||||
|
ThreadLocalRandom r = ThreadLocalRandom.current();
|
||||||
|
return CN_PREFIX[r.nextInt(CN_PREFIX.length)] + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + (1 + r.nextInt(254));
|
||||||
|
}
|
||||||
|
return mode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按当前配置写入或移除请求头 */
|
||||||
|
public static void apply(MultiMap headers) {
|
||||||
|
String value = resolve(configured());
|
||||||
|
if (value == null) {
|
||||||
|
headers.remove(HEADER);
|
||||||
|
} else {
|
||||||
|
headers.set(HEADER, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package cn.qaiu.parser.impl;
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.util.Base64Encoder;
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
@@ -13,8 +14,8 @@ import io.vertx.core.json.JsonObject;
|
|||||||
import java.io.UnsupportedEncodingException;
|
import java.io.UnsupportedEncodingException;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Random;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -24,6 +25,7 @@ public class LeTool extends PanBase {
|
|||||||
private static final String API_URL_PREFIX = "https://lecloud.lenovo.com/mshare/api/clouddiskapi/share/public/v1/";
|
private static final String API_URL_PREFIX = "https://lecloud.lenovo.com/mshare/api/clouddiskapi/share/public/v1/";
|
||||||
private static final String DEFAULT_FILE_TYPE = "file";
|
private static final String DEFAULT_FILE_TYPE = "file";
|
||||||
private static final int FILE_TYPE_DIRECTORY = 0; // 目录类型
|
private static final int FILE_TYPE_DIRECTORY = 0; // 目录类型
|
||||||
|
private static final Random RANDOM = new Random();
|
||||||
|
|
||||||
private static final MultiMap HEADERS;
|
private static final MultiMap HEADERS;
|
||||||
|
|
||||||
@@ -100,8 +102,8 @@ public class LeTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String fileId = fileInfoJson.getString("fileId");
|
String fileId = fileInfoJson.getString("fileId");
|
||||||
// 根据文件ID获取跳转链接
|
// 根据文件ID获取跳转链接(随机选择方式,失败自动fallback)
|
||||||
getDownURL(dataKey, fileId);
|
getDownURLWithFallback(dataKey, fileId);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
fail("{}: {}", resJson.getString("errcode"), resJson.getString("errmsg"));
|
fail("{}: {}", resJson.getString("errcode"), resJson.getString("errmsg"));
|
||||||
@@ -230,7 +232,7 @@ public class LeTool extends PanBase {
|
|||||||
"shareId", shareId,
|
"shareId", shareId,
|
||||||
"fileId", fileId
|
"fileId", fileId
|
||||||
);
|
);
|
||||||
String paramBase64 = Base64.getEncoder().encodeToString(paramJson.encode().getBytes());
|
String paramBase64 = Base64Encoder.encode(paramJson.encode().getBytes());
|
||||||
|
|
||||||
// 设置解析URL和预览URL
|
// 设置解析URL和预览URL
|
||||||
fileInfo.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
|
fileInfo.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
|
||||||
@@ -260,8 +262,8 @@ public class LeTool extends PanBase {
|
|||||||
String shareId = paramJson.getString("shareId");
|
String shareId = paramJson.getString("shareId");
|
||||||
String fileId = paramJson.getString("fileId");
|
String fileId = paramJson.getString("fileId");
|
||||||
|
|
||||||
// 调用获取下载链接
|
// 调用获取下载链接(随机选择方式,失败自动fallback)
|
||||||
getDownURLForById(shareId, fileId, parsePromise);
|
getDownURLWithFallbackForById(shareId, fileId, parsePromise);
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
parsePromise.fail("解析参数失败: " + e.getMessage());
|
parsePromise.fail("解析参数失败: " + e.getMessage());
|
||||||
@@ -304,14 +306,22 @@ public class LeTool extends PanBase {
|
|||||||
}).onFailure(err -> promise.fail(err));
|
}).onFailure(err -> promise.fail(err));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void getDownURL(String key, String fileId) {
|
/**
|
||||||
|
* 通过 packageDownloadWithFileIds 接口获取下载链接
|
||||||
|
* 需要两步:先获取 downloadUrl,再请求 302 跳转
|
||||||
|
*
|
||||||
|
* @param shareId 分享ID
|
||||||
|
* @param fileId 文件ID
|
||||||
|
* @param promise 完成时会写入此 promise
|
||||||
|
*/
|
||||||
|
private void getDownURL(String shareId, String fileId, Promise<String> promise) {
|
||||||
String uuid = UUID.randomUUID().toString();
|
String uuid = UUID.randomUUID().toString();
|
||||||
JsonArray fileIds = JsonArray.of(fileId);
|
JsonArray fileIds = JsonArray.of(fileId);
|
||||||
String apiUrl2 = API_URL_PREFIX + "packageDownloadWithFileIds";
|
String apiUrl = API_URL_PREFIX + "packageDownloadWithFileIds";
|
||||||
// {"fileIds":[123],"shareId":"xxx","browserId":"uuid"}
|
// {"fileIds":[123],"shareId":"xxx","browserId":"uuid"}
|
||||||
client.postAbs(apiUrl2)
|
client.postAbs(apiUrl)
|
||||||
.putHeaders(HEADERS)
|
.putHeaders(HEADERS)
|
||||||
.sendJsonObject(JsonObject.of("fileIds", fileIds, "shareId", key, "browserId", uuid))
|
.sendJsonObject(JsonObject.of("fileIds", fileIds, "shareId", shareId, "browserId", uuid))
|
||||||
.onSuccess(res -> {
|
.onSuccess(res -> {
|
||||||
JsonObject resJson = asJson(res);
|
JsonObject resJson = asJson(res);
|
||||||
if (resJson.containsKey("result")) {
|
if (resJson.containsKey("result")) {
|
||||||
@@ -320,20 +330,107 @@ public class LeTool extends PanBase {
|
|||||||
// 获取重定向链接跳转链接
|
// 获取重定向链接跳转链接
|
||||||
String downloadUrl = dataJson.getString("downloadUrl");
|
String downloadUrl = dataJson.getString("downloadUrl");
|
||||||
if (downloadUrl == null) {
|
if (downloadUrl == null) {
|
||||||
fail("Result JSON数据异常: downloadUrl不存在");
|
promise.fail("Result JSON数据异常: downloadUrl不存在");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 获取重定向链接跳转链接
|
// 获取重定向链接跳转链接
|
||||||
clientNoRedirects.getAbs(downloadUrl).send()
|
clientNoRedirects.getAbs(downloadUrl).send()
|
||||||
.onSuccess(res2 -> promise.complete(res2.headers().get("Location")))
|
.onSuccess(res2 -> promise.complete(res2.headers().get("Location")))
|
||||||
.onFailure(handleFail(downloadUrl));
|
.onFailure(err -> promise.fail(err));
|
||||||
} else {
|
} else {
|
||||||
fail("{}: {}", resJson.getString("errcode"), resJson.getString("errmsg"));
|
promise.fail(resJson.getString("errcode") + ": " + resJson.getString("errmsg"));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
fail("Result JSON数据异常: result字段不存在");
|
promise.fail("Result JSON数据异常: result字段不存在");
|
||||||
}
|
}
|
||||||
}).onFailure(handleFail(apiUrl2));
|
}).onFailure(err -> promise.fail(err));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过 directDownload 接口获取下载链接
|
||||||
|
* 相比 packageDownloadWithFileIds 少一次请求,直接返回302
|
||||||
|
*
|
||||||
|
* @param shareId 分享ID
|
||||||
|
* @param fileId 文件ID
|
||||||
|
* @param promise 完成时会写入此 promise
|
||||||
|
*/
|
||||||
|
private void getDownURLDirect(String shareId, String fileId, Promise<String> promise) {
|
||||||
|
String uuid = UUID.randomUUID().toString();
|
||||||
|
String apiUrl = API_URL_PREFIX + "directDownload"
|
||||||
|
+ "?shareId=" + shareId
|
||||||
|
+ "&fileId=" + fileId
|
||||||
|
+ "&browserId=" + uuid;
|
||||||
|
|
||||||
|
clientNoRedirects.getAbs(apiUrl)
|
||||||
|
.putHeaders(HEADERS)
|
||||||
|
.send()
|
||||||
|
.onSuccess(res -> {
|
||||||
|
String location = res.headers().get("Location");
|
||||||
|
if (location != null && !location.isEmpty()) {
|
||||||
|
promise.complete(location);
|
||||||
|
} else {
|
||||||
|
log.warn("directDownload 返回非302响应: shareId={}, fileId={}, statusCode={}", shareId, fileId, res.statusCode());
|
||||||
|
promise.fail("directDownload 未返回有效的 Location, statusCode=" + res.statusCode());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.onFailure(err -> {
|
||||||
|
log.warn("directDownload 请求失败: shareId={}, fileId={}, error={}", shareId, fileId, err.getMessage());
|
||||||
|
promise.fail(err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 随机选择下载方式并带 fallback(用于 parse)
|
||||||
|
* 先随机选择 directDownload 或 packageDownloadWithFileIds,失败则尝试另一个
|
||||||
|
*/
|
||||||
|
private void getDownURLWithFallback(String shareId, String fileId) {
|
||||||
|
boolean useDirect = RANDOM.nextBoolean();
|
||||||
|
log.info("乐云下载方式选择: shareId={}, fileId={}, method={}", shareId, fileId, useDirect ? "directDownload" : "packageDownloadWithFileIds");
|
||||||
|
|
||||||
|
Promise<String> fallbackPromise = Promise.promise();
|
||||||
|
fallbackPromise.future().onSuccess(url -> {
|
||||||
|
promise.complete(url);
|
||||||
|
}).onFailure(err -> {
|
||||||
|
log.warn("乐云第一种下载方式失败,尝试另一种: {}", err.getMessage());
|
||||||
|
if (useDirect) {
|
||||||
|
getDownURL(shareId, fileId, promise);
|
||||||
|
} else {
|
||||||
|
getDownURLDirect(shareId, fileId, promise);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (useDirect) {
|
||||||
|
getDownURLDirect(shareId, fileId, fallbackPromise);
|
||||||
|
} else {
|
||||||
|
getDownURL(shareId, fileId, fallbackPromise);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 随机选择下载方式并带 fallback(用于 parseById)
|
||||||
|
* 先随机选择 directDownload 或 packageDownloadWithFileIds,失败则尝试另一个
|
||||||
|
*/
|
||||||
|
private void getDownURLWithFallbackForById(String shareId, String fileId, Promise<String> promise) {
|
||||||
|
boolean useDirect = RANDOM.nextBoolean();
|
||||||
|
log.info("乐云下载方式选择(parseById): shareId={}, fileId={}, method={}", shareId, fileId, useDirect ? "directDownload" : "packageDownloadWithFileIds");
|
||||||
|
|
||||||
|
Promise<String> fallbackPromise = Promise.promise();
|
||||||
|
fallbackPromise.future().onSuccess(url -> {
|
||||||
|
promise.complete(url);
|
||||||
|
}).onFailure(err -> {
|
||||||
|
log.warn("乐云第一种下载方式失败,尝试另一种: {}", err.getMessage());
|
||||||
|
if (useDirect) {
|
||||||
|
getDownURLForById(shareId, fileId, promise);
|
||||||
|
} else {
|
||||||
|
getDownURLDirect(shareId, fileId, promise);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (useDirect) {
|
||||||
|
getDownURLDirect(shareId, fileId, fallbackPromise);
|
||||||
|
} else {
|
||||||
|
getDownURLForById(shareId, fileId, fallbackPromise);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.util.CommonUtils;
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 蓝奏目录「下一页」游标。
|
||||||
|
* <p>
|
||||||
|
* filemoreajax 的 t/k 由分享页下发,上游按这组令牌记录已翻到第几页:同一组令牌可以取
|
||||||
|
* 「已取过的最大页 + 1」以内的任意页;换一组新令牌直接跳到第 N 页会返回 zt=4「请刷新,重试」。
|
||||||
|
* 所以加载更多时把上一页用过的表单(不含密码和页码)交还给客户端,下次直接续翻。
|
||||||
|
* <p>
|
||||||
|
* 游标来自客户端,不可信:只用于表单字段,POST 主机仍由服务端按分享链接决定;
|
||||||
|
* 分享 key、页码、路径对不上一律当作没有游标,回退到从第 1 页顺序翻。
|
||||||
|
*/
|
||||||
|
final class LzFolderCursor {
|
||||||
|
|
||||||
|
private static final int VERSION = 1;
|
||||||
|
private static final Pattern PATH = Pattern.compile("/filemoreajax\\.php\\?file=(\\d+)");
|
||||||
|
private static final Pattern KEY = Pattern.compile("\\w{1,32}");
|
||||||
|
private static final int MAX_VALUE_LENGTH = 256;
|
||||||
|
private static final int MAX_FIELDS = 32;
|
||||||
|
|
||||||
|
final String path;
|
||||||
|
final Map<String, String> form;
|
||||||
|
final String webpage;
|
||||||
|
|
||||||
|
private LzFolderCursor(String path, Map<String, String> form, String webpage) {
|
||||||
|
this.path = path;
|
||||||
|
this.form = form;
|
||||||
|
this.webpage = webpage;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String encode(String shareKey, String path, Map<String, String> form, int nextPage, String webpage) {
|
||||||
|
JsonObject f = new JsonObject();
|
||||||
|
form.forEach((k, v) -> {
|
||||||
|
if (!"pwd".equals(k) && !"pg".equals(k)) {
|
||||||
|
f.put(k, v);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
JsonObject json = new JsonObject()
|
||||||
|
.put("v", VERSION)
|
||||||
|
.put("s", shareKey)
|
||||||
|
.put("p", path)
|
||||||
|
.put("n", nextPage)
|
||||||
|
.put("f", f);
|
||||||
|
if (webpage != null && !webpage.isBlank()) {
|
||||||
|
json.put("w", webpage);
|
||||||
|
}
|
||||||
|
return CommonUtils.urlBase64Encode(json.encode());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return 校验通过的游标;任何不匹配或格式问题都返回 null
|
||||||
|
*/
|
||||||
|
static LzFolderCursor decode(String raw, String shareKey, int page) {
|
||||||
|
if (raw == null || raw.isBlank() || raw.length() > 4096) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
JsonObject json = new JsonObject(CommonUtils.urlBase64Decode(raw));
|
||||||
|
if (json.getInteger("v", 0) != VERSION) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (shareKey == null || !shareKey.equals(json.getString("s"))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (json.getInteger("n", -1) != page) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String path = json.getString("p");
|
||||||
|
var m = path == null ? null : PATH.matcher(path);
|
||||||
|
if (m == null || !m.matches()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
JsonObject f = json.getJsonObject("f");
|
||||||
|
if (f == null || f.size() > MAX_FIELDS) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Map<String, String> form = new LinkedHashMap<>();
|
||||||
|
for (String key : f.fieldNames()) {
|
||||||
|
Object v = f.getValue(key);
|
||||||
|
if (!KEY.matcher(key).matches() || v == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String s = String.valueOf(v);
|
||||||
|
if (s.length() > MAX_VALUE_LENGTH || s.chars().anyMatch(c -> c < 0x20)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
form.put(key, s);
|
||||||
|
}
|
||||||
|
if (!m.group(1).equals(form.get("fid")) || !form.containsKey("t") || !form.containsKey("k")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String webpage = json.getString("w");
|
||||||
|
if (webpage != null && (webpage.length() > MAX_VALUE_LENGTH || !webpage.matches("[\\w\\-=.%]+"))) {
|
||||||
|
webpage = null;
|
||||||
|
}
|
||||||
|
return new LzFolderCursor(path, form, webpage);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 本次请求用的表单:游标字段 + 当前密码 + 目标页。 */
|
||||||
|
Map<String, String> formFor(String pwd, int page) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>(form);
|
||||||
|
out.put("pg", String.valueOf(page));
|
||||||
|
out.put("pwd", pwd == null ? "" : pwd);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -21,6 +21,8 @@ public class MkgsTool extends PanBase {
|
|||||||
|
|
||||||
public static final String API_URL = "https://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash={hash}";
|
public static final String API_URL = "https://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash={hash}";
|
||||||
|
|
||||||
|
private static final Pattern HASH_PATTERN = Pattern.compile("\"hash\"\\s*:\\s*\"([A-F0-9]+)\"");
|
||||||
|
|
||||||
private static final MultiMap headers = MultiMap.caseInsensitiveMultiMap();
|
private static final MultiMap headers = MultiMap.caseInsensitiveMultiMap();
|
||||||
static {
|
static {
|
||||||
// 设置 User-Agent
|
// 设置 User-Agent
|
||||||
@@ -78,18 +80,15 @@ public class MkgsTool extends PanBase {
|
|||||||
protected void downUrl(String locationURL) {
|
protected void downUrl(String locationURL) {
|
||||||
client.getAbs(locationURL).putHeaders(headers).send().onSuccess(res2->{
|
client.getAbs(locationURL).putHeaders(headers).send().onSuccess(res2->{
|
||||||
String body = res2.bodyAsString();
|
String body = res2.bodyAsString();
|
||||||
// 正则表达式匹配 hash 字段
|
Matcher matcher = HASH_PATTERN.matcher(body);
|
||||||
String regex = "\"hash\"\s*:\s*\"([A-F0-9]+)\"";
|
|
||||||
Pattern pattern = Pattern.compile(regex);
|
|
||||||
Matcher matcher = pattern.matcher(body);
|
|
||||||
|
|
||||||
// 查找并输出 hash 字段的值
|
// 查找并输出 hash 字段的值
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
String hashValue = matcher.group(1); // 获取第一个捕获组
|
String hashValue = matcher.group(1); // 获取第一个捕获组
|
||||||
System.out.println(hashValue);
|
log.debug("hash: {}", hashValue);
|
||||||
client.getAbs(UriTemplate.of(API_URL)).setTemplateParam("hash", hashValue).send().onSuccess(res3 -> {
|
client.getAbs(UriTemplate.of(API_URL)).setTemplateParam("hash", hashValue).send().onSuccess(res3 -> {
|
||||||
JsonObject jsonObject = asJson(res3);
|
JsonObject jsonObject = asJson(res3);
|
||||||
System.out.println(jsonObject.encodePrettily());
|
log.debug("API response: {}", jsonObject.encodePrettily());
|
||||||
if (jsonObject.containsKey("url")) {
|
if (jsonObject.containsKey("url")) {
|
||||||
promise.complete(jsonObject.getString("url"));
|
promise.complete(jsonObject.getString("url"));
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ public class MkwTool extends PanBase {
|
|||||||
|
|
||||||
public static final String API_URL = "https://www.kuwo.cn/api/v1/www/music/playUrl?mid={mid}&type=music&httpsStatus=1&reqId=&plat=web_www&from=";
|
public static final String API_URL = "https://www.kuwo.cn/api/v1/www/music/playUrl?mid={mid}&type=music&httpsStatus=1&reqId=&plat=web_www&from=";
|
||||||
|
|
||||||
|
private static final Pattern COOKIE_PATTERN = Pattern.compile("([A-Za-z0-9_]+)=([A-Za-z0-9]+)");
|
||||||
|
|
||||||
|
|
||||||
public MkwTool(ShareLinkInfo shareLinkInfo) {
|
public MkwTool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
@@ -29,39 +31,41 @@ public class MkwTool extends PanBase {
|
|||||||
clientSession.getAbs(shareUrl).send().onSuccess(result -> {
|
clientSession.getAbs(shareUrl).send().onSuccess(result -> {
|
||||||
String cookie = result.headers().get("set-cookie");
|
String cookie = result.headers().get("set-cookie");
|
||||||
|
|
||||||
if (!cookie.isEmpty()) {
|
if (cookie == null || cookie.isEmpty()) {
|
||||||
|
fail("未获取到 cookie,无法继续解析");
|
||||||
String regex = "([A-Za-z0-9_]+)=([A-Za-z0-9]+)";
|
return;
|
||||||
Pattern pattern = Pattern.compile(regex);
|
|
||||||
Matcher matcher = pattern.matcher(cookie);
|
|
||||||
if (matcher.find()) {
|
|
||||||
System.out.println(matcher.group(1));
|
|
||||||
System.out.println(matcher.group(2));
|
|
||||||
|
|
||||||
var key = matcher.group(1);
|
|
||||||
var token = matcher.group(2);
|
|
||||||
String sign = JsExecUtils.getKwSign(token, key);
|
|
||||||
System.out.println(sign);
|
|
||||||
clientSession.getAbs(UriTemplate.of(API_URL)).setTemplateParam("mid", shareLinkInfo.getShareKey())
|
|
||||||
.putHeader("Secret", sign).send().onSuccess(res -> {
|
|
||||||
JsonObject json = asJson(res);
|
|
||||||
log.debug(json.encodePrettily());
|
|
||||||
try {
|
|
||||||
if (json.getInteger("code") == 200) {
|
|
||||||
complete(json.getJsonObject("data").getString("url"));
|
|
||||||
} else {
|
|
||||||
fail("链接已失效/需要VIP");
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
fail("解析失败");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
});
|
Matcher matcher = COOKIE_PATTERN.matcher(cookie);
|
||||||
|
if (!matcher.find()) {
|
||||||
|
fail("cookie 格式不匹配");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug("cookie key: {}", matcher.group(1));
|
||||||
|
log.debug("cookie value: {}", matcher.group(2));
|
||||||
|
|
||||||
|
var key = matcher.group(1);
|
||||||
|
var token = matcher.group(2);
|
||||||
|
String sign = JsExecUtils.getKwSign(token, key);
|
||||||
|
log.debug("sign: {}", sign);
|
||||||
|
clientSession.getAbs(UriTemplate.of(API_URL)).setTemplateParam("mid", shareLinkInfo.getShareKey())
|
||||||
|
.putHeader("Secret", sign).send().onSuccess(res -> {
|
||||||
|
JsonObject json = asJson(res);
|
||||||
|
log.debug(json.encodePrettily());
|
||||||
|
try {
|
||||||
|
if (json.getInteger("code") == 200) {
|
||||||
|
complete(json.getJsonObject("data").getString("url"));
|
||||||
|
} else {
|
||||||
|
fail("链接已失效/需要VIP");
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("解析失败", e);
|
||||||
|
fail("解析失败");
|
||||||
|
}
|
||||||
|
}).onFailure(handleFail("获取下载链接失败"));
|
||||||
|
}).onFailure(handleFail("请求分享页面失败"));
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ public class P115Tool extends PanBase {
|
|||||||
private static final String SECOND_REQUEST_URL = API_URL_PREFIX + "share/skip_login_downurl";
|
private static final String SECOND_REQUEST_URL = API_URL_PREFIX + "share/skip_login_downurl";
|
||||||
|
|
||||||
|
|
||||||
|
private static final String DEFAULT_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
|
||||||
|
|
||||||
private static final MultiMap header;
|
private static final MultiMap header;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
@@ -49,9 +51,11 @@ public class P115Tool extends PanBase {
|
|||||||
|
|
||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
// 第一次请求 获取文件信息
|
// 第一次请求 获取文件信息
|
||||||
|
Object uaObj = shareLinkInfo.getOtherParam().get("UA");
|
||||||
|
String ua = uaObj != null ? uaObj.toString() : DEFAULT_UA;
|
||||||
client.getAbs(UriTemplate.of(FIRST_REQUEST_URL))
|
client.getAbs(UriTemplate.of(FIRST_REQUEST_URL))
|
||||||
.putHeaders(header)
|
.putHeaders(header)
|
||||||
.putHeader("User-Agent", shareLinkInfo.getOtherParam().get("UA").toString())
|
.putHeader("User-Agent", ua)
|
||||||
.setTemplateParam("dataKey", shareLinkInfo.getShareKey())
|
.setTemplateParam("dataKey", shareLinkInfo.getShareKey())
|
||||||
.setTemplateParam("dataPwd", shareLinkInfo.getSharePassword())
|
.setTemplateParam("dataPwd", shareLinkInfo.getSharePassword())
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
@@ -68,7 +72,7 @@ public class P115Tool extends PanBase {
|
|||||||
// share_code={dataKey}&receive_code={dataPwd}&file_id={file_id}
|
// share_code={dataKey}&receive_code={dataPwd}&file_id={file_id}
|
||||||
client.postAbs(SECOND_REQUEST_URL)
|
client.postAbs(SECOND_REQUEST_URL)
|
||||||
.putHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
|
.putHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
|
||||||
.putHeader("User-Agent", shareLinkInfo.getOtherParam().get("UA").toString())
|
.putHeader("User-Agent", ua)
|
||||||
.sendForm(MultiMap.caseInsensitiveMultiMap()
|
.sendForm(MultiMap.caseInsensitiveMultiMap()
|
||||||
.set("share_code", shareLinkInfo.getShareKey())
|
.set("share_code", shareLinkInfo.getShareKey())
|
||||||
.set("receive_code", shareLinkInfo.getSharePassword())
|
.set("receive_code", shareLinkInfo.getSharePassword())
|
||||||
|
|||||||
@@ -16,6 +16,9 @@ import java.util.regex.Pattern;
|
|||||||
* 下载链接需要Referer: https://link.yunpan.com/
|
* 下载链接需要Referer: https://link.yunpan.com/
|
||||||
*/
|
*/
|
||||||
public class P360Tool extends PanBase {
|
public class P360Tool extends PanBase {
|
||||||
|
|
||||||
|
private static final Pattern NID_PATTERN = Pattern.compile("\"nid\": \"([^\"]+)\"");
|
||||||
|
|
||||||
public P360Tool(ShareLinkInfo shareLinkInfo) {
|
public P360Tool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
}
|
}
|
||||||
@@ -43,9 +46,7 @@ public class P360Tool extends PanBase {
|
|||||||
clientSession.getAbs(url)
|
clientSession.getAbs(url)
|
||||||
.send()
|
.send()
|
||||||
.onSuccess(res -> {
|
.onSuccess(res -> {
|
||||||
// find "nid": "17402043311959599"
|
Matcher matcher = NID_PATTERN.matcher(res.bodyAsString());
|
||||||
Pattern compile = Pattern.compile("\"nid\": \"([^\"]+)\"");
|
|
||||||
Matcher matcher = compile.matcher(res.bodyAsString());
|
|
||||||
AtomicReference<String> nid = new AtomicReference<>();
|
AtomicReference<String> nid = new AtomicReference<>();
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
nid.set(matcher.group(1));
|
nid.set(matcher.group(1));
|
||||||
@@ -69,7 +70,7 @@ public class P360Tool extends PanBase {
|
|||||||
clientSession.getAbs(url)
|
clientSession.getAbs(url)
|
||||||
.send()
|
.send()
|
||||||
.onSuccess(res3 -> {
|
.onSuccess(res3 -> {
|
||||||
Matcher matcher1 = compile.matcher(res3.bodyAsString());
|
Matcher matcher1 = NID_PATTERN.matcher(res3.bodyAsString());
|
||||||
if (matcher1.find()) {
|
if (matcher1.find()) {
|
||||||
nid.set(matcher1.group(1));
|
nid.set(matcher1.group(1));
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -14,6 +14,25 @@ import java.util.regex.Pattern;
|
|||||||
*/
|
*/
|
||||||
public class PcxTool extends PanBase {
|
public class PcxTool extends PanBase {
|
||||||
|
|
||||||
|
private static final Pattern TITLE_PATTERN =
|
||||||
|
Pattern.compile("<title>([^<]+)</title>");
|
||||||
|
private static final Pattern FILENAME_INPUT_PATTERN =
|
||||||
|
Pattern.compile("<input id=\"filename\" type=\"hidden\" value=\"([^\"]+)\"");
|
||||||
|
private static final Pattern FILESIZE_PATTERN =
|
||||||
|
Pattern.compile("['\"]filesize['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
||||||
|
private static final Pattern SUFFIX_PATTERN =
|
||||||
|
Pattern.compile("['\"]suffix['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
||||||
|
private static final Pattern OBJECT_ID_PATTERN =
|
||||||
|
Pattern.compile("['\"]objectId['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
||||||
|
private static final Pattern CREATOR_PATTERN =
|
||||||
|
Pattern.compile("['\"]creator['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
||||||
|
private static final Pattern UPLOAD_DATE_PATTERN =
|
||||||
|
Pattern.compile("['\"]uploadDate['\"]\\s*:\\s*(\\d+)");
|
||||||
|
private static final Pattern THUMBNAIL_PATTERN =
|
||||||
|
Pattern.compile("['\"]thumbnail['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
||||||
|
private static final Pattern DOWNLOAD_PATTERN =
|
||||||
|
Pattern.compile("['\"]download['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
||||||
|
|
||||||
public PcxTool(ShareLinkInfo shareLinkInfo) {
|
public PcxTool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
}
|
}
|
||||||
@@ -44,9 +63,7 @@ public class PcxTool extends PanBase {
|
|||||||
* 从HTML中提取download链接
|
* 从HTML中提取download链接
|
||||||
*/
|
*/
|
||||||
private String extractDownloadUrl(String html) {
|
private String extractDownloadUrl(String html) {
|
||||||
// 匹配 'download': 'https://xxx' 或 "download": "https://xxx"
|
Matcher matcher = DOWNLOAD_PATTERN.matcher(html);
|
||||||
Pattern pattern = Pattern.compile("['\"]download['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
|
||||||
Matcher matcher = pattern.matcher(html);
|
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
return matcher.group(1);
|
return matcher.group(1);
|
||||||
}
|
}
|
||||||
@@ -61,13 +78,13 @@ public class PcxTool extends PanBase {
|
|||||||
FileInfo fileInfo = new FileInfo();
|
FileInfo fileInfo = new FileInfo();
|
||||||
|
|
||||||
// 提取文件名:从<title>标签或文件名input
|
// 提取文件名:从<title>标签或文件名input
|
||||||
String fileName = extractByRegex(html, "<title>([^<]+)</title>");
|
String fileName = extractByRegex(html, TITLE_PATTERN);
|
||||||
if (fileName == null) {
|
if (fileName == null) {
|
||||||
fileName = extractByRegex(html, "<input id=\"filename\" type=\"hidden\" value=\"([^\"]+)\"");
|
fileName = extractByRegex(html, FILENAME_INPUT_PATTERN);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 提取文件大小:'filesize': 'xxx' 或 "filesize": "xxx"
|
// 提取文件大小:'filesize': 'xxx' 或 "filesize": "xxx"
|
||||||
String fileSizeStr = extractByRegex(html, "['\"]filesize['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
String fileSizeStr = extractByRegex(html, FILESIZE_PATTERN);
|
||||||
Long fileSize = null;
|
Long fileSize = null;
|
||||||
if (fileSizeStr != null) {
|
if (fileSizeStr != null) {
|
||||||
try {
|
try {
|
||||||
@@ -76,19 +93,19 @@ public class PcxTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 提取文件类型/后缀:'suffix': 'xxx' 或 "suffix": "xxx"
|
// 提取文件类型/后缀:'suffix': 'xxx' 或 "suffix": "xxx"
|
||||||
String suffix = extractByRegex(html, "['\"]suffix['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
String suffix = extractByRegex(html, SUFFIX_PATTERN);
|
||||||
|
|
||||||
// 提取objectId(文件ID):'objectId': 'xxx' 或 "objectId": "xxx"
|
// 提取objectId(文件ID):'objectId': 'xxx' 或 "objectId": "xxx"
|
||||||
String objectId = extractByRegex(html, "['\"]objectId['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
String objectId = extractByRegex(html, OBJECT_ID_PATTERN);
|
||||||
|
|
||||||
// 提取创建者:'creator': 'xxx' 或 "creator": "xxx"
|
// 提取创建者:'creator': 'xxx' 或 "creator": "xxx"
|
||||||
String creator = extractByRegex(html, "['\"]creator['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
String creator = extractByRegex(html, CREATOR_PATTERN);
|
||||||
|
|
||||||
// 提取上传时间:'uploadDate': timestamp
|
// 提取上传时间:'uploadDate': timestamp
|
||||||
String uploadDate = extractByRegex(html, "['\"]uploadDate['\"]\\s*:\\s*(\\d+)");
|
String uploadDate = extractByRegex(html, UPLOAD_DATE_PATTERN);
|
||||||
|
|
||||||
// 提取缩略图:'thumbnail': 'xxx' 或 "thumbnail": "xxx"
|
// 提取缩略图:'thumbnail': 'xxx' 或 "thumbnail": "xxx"
|
||||||
String thumbnail = extractByRegex(html, "['\"]thumbnail['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
|
String thumbnail = extractByRegex(html, THUMBNAIL_PATTERN);
|
||||||
|
|
||||||
// 设置文件信息
|
// 设置文件信息
|
||||||
if (fileName != null) {
|
if (fileName != null) {
|
||||||
@@ -141,8 +158,7 @@ public class PcxTool extends PanBase {
|
|||||||
/**
|
/**
|
||||||
* 使用正则表达式提取内容
|
* 使用正则表达式提取内容
|
||||||
*/
|
*/
|
||||||
private String extractByRegex(String text, String regex) {
|
private String extractByRegex(String text, Pattern pattern) {
|
||||||
Pattern pattern = Pattern.compile(regex);
|
|
||||||
Matcher matcher = pattern.matcher(text);
|
Matcher matcher = pattern.matcher(text);
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
return matcher.group(1);
|
return matcher.group(1);
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ public class PdbTool extends PanBase implements IPanTool {
|
|||||||
private static final String API_URL =
|
private static final String API_URL =
|
||||||
"https://www.dropbox.com/sharing/fetch_user_content_link";
|
"https://www.dropbox.com/sharing/fetch_user_content_link";
|
||||||
static final String COOKIE_KEY = "__Host-js_csrf=";
|
static final String COOKIE_KEY = "__Host-js_csrf=";
|
||||||
|
private static final Pattern CSRF_TOKEN_PATTERN = Pattern.compile(COOKIE_KEY + "([\\w-]+);");
|
||||||
|
|
||||||
public PdbTool(ShareLinkInfo shareLinkInfo) {
|
public PdbTool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
@@ -47,7 +48,7 @@ public class PdbTool extends PanBase implements IPanTool {
|
|||||||
fail("cookie未找到");
|
fail("cookie未找到");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Matcher matcher = Pattern.compile(COOKIE_KEY + "([\\w-]+);").matcher(collect.get(0));
|
Matcher matcher = CSRF_TOKEN_PATTERN.matcher(collect.get(0));
|
||||||
String _t;
|
String _t;
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
_t = matcher.group(1);
|
_t = matcher.group(1);
|
||||||
@@ -85,7 +86,7 @@ public class PdbTool extends PanBase implements IPanTool {
|
|||||||
})
|
})
|
||||||
.onFailure(handleFail());
|
.onFailure(handleFail());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
log.error("URL编码异常", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -23,6 +23,16 @@ import java.util.regex.Pattern;
|
|||||||
*/
|
*/
|
||||||
public class PodTool extends PanBase {
|
public class PodTool extends PanBase {
|
||||||
|
|
||||||
|
private static final int MAX_RESPONSE_BODY_BYTES = 8 * 1024 * 1024;
|
||||||
|
private static final java.time.Duration REQUEST_TIMEOUT = java.time.Duration.ofSeconds(30);
|
||||||
|
|
||||||
|
// 静态共享的 JDK HttpClient 实例,避免每次调用创建新实例
|
||||||
|
private static final HttpClient SHARED_HTTP_CLIENT = HttpClient.newBuilder()
|
||||||
|
.connectTimeout(java.time.Duration.ofSeconds(10))
|
||||||
|
.build();
|
||||||
|
private static volatile WorkerExecutor SHARED_WORKER_EXECUTOR;
|
||||||
|
private static volatile boolean workerExecutorShutdown = false;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* https://1drv.ms/w/s!Alg0feQmCv2rnRFd60DQOmMa-Oh_?e=buaRtp --302->
|
* https://1drv.ms/w/s!Alg0feQmCv2rnRFd60DQOmMa-Oh_?e=buaRtp --302->
|
||||||
* https://api.onedrive.com/v1.0/drives/abfd0a26e47d3458/items/ABFD0A26E47D3458!3729?authkey=!AF3rQNA6Yxr46H8
|
* https://api.onedrive.com/v1.0/drives/abfd0a26e47d3458/items/ABFD0A26E47D3458!3729?authkey=!AF3rQNA6Yxr46H8
|
||||||
@@ -45,6 +55,13 @@ public class PodTool extends PanBase {
|
|||||||
private static final Pattern redirectUrlRegex =
|
private static final Pattern redirectUrlRegex =
|
||||||
Pattern.compile("resid=(?<cid1>[^!]+)!(?<cid2>[^&]+).+&redeem=(?<redeem>.+).*");
|
Pattern.compile("resid=(?<cid1>[^!]+)!(?<cid2>[^&]+).+&redeem=(?<redeem>.+).*");
|
||||||
|
|
||||||
|
private static final Pattern DOWNLOAD_URL_IN_RESPONSE_PATTERN =
|
||||||
|
Pattern.compile("\"downloadUrl\":\"(?<url>https?://[^\\s\"]+)");
|
||||||
|
private static final Pattern ACTION_URL_PATTERN =
|
||||||
|
Pattern.compile("'action'.+(?<url>https://.+)'\\)");
|
||||||
|
private static final Pattern TOKEN_PATTERN =
|
||||||
|
Pattern.compile("inputElem\\.value\\s*=\\s*'([^']+)'");
|
||||||
|
|
||||||
public PodTool(ShareLinkInfo shareLinkInfo) {
|
public PodTool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
}
|
}
|
||||||
@@ -97,7 +114,7 @@ public class PodTool extends PanBase {
|
|||||||
|
|
||||||
sendHttpRequest(url, token).onSuccess(body -> {
|
sendHttpRequest(url, token).onSuccess(body -> {
|
||||||
Matcher matcher1 =
|
Matcher matcher1 =
|
||||||
Pattern.compile("\"downloadUrl\":\"(?<url>https?://[^\s\"]+)").matcher(body);
|
DOWNLOAD_URL_IN_RESPONSE_PATTERN.matcher(body);
|
||||||
if (matcher1.find()) {
|
if (matcher1.find()) {
|
||||||
// 响应体是 JSON 文本,URL 中的 '&' 被转义为 \u0026,需要反转义
|
// 响应体是 JSON 文本,URL 中的 '&' 被转义为 \u0026,需要反转义
|
||||||
complete(unescapeJsonUnicode(matcher1.group("url")));
|
complete(unescapeJsonUnicode(matcher1.group("url")));
|
||||||
@@ -121,15 +138,11 @@ public class PodTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String matcherUrl(String html) {
|
private String matcherUrl(String html) {
|
||||||
|
Matcher urlMatcher = ACTION_URL_PATTERN.matcher(html);
|
||||||
// 正则表达式来匹配 URL
|
|
||||||
String urlRegex = "'action'.+(?<url>https://.+)'\\)";
|
|
||||||
Pattern urlPattern = Pattern.compile(urlRegex);
|
|
||||||
Matcher urlMatcher = urlPattern.matcher(html);
|
|
||||||
|
|
||||||
if (urlMatcher.find()) {
|
if (urlMatcher.find()) {
|
||||||
String url = urlMatcher.group("url");
|
String url = urlMatcher.group("url");
|
||||||
System.out.println("URL: " + url);
|
log.debug("URL: {}", url);
|
||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
throw new RuntimeException("URL匹配失败");
|
throw new RuntimeException("URL匹配失败");
|
||||||
@@ -165,14 +178,11 @@ public class PodTool extends PanBase {
|
|||||||
|
|
||||||
|
|
||||||
private String matcherToken(String html) {
|
private String matcherToken(String html) {
|
||||||
// 正则表达式来匹配 inputElem.value 中的 Token
|
Matcher tokenMatcher = TOKEN_PATTERN.matcher(html);
|
||||||
String tokenRegex = "inputElem\\.value\\s*=\\s*'([^']+)'";
|
|
||||||
Pattern tokenPattern = Pattern.compile(tokenRegex);
|
|
||||||
Matcher tokenMatcher = tokenPattern.matcher(html);
|
|
||||||
|
|
||||||
if (tokenMatcher.find()) {
|
if (tokenMatcher.find()) {
|
||||||
String token = tokenMatcher.group(1);
|
String token = tokenMatcher.group(1);
|
||||||
System.out.println("Token: " + token);
|
log.debug("Token: {}***", token.length() > 4 ? token.substring(0, 4) : "***");
|
||||||
return token;
|
return token;
|
||||||
}
|
}
|
||||||
throw new RuntimeException("token匹配失败");
|
throw new RuntimeException("token匹配失败");
|
||||||
@@ -180,11 +190,8 @@ public class PodTool extends PanBase {
|
|||||||
|
|
||||||
public Future<String> sendHttpRequest2(String token, String redeem) {
|
public Future<String> sendHttpRequest2(String token, String redeem) {
|
||||||
Promise<String> promise = Promise.promise();
|
Promise<String> promise = Promise.promise();
|
||||||
// 构造 HttpClient
|
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
|
||||||
|
|
||||||
// 构造请求的 URI 和头部信息
|
// 构造请求的 URI 和头部信息
|
||||||
// https://onedrive.live.com/redir?cid=abfd0a26e47d3458&resid=ABFD0A26E47D3458!4465&ithint=file%2cxlsx&e=Ao2uSU&migratedtospo=true&redeem=aHR0cHM6Ly8xZHJ2Lm1zL3gvYy9hYmZkMGEyNmU0N2QzNDU4L0VWZzBmZVFtQ3YwZ2dLdHhFUUFBQUFBQlRQRWVDMTZfZk1EYk5FTjhEdTRta1E_ZT1BbzJ1U1U
|
|
||||||
String url = ("https://my.microsoftpersonalcontent.com/_api/v2.0/shares/u!%s/driveItem?$select=content" +
|
String url = ("https://my.microsoftpersonalcontent.com/_api/v2.0/shares/u!%s/driveItem?$select=content" +
|
||||||
".downloadUrl").formatted(redeem);
|
".downloadUrl").formatted(redeem);
|
||||||
String authorizationHeader = "Badger " + token;
|
String authorizationHeader = "Badger " + token;
|
||||||
@@ -192,15 +199,20 @@ public class PodTool extends PanBase {
|
|||||||
// 构建请求
|
// 构建请求
|
||||||
HttpRequest request = HttpRequest.newBuilder()
|
HttpRequest request = HttpRequest.newBuilder()
|
||||||
.uri(URI.create(url))
|
.uri(URI.create(url))
|
||||||
|
.timeout(REQUEST_TIMEOUT)
|
||||||
.header("Authorization", authorizationHeader)
|
.header("Authorization", authorizationHeader)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
// 发送请求并处理响应
|
// 发送请求并处理响应(使用共享的 HttpClient)
|
||||||
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
|
SHARED_HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofByteArray())
|
||||||
.thenApply(response -> {
|
.thenApply(response -> {
|
||||||
System.out.println("Response Status Code: " + response.statusCode());
|
log.debug("Response Status Code: {}", response.statusCode());
|
||||||
System.out.println("Response Body: " + response.body());
|
promise.complete(toLimitedString(response.body()));
|
||||||
promise.complete(response.body());
|
return null;
|
||||||
|
})
|
||||||
|
.exceptionally(e -> {
|
||||||
|
log.error("sendHttpRequest2 请求失败: {}", e.getMessage());
|
||||||
|
promise.fail(e);
|
||||||
return null;
|
return null;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -208,18 +220,13 @@ public class PodTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Future<String> sendHttpRequest(String url, String token) {
|
public Future<String> sendHttpRequest(String url, String token) {
|
||||||
// 创建一个 WorkerExecutor 用于异步执行阻塞的 HTTP 请求
|
|
||||||
WorkerExecutor executor = WebClientVertxInit.get().createSharedWorkerExecutor("http-client-worker");
|
|
||||||
|
|
||||||
Promise<String> promise = Promise.promise();
|
Promise<String> promise = Promise.promise();
|
||||||
executor.executeBlocking(() -> {
|
getWorkerExecutor().executeBlocking(() -> {
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
|
||||||
HttpRequest request = null;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 构造请求
|
// 构造请求
|
||||||
request = HttpRequest.newBuilder()
|
HttpRequest request = HttpRequest.newBuilder()
|
||||||
.uri(new URI(url))
|
.uri(new URI(url))
|
||||||
|
.timeout(REQUEST_TIMEOUT)
|
||||||
.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9," +
|
.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9," +
|
||||||
"image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;" +
|
"image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;" +
|
||||||
"v=b3;q=0.7")
|
"v=b3;q=0.7")
|
||||||
@@ -244,17 +251,49 @@ public class PodTool extends PanBase {
|
|||||||
.POST(HttpRequest.BodyPublishers.ofString("badger_token=" + token))
|
.POST(HttpRequest.BodyPublishers.ofString("badger_token=" + token))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
// 发起请求并获取响应
|
// 发起请求并获取响应(使用共享的 HttpClient)
|
||||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
HttpResponse<byte[]> response = SHARED_HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofByteArray());
|
||||||
|
|
||||||
// 返回响应体
|
// 返回响应体
|
||||||
promise.complete(response.body());
|
promise.complete(toLimitedString(response.body()));
|
||||||
return null;
|
return null;
|
||||||
} catch (URISyntaxException | IOException | InterruptedException e) {
|
} catch (URISyntaxException | IOException | InterruptedException e) {
|
||||||
|
if (e instanceof InterruptedException) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
}
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
});
|
}).onFailure(promise::fail);
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
private static String toLimitedString(byte[] body) {
|
||||||
|
if (body.length > MAX_RESPONSE_BODY_BYTES) {
|
||||||
|
throw new IllegalArgumentException("OneDrive响应体过大: " + body.length + " bytes");
|
||||||
|
}
|
||||||
|
return new String(body, java.nio.charset.StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static WorkerExecutor getWorkerExecutor() {
|
||||||
|
synchronized (PodTool.class) {
|
||||||
|
if (workerExecutorShutdown) {
|
||||||
|
throw new IllegalStateException("OneDrive WorkerExecutor 已关闭");
|
||||||
|
}
|
||||||
|
if (SHARED_WORKER_EXECUTOR == null) {
|
||||||
|
SHARED_WORKER_EXECUTOR = WebClientVertxInit.get().createSharedWorkerExecutor("http-client-worker", 8);
|
||||||
|
}
|
||||||
|
return SHARED_WORKER_EXECUTOR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void shutdownWorkerExecutor() {
|
||||||
|
synchronized (PodTool.class) {
|
||||||
|
workerExecutorShutdown = true;
|
||||||
|
if (SHARED_WORKER_EXECUTOR != null) {
|
||||||
|
SHARED_WORKER_EXECUTOR.close();
|
||||||
|
SHARED_WORKER_EXECUTOR = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
package cn.qaiu.parser.impl;
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
import cn.qaiu.WebClientVertxInit;
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
@@ -11,7 +10,6 @@ import io.vertx.core.MultiMap;
|
|||||||
import io.vertx.core.Promise;
|
import io.vertx.core.Promise;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import io.vertx.core.json.pointer.JsonPointer;
|
import io.vertx.core.json.pointer.JsonPointer;
|
||||||
import io.vertx.ext.web.client.WebClient;
|
|
||||||
import io.vertx.uritemplate.UriTemplate;
|
import io.vertx.uritemplate.UriTemplate;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -53,9 +51,8 @@ public class PvyyTool extends PanBase {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
// 请求downcode
|
// 请求downcode - 使用父类的共享 WebClient 而非创建新实例
|
||||||
WebClient.create(WebClientVertxInit.get())
|
client.getAbs(api + shareLinkInfo.getShareKey())
|
||||||
.getAbs(api + shareLinkInfo.getShareKey())
|
|
||||||
.send()
|
.send()
|
||||||
.onSuccess(res -> {
|
.onSuccess(res -> {
|
||||||
if (res.statusCode() == 200) {
|
if (res.statusCode() == 200) {
|
||||||
|
|||||||
@@ -74,9 +74,9 @@ public class QQTool extends PanBase {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 调试匹配的情况
|
// 调试匹配的情况
|
||||||
System.out.println("文件名称: " + filename);
|
log.debug("文件名称: {}", filename);
|
||||||
System.out.println("文件大小: " + filesize);
|
log.debug("文件大小: {}", filesize);
|
||||||
System.out.println("文件直链: " + fileurl);
|
log.debug("文件直链: {}", fileurl);
|
||||||
|
|
||||||
// 提交
|
// 提交
|
||||||
promise.complete(fileurl.replace("\\x26", "&"));
|
promise.complete(fileurl.replace("\\x26", "&"));
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ package cn.qaiu.parser.impl;
|
|||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
|
import cn.qaiu.util.CommonUtils;
|
||||||
import cn.qaiu.util.HeaderUtils;
|
import cn.qaiu.util.HeaderUtils;
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
import io.vertx.core.MultiMap;
|
import io.vertx.core.MultiMap;
|
||||||
|
import io.vertx.core.Promise;
|
||||||
import io.vertx.core.json.JsonArray;
|
import io.vertx.core.json.JsonArray;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -13,27 +15,33 @@ import org.slf4j.LoggerFactory;
|
|||||||
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* QQ闪传 <br>
|
* QQ闪传 <br>
|
||||||
* 只能客户端上传 支持Android QQ 9.2.5, MACOS QQ 6.9.78,可生成分享链接,通过浏览器下载,支持超大文件,有效期默认7天(暂时没找到续期方法)。<br>
|
* 支持多文件、多级目录解析。通过 GetFileList API 获取文件列表,BatchDownload API 获取下载直链。<br>
|
||||||
|
* 有效期默认7天。
|
||||||
*/
|
*/
|
||||||
public class QQscTool extends PanBase {
|
public class QQscTool extends PanBase {
|
||||||
|
|
||||||
Logger LOG = LoggerFactory.getLogger(QQscTool.class);
|
Logger LOG = LoggerFactory.getLogger(QQscTool.class);
|
||||||
|
|
||||||
private static final String API_URL = "https://qfile.qq.com/http2rpc/gotrpc/noauth/trpc.qqntv2.richmedia.InnerProxy/BatchDownload";
|
private static final String BATCH_DOWNLOAD_API =
|
||||||
|
"https://qfile.qq.com/http2rpc/gotrpc/noauth/trpc.qqntv2.richmedia.InnerProxy/BatchDownload";
|
||||||
|
|
||||||
private static final MultiMap HEADERS = HeaderUtils.parseHeaders("""
|
private static final String GET_FILE_LIST_API =
|
||||||
|
"https://qfile.qq.com/http2rpc/gotrpc/noauth/trpc.file.FileFlashTrans/GetFileList";
|
||||||
|
|
||||||
|
private static final MultiMap BATCH_DOWNLOAD_HEADERS = HeaderUtils.parseHeaders("""
|
||||||
Accept-Encoding: gzip, deflate
|
Accept-Encoding: gzip, deflate
|
||||||
Accept-Language: zh-CN,zh;q=0.9
|
Accept-Language: zh-CN,zh;q=0.9
|
||||||
Connection: keep-alive
|
Connection: keep-alive
|
||||||
Cookie: uin=9000002; p_uin=9000002
|
Cookie: uin=9000002; p_uin=9000002
|
||||||
DNT: 1
|
DNT: 1
|
||||||
Origin: https://qfile.qq.com
|
Origin: https://qfile.qq.com
|
||||||
Referer: https://qfile.qq.com/q/Xolxtv5b4O
|
|
||||||
Sec-Fetch-Dest: empty
|
Sec-Fetch-Dest: empty
|
||||||
Sec-Fetch-Mode: cors
|
Sec-Fetch-Mode: cors
|
||||||
Sec-Fetch-Site: same-origin
|
Sec-Fetch-Site: same-origin
|
||||||
@@ -46,86 +54,262 @@ public class QQscTool extends PanBase {
|
|||||||
x-oidb: {"uint32_command":"0x9248", "uint32_service_type":"4"}
|
x-oidb: {"uint32_command":"0x9248", "uint32_service_type":"4"}
|
||||||
""");
|
""");
|
||||||
|
|
||||||
|
private static final MultiMap GET_FILE_LIST_HEADERS = HeaderUtils.parseHeaders("""
|
||||||
|
Accept-Encoding: gzip, deflate
|
||||||
|
Cookie: uin=9000002; p_uin=9000002
|
||||||
|
Origin: https://qfile.qq.com
|
||||||
|
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0
|
||||||
|
content-type: application/json
|
||||||
|
x-oidb: {"uint32_command":"0x93d4", "uint32_service_type":"1"}
|
||||||
|
""");
|
||||||
|
|
||||||
|
private static final Pattern FILESET_ID_PATTERN = Pattern.compile(
|
||||||
|
"fileset_id[^a-f0-9]*([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})");
|
||||||
|
|
||||||
|
private static final Pattern TITLE_PATTERN = Pattern.compile("<title>(.*?)</title>");
|
||||||
|
|
||||||
public QQscTool(ShareLinkInfo shareLinkInfo) {
|
public QQscTool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
String jsonTemplate = """
|
|
||||||
{"req_head":{"agent":8},"download_info":[{"batch_id":"%s","scene":{"business_type":4,"app_type":22,"scene_type":5},"index_node":{"file_uuid":"%s"},"url_type":2,"download_scene":0}],"scene_type":103}
|
|
||||||
""";
|
|
||||||
|
|
||||||
client.getAbs(shareLinkInfo.getShareUrl()).send(result -> {
|
client.getAbs(shareLinkInfo.getShareUrl()).send(result -> {
|
||||||
if (result.succeeded()) {
|
if (result.failed()) {
|
||||||
String htmlJs = result.result().bodyAsString();
|
|
||||||
LOG.debug("获取到的HTML内容: {}", htmlJs);
|
|
||||||
String fileUUID = getFileUUID(htmlJs);
|
|
||||||
String fileName = extractFileNameFromTitle(htmlJs);
|
|
||||||
if (fileName != null) {
|
|
||||||
LOG.info("提取到的文件名: {}", fileName);
|
|
||||||
FileInfo fileInfo = new FileInfo();
|
|
||||||
fileInfo.setFileName(fileName);
|
|
||||||
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
|
|
||||||
} else {
|
|
||||||
LOG.warn("未能提取到文件名");
|
|
||||||
}
|
|
||||||
if (fileUUID != null) {
|
|
||||||
LOG.info("提取到的文件UUID: {}", fileUUID);
|
|
||||||
String formatted = jsonTemplate.formatted(fileUUID, fileUUID);
|
|
||||||
JsonObject entries = new JsonObject(formatted);
|
|
||||||
client.postAbs(API_URL)
|
|
||||||
.putHeaders(HEADERS)
|
|
||||||
.sendJsonObject(entries)
|
|
||||||
.onSuccess(result2 -> {
|
|
||||||
if (result2.statusCode() == 200) {
|
|
||||||
JsonObject body = asJson(result2);
|
|
||||||
LOG.debug("API响应内容: {}", body.encodePrettily());
|
|
||||||
// {
|
|
||||||
// "retcode": 0,
|
|
||||||
// "cost": 132,
|
|
||||||
// "message": "",
|
|
||||||
// "error": {
|
|
||||||
// "message": "",
|
|
||||||
// "code": 0
|
|
||||||
// },
|
|
||||||
// "data": {
|
|
||||||
// "download_rsp": [{
|
|
||||||
|
|
||||||
// 取 download_rsp
|
|
||||||
if (!body.containsKey("retcode") || body.getInteger("retcode") != 0) {
|
|
||||||
promise.fail("API请求失败,错误信息: " + body.encodePrettily());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
JsonArray downloadRsp = body.getJsonObject("data").getJsonArray("download_rsp");
|
|
||||||
if (downloadRsp != null && !downloadRsp.isEmpty()) {
|
|
||||||
String url = downloadRsp.getJsonObject(0).getString("url");
|
|
||||||
if (fileName != null) {
|
|
||||||
url = url + "&filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8);
|
|
||||||
}
|
|
||||||
promise.complete(url);
|
|
||||||
} else {
|
|
||||||
promise.fail("API响应中缺少 download_rsp");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
promise.fail("API请求失败,状态码: " + result2.statusCode());
|
|
||||||
}
|
|
||||||
}).onFailure(e -> {
|
|
||||||
LOG.error("API请求异常", e);
|
|
||||||
promise.fail(e);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
LOG.error("未能提取到文件UUID");
|
|
||||||
promise.fail("未能提取到文件UUID");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
LOG.error("请求失败: {}", result.cause().getMessage());
|
LOG.error("请求失败: {}", result.cause().getMessage());
|
||||||
promise.fail(result.cause());
|
promise.fail(result.cause());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String html = result.result().bodyAsString();
|
||||||
|
String fileName = extractFileNameFromTitle(html);
|
||||||
|
if (fileName != null) {
|
||||||
|
FileInfo fileInfo = new FileInfo();
|
||||||
|
fileInfo.setFileName(fileName);
|
||||||
|
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
|
||||||
|
}
|
||||||
|
// 尝试用 GetFileList API 获取第一个文件的下载链接
|
||||||
|
String filesetId = extractFilesetId(html);
|
||||||
|
if (filesetId != null) {
|
||||||
|
fetchFileList(filesetId, "").onSuccess(fileList -> {
|
||||||
|
for (int i = 0; i < fileList.size(); i++) {
|
||||||
|
JsonObject file = fileList.getJsonObject(i);
|
||||||
|
if (!file.getBoolean("is_dir", false)) {
|
||||||
|
String physicalId = file.getJsonObject("physical").getString("id");
|
||||||
|
String name = file.getString("name");
|
||||||
|
downloadFile(physicalId, name);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
promise.fail("未找到可下载的文件");
|
||||||
|
}).onFailure(e -> {
|
||||||
|
LOG.warn("GetFileList 失败,回退到旧解析方式: {}", e.getMessage());
|
||||||
|
parseLegacy(html, fileName);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
parseLegacy(html, fileName);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Future<List<FileInfo>> parseFileList() {
|
||||||
|
Promise<List<FileInfo>> resultPromise = Promise.promise();
|
||||||
|
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
|
||||||
|
|
||||||
|
client.getAbs(shareLinkInfo.getShareUrl()).send(result -> {
|
||||||
|
if (result.failed()) {
|
||||||
|
resultPromise.fail(result.cause());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String html = result.result().bodyAsString();
|
||||||
|
String filesetId = extractFilesetId(html);
|
||||||
|
if (filesetId == null) {
|
||||||
|
resultPromise.fail("无法从页面提取 filesetId");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String parentId = dirId != null ? dirId : "";
|
||||||
|
fetchFileList(filesetId, parentId).onSuccess(fileList -> {
|
||||||
|
try {
|
||||||
|
List<FileInfo> list = new ArrayList<>();
|
||||||
|
String panType = shareLinkInfo.getType();
|
||||||
|
for (int i = 0; i < fileList.size(); i++) {
|
||||||
|
JsonObject file = fileList.getJsonObject(i);
|
||||||
|
FileInfo fileInfo = new FileInfo();
|
||||||
|
String name = file.getString("name");
|
||||||
|
String cliFileid = file.getString("cli_fileid");
|
||||||
|
boolean isDir = file.getBoolean("is_dir", false);
|
||||||
|
String sizeStr = file.getString("file_size");
|
||||||
|
|
||||||
|
fileInfo.setFileName(name)
|
||||||
|
.setFileId(cliFileid)
|
||||||
|
.setPanType(panType)
|
||||||
|
.setSizeStr(sizeStr);
|
||||||
|
|
||||||
|
if (isDir) {
|
||||||
|
fileInfo.setFileType("folder")
|
||||||
|
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s",
|
||||||
|
getDomainName(),
|
||||||
|
URLEncoder.encode(shareLinkInfo.getShareUrl(), StandardCharsets.UTF_8),
|
||||||
|
cliFileid));
|
||||||
|
} else {
|
||||||
|
String physicalId = file.getJsonObject("physical").getString("id");
|
||||||
|
JsonObject paramJson = new JsonObject()
|
||||||
|
.put("fileId", physicalId)
|
||||||
|
.put("fileName", name)
|
||||||
|
.put("cliFileid", cliFileid);
|
||||||
|
String param = CommonUtils.urlBase64Encode(paramJson.encode());
|
||||||
|
fileInfo.setFileType("file")
|
||||||
|
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
|
||||||
|
getDomainName(), panType, param));
|
||||||
|
}
|
||||||
|
list.add(fileInfo);
|
||||||
|
}
|
||||||
|
resultPromise.complete(list);
|
||||||
|
} catch (Exception e) {
|
||||||
|
resultPromise.fail(e);
|
||||||
|
}
|
||||||
|
}).onFailure(resultPromise::fail);
|
||||||
|
});
|
||||||
|
return resultPromise.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Future<String> parseById() {
|
||||||
|
JsonObject paramJson = (JsonObject) shareLinkInfo.getOtherParam().get("paramJson");
|
||||||
|
String fileId = paramJson.getString("fileId");
|
||||||
|
String fileName = paramJson.getString("fileName");
|
||||||
|
|
||||||
|
Promise<String> p = Promise.promise();
|
||||||
|
callBatchDownload(fileId, fileName, p);
|
||||||
|
return p.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 内部方法 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调用 BatchDownload API 获取单个文件的下载直链
|
||||||
|
*/
|
||||||
|
private void downloadFile(String physicalId, String fileName) {
|
||||||
|
callBatchDownload(physicalId, fileName, promise);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void callBatchDownload(String physicalId, String fileName, Promise<String> p) {
|
||||||
|
String body = """
|
||||||
|
{"req_head":{"agent":8},"download_info":[{"batch_id":"%s","scene":{"business_type":4,"app_type":22,"scene_type":5},"index_node":{"file_uuid":"%s"},"url_type":2,"download_scene":0}],"scene_type":103}
|
||||||
|
""".formatted(physicalId, physicalId);
|
||||||
|
|
||||||
|
client.postAbs(BATCH_DOWNLOAD_API)
|
||||||
|
.putHeaders(BATCH_DOWNLOAD_HEADERS)
|
||||||
|
.sendJsonObject(new JsonObject(body))
|
||||||
|
.onSuccess(resp -> {
|
||||||
|
if (resp.statusCode() != 200) {
|
||||||
|
p.fail("BatchDownload 请求失败,状态码: " + resp.statusCode());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JsonObject respBody = asJson(resp);
|
||||||
|
if (!respBody.containsKey("retcode") || respBody.getInteger("retcode") != 0) {
|
||||||
|
p.fail("BatchDownload 请求失败: " + respBody.encodePrettily());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JsonArray downloadRsp = respBody.getJsonObject("data").getJsonArray("download_rsp");
|
||||||
|
if (downloadRsp == null || downloadRsp.isEmpty()) {
|
||||||
|
p.fail("BatchDownload 响应中缺少 download_rsp");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String url = downloadRsp.getJsonObject(0).getString("url");
|
||||||
|
if (url != null && url.startsWith("&filename=")) {
|
||||||
|
p.fail("该文件已被和谐");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (fileName != null) {
|
||||||
|
url = url + "&filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
p.complete(url);
|
||||||
|
})
|
||||||
|
.onFailure(e -> {
|
||||||
|
LOG.error("BatchDownload 请求异常", e);
|
||||||
|
p.fail(e);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调用 GetFileList API 获取指定目录下的文件列表
|
||||||
|
*/
|
||||||
|
private Future<JsonArray> fetchFileList(String filesetId, String parentId) {
|
||||||
|
Promise<JsonArray> p = Promise.promise();
|
||||||
|
JsonObject body = new JsonObject()
|
||||||
|
.put("fileset_id", filesetId)
|
||||||
|
.put("req_infos", new JsonArray()
|
||||||
|
.add(new JsonObject()
|
||||||
|
.put("parent_id", parentId)
|
||||||
|
.put("req_depth", 1)
|
||||||
|
.put("count", 50)
|
||||||
|
.put("filter_condition", new JsonObject().put("file_category", 0))
|
||||||
|
.put("sort_conditions", new JsonArray()
|
||||||
|
.add(new JsonObject()
|
||||||
|
.put("sort_field", 0)
|
||||||
|
.put("sort_order", 0)))))
|
||||||
|
.put("support_folder_status", true);
|
||||||
|
|
||||||
|
// 创建局部副本,避免修改静态 MultiMap 导致并发污染
|
||||||
|
MultiMap headers = MultiMap.caseInsensitiveMultiMap().addAll(GET_FILE_LIST_HEADERS)
|
||||||
|
.set("Referer", shareLinkInfo.getShareUrl());
|
||||||
|
|
||||||
|
client.postAbs(GET_FILE_LIST_API)
|
||||||
|
.putHeaders(headers)
|
||||||
|
.sendJsonObject(body)
|
||||||
|
.onSuccess(resp -> {
|
||||||
|
if (resp.statusCode() != 200) {
|
||||||
|
p.fail("GetFileList 请求失败,状态码: " + resp.statusCode());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JsonObject respBody = asJson(resp);
|
||||||
|
if (respBody.getInteger("retcode", -1) != 0) {
|
||||||
|
p.fail("GetFileList 请求失败: " + respBody.getString("message", "未知错误"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JsonArray fileLists = respBody.getJsonObject("data").getJsonArray("file_lists");
|
||||||
|
if (fileLists == null || fileLists.isEmpty()) {
|
||||||
|
p.fail("GetFileList 响应中缺少 file_lists");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JsonArray fileList = fileLists.getJsonObject(0).getJsonArray("file_list");
|
||||||
|
p.complete(fileList != null ? fileList : new JsonArray());
|
||||||
|
})
|
||||||
|
.onFailure(e -> {
|
||||||
|
LOG.error("GetFileList 请求异常", e);
|
||||||
|
p.fail(e);
|
||||||
|
});
|
||||||
|
return p.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 HTML 的 __NUXT_DATA__ 中提取 fileset_id
|
||||||
|
*/
|
||||||
|
String extractFilesetId(String html) {
|
||||||
|
// Nuxt __NUXT_DATA__ 中 fileset_id 出现在缓存 key 的嵌套 JSON 中
|
||||||
|
// 直接匹配 fileset_id 后面最近的 UUID(跳过转义引号、冒号等非hex字符)
|
||||||
|
Matcher matcher = FILESET_ID_PATTERN.matcher(html);
|
||||||
|
if (matcher.find()) {
|
||||||
|
return matcher.group(1);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 旧版解析方式(兼容单文件链接,通过 HTML 字符串搜索提取 UUID)
|
||||||
|
*/
|
||||||
|
private void parseLegacy(String html, String fileName) {
|
||||||
|
String fileUUID = getFileUUID(html);
|
||||||
|
if (fileUUID == null) {
|
||||||
|
promise.fail("未能提取到文件UUID");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
LOG.info("使用旧版解析,提取到的文件UUID: {}", fileUUID);
|
||||||
|
downloadFile(fileUUID, fileName);
|
||||||
|
}
|
||||||
|
|
||||||
String getFileUUID(String htmlJs) {
|
String getFileUUID(String htmlJs) {
|
||||||
String keyword = "\"download_limit_status\"";
|
String keyword = "\"download_limit_status\"";
|
||||||
String marker = "},\"";
|
String marker = "},\"";
|
||||||
@@ -140,32 +324,22 @@ public class QQscTool extends PanBase {
|
|||||||
String extracted = htmlJs.substring(quoteStart, quoteEnd);
|
String extracted = htmlJs.substring(quoteStart, quoteEnd);
|
||||||
LOG.debug("提取结果: {}", extracted);
|
LOG.debug("提取结果: {}", extracted);
|
||||||
return extracted;
|
return extracted;
|
||||||
} else {
|
|
||||||
LOG.error("未找到结束引号: {}", marker);
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
LOG.error("未找到标记: {} 在关键字: {} 之后", marker, keyword);
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
LOG.error("未找到关键字: {}", keyword);
|
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static String extractFileNameFromTitle(String content) {
|
public static String extractFileNameFromTitle(String content) {
|
||||||
// 匹配<title>和</title>之间的内容
|
Matcher matcher = TITLE_PATTERN.matcher(content);
|
||||||
Pattern pattern = Pattern.compile("<title>(.*?)</title>");
|
|
||||||
Matcher matcher = pattern.matcher(content);
|
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
String fullTitle = matcher.group(1);
|
String fullTitle = matcher.group(1);
|
||||||
// 按 "|" 分割,取前半部分
|
|
||||||
int sepIndex = fullTitle.indexOf("|");
|
int sepIndex = fullTitle.indexOf("|");
|
||||||
if (sepIndex != -1) {
|
if (sepIndex != -1) {
|
||||||
return fullTitle.substring(0, sepIndex);
|
return fullTitle.substring(0, sepIndex);
|
||||||
}
|
}
|
||||||
return fullTitle; // 如果没有分隔符,就返回全部
|
return fullTitle;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3,10 +3,11 @@ package cn.qaiu.parser.impl;
|
|||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
import java.util.HashMap;
|
import io.vertx.core.buffer.Buffer;
|
||||||
import java.util.Map;
|
import io.vertx.core.json.JsonObject;
|
||||||
import java.util.regex.Matcher;
|
|
||||||
import java.util.regex.Pattern;
|
import java.net.URLEncoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
public class QQwTool extends QQTool {
|
public class QQwTool extends QQTool {
|
||||||
|
|
||||||
@@ -16,54 +17,51 @@ public class QQwTool extends QQTool {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
client.getAbs(shareLinkInfo.getShareUrl()).send().onSuccess(res -> {
|
String k = shareLinkInfo.getShareKey();
|
||||||
String html = res.bodyAsString();
|
String postBody = "f=json&k=" + URLEncoder.encode(k, StandardCharsets.UTF_8);
|
||||||
Map<String, String> stringStringMap = extractVariables(html);
|
|
||||||
String url = stringStringMap.get("url");
|
|
||||||
String fn = stringStringMap.get("filename");
|
|
||||||
String size = stringStringMap.get("filesize");
|
|
||||||
String createBy = stringStringMap.get("nick");
|
|
||||||
FileInfo fileInfo = new FileInfo().setFileName(fn).setSize(Long.parseLong(size)).setCreateBy(createBy);
|
|
||||||
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
|
|
||||||
if (url != null) {
|
|
||||||
String url302 = url.replace("\\x26", "&");
|
|
||||||
promise.complete(url302);
|
|
||||||
|
|
||||||
/*
|
client.postAbs("https://wx.mail.qq.com/s")
|
||||||
clientNoRedirects.getAbs(url302).send().onSuccess(res2 -> {
|
.putHeader("Content-Type", "application/x-www-form-urlencoded")
|
||||||
MultiMap headers = res2.headers();
|
.putHeader("Accept", "application/json, text/plain, */*")
|
||||||
if (headers.contains("Location")) {
|
.putHeader("Referer", shareLinkInfo.getShareUrl())
|
||||||
promise.complete(headers.get("Location"));
|
.putHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||||
} else {
|
+ "(KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0")
|
||||||
fail("找不到重定向URL");
|
.sendBuffer(Buffer.buffer(postBody))
|
||||||
|
.onSuccess(res -> {
|
||||||
|
try {
|
||||||
|
JsonObject data = asJson(res);
|
||||||
|
JsonObject head = data.getJsonObject("head");
|
||||||
|
if (head == null || head.getInteger("ret", -1) != 0) {
|
||||||
|
String msg = head != null ? head.getString("msg", "未知错误") : "未知错误";
|
||||||
|
fail("API错误: " + msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonObject body = data.getJsonObject("body");
|
||||||
|
if (body == null) {
|
||||||
|
fail("文件信息为空");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String url = body.getString("url");
|
||||||
|
String fn = body.getString("name", "");
|
||||||
|
long size = body.getLong("size", 0L);
|
||||||
|
|
||||||
|
if (url == null || url.isEmpty()) {
|
||||||
|
fail("分享链接解析失败, 可能是链接失效");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
FileInfo fileInfo = new FileInfo().setFileName(fn).setSize(size);
|
||||||
|
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
|
||||||
|
|
||||||
|
String url302 = url.replace("\\x26", "&");
|
||||||
|
complete(url302);
|
||||||
|
} catch (Exception e) {
|
||||||
|
fail(e, "解析响应失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
}).onFailure(handleFail());
|
}).onFailure(handleFail());
|
||||||
*/
|
|
||||||
} else {
|
|
||||||
fail("分享链接解析失败, 可能是链接失效");
|
|
||||||
}
|
|
||||||
}).onFailure(handleFail());
|
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private Map<String, String> extractVariables(String jsCode) {
|
|
||||||
Map<String, String> variables = new HashMap<>();
|
|
||||||
// 正则表达式匹配 var 变量定义
|
|
||||||
String regex = "\\s+var\\s+(\\w+)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^;\\r\\n]*))";
|
|
||||||
Pattern p = Pattern.compile(regex);
|
|
||||||
Matcher m = p.matcher(jsCode);
|
|
||||||
|
|
||||||
while (m.find()) {
|
|
||||||
String name = m.group(1);
|
|
||||||
String value = m.group(2) != null ? m.group(2)
|
|
||||||
: m.group(3) != null ? m.group(3)
|
|
||||||
: m.group(4);
|
|
||||||
variables.put(name, value);
|
|
||||||
}
|
|
||||||
|
|
||||||
return variables;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,699 @@
|
|||||||
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import io.vertx.core.Future;
|
||||||
|
import io.vertx.core.MultiMap;
|
||||||
|
import io.vertx.core.Promise;
|
||||||
|
import io.vertx.core.Vertx;
|
||||||
|
import io.vertx.core.buffer.Buffer;
|
||||||
|
import io.vertx.core.http.HttpClient;
|
||||||
|
import io.vertx.core.http.HttpClientOptions;
|
||||||
|
import io.vertx.core.http.HttpClientResponse;
|
||||||
|
import io.vertx.core.http.HttpHeaders;
|
||||||
|
import io.vertx.core.http.HttpMethod;
|
||||||
|
import io.vertx.core.http.RequestOptions;
|
||||||
|
import io.vertx.core.json.JsonArray;
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
|
import io.vertx.ext.web.client.HttpResponse;
|
||||||
|
import io.vertx.ext.web.client.WebClient;
|
||||||
|
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 夸克 / UC 单文件下载策略。
|
||||||
|
* <p>
|
||||||
|
* 体积不大于 {@link #NORMAL_PARSE_MAX_BYTES}(10MiB,即 {@code 10 * 1024 * 1024},等于阈值仍走原解析)时,
|
||||||
|
* 调用方保持现有分享下载。更大且能读到体积的文件:先用会员接口确认未过期的 SVIP/VIP,
|
||||||
|
* 再用该账号已有的 {@code /file/download} 直链;否则只接受 H5 预览返回、并经匿名探测确认为文件字节的
|
||||||
|
* {@code https://dl-c-* .drive.quark.cn|drive.uc.cn} 地址,附上真实文件名。
|
||||||
|
* 预览网页、HTML、JSON、m3u8 播放列表和登录态 CDN 都不当作下载成功。
|
||||||
|
* UC 不因为尝试 H5 就变成免登录。
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
public final class QuarkFamilyDownloadPolicy {
|
||||||
|
|
||||||
|
/** 10MiB。仓库没有另一套 10MB 常量,按二进制兆字节 {@code 10 * 1024 * 1024}。 */
|
||||||
|
public static final long NORMAL_PARSE_MAX_BYTES = 10L * 1024 * 1024;
|
||||||
|
|
||||||
|
private static final Set<String> PAID_TYPES = Set.of(
|
||||||
|
"SUPER_VIP", "EXP_SVIP", "Z_VIP", "VIP", "EXP_VIP");
|
||||||
|
private static final List<String> BARE_QUERY = List.of("auth_key", "sp", "token");
|
||||||
|
private static final String GUEST_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||||
|
+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
|
||||||
|
private static final int PROBE_PREFIX_BYTES = 64;
|
||||||
|
|
||||||
|
private QuarkFamilyDownloadPolicy() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 已知体积且严格大于 10MiB。缺少体积或无法解析时返回 false,调用方继续原解析。 */
|
||||||
|
public static boolean knownLarge(long size) {
|
||||||
|
return size > NORMAL_PARSE_MAX_BYTES && size < Long.MAX_VALUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long sizeOf(JsonObject item) {
|
||||||
|
if (item == null || !item.containsKey("size")) {
|
||||||
|
return Long.MAX_VALUE;
|
||||||
|
}
|
||||||
|
return sizeOf(item.getValue("size"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long sizeOf(Object value) {
|
||||||
|
if (value instanceof Number number) {
|
||||||
|
return number.longValue();
|
||||||
|
}
|
||||||
|
if (value instanceof String text && !text.isBlank()) {
|
||||||
|
try {
|
||||||
|
return Long.parseLong(text.trim());
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
return Long.MAX_VALUE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Long.MAX_VALUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final class Membership {
|
||||||
|
public final boolean validPaid;
|
||||||
|
public final String memberType;
|
||||||
|
public final Long expAtMs;
|
||||||
|
public final String reason;
|
||||||
|
|
||||||
|
Membership(boolean validPaid, String memberType, Long expAtMs, String reason) {
|
||||||
|
this.validPaid = validPaid;
|
||||||
|
this.memberType = memberType;
|
||||||
|
this.expAtMs = expAtMs;
|
||||||
|
this.reason = reason;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Membership notPaid(String type, Long expAtMs, String reason) {
|
||||||
|
return new Membership(false, type, expAtMs, reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 只认会员接口的 {@code member_type} 和 {@code exp_at}。Cookie 是否存在不参与判断。
|
||||||
|
* 体验会员(EXP_SVIP / EXP_VIP)和 Z_VIP 在到期前算有效;NORMAL、未知档位、缺少到期时间或已到期都无效。
|
||||||
|
*/
|
||||||
|
public static Membership judgeMembership(JsonObject data, long nowMs) {
|
||||||
|
if (data == null) {
|
||||||
|
return Membership.notPaid(null, null, "会员接口没有 data");
|
||||||
|
}
|
||||||
|
String raw = data.getString("member_type");
|
||||||
|
if (raw == null || raw.isBlank()) {
|
||||||
|
return Membership.notPaid(null, null, "会员接口没有 member_type");
|
||||||
|
}
|
||||||
|
String type = raw.trim().toUpperCase(Locale.ROOT);
|
||||||
|
Long expAt = epochMillis(data.getValue("exp_at"));
|
||||||
|
if (!PAID_TYPES.contains(type)) {
|
||||||
|
return Membership.notPaid(type, expAt, "当前档位不是未过期的 SVIP/VIP");
|
||||||
|
}
|
||||||
|
if (expAt == null) {
|
||||||
|
return Membership.notPaid(type, null, "会员接口没有 exp_at,不能确认未过期");
|
||||||
|
}
|
||||||
|
if (expAt <= nowMs) {
|
||||||
|
return Membership.notPaid(type, expAt, "会员已过期");
|
||||||
|
}
|
||||||
|
return new Membership(true, type, expAt, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Long epochMillis(Object value) {
|
||||||
|
Long raw = null;
|
||||||
|
if (value instanceof Number number) {
|
||||||
|
raw = number.longValue();
|
||||||
|
} else if (value instanceof String text && !text.isBlank()) {
|
||||||
|
try {
|
||||||
|
raw = Long.parseLong(text.trim());
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (raw == null || raw <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return raw < 100_000_000_000L ? raw * 1000L : raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Future<Membership> fetchMembership(WebClient client, MultiMap apiHeaders, boolean uc) {
|
||||||
|
String url = uc
|
||||||
|
? "https://pc-api.uc.cn/1/clouddrive/member?pr=UCBrowser&fr=pc&fetch_subscribe=true&_ch=home&fetch_identity=true"
|
||||||
|
: "https://drive-pc.quark.cn/1/clouddrive/member?pr=ucpro&fr=pc&fetch_subscribe=true&_ch=home&fetch_identity=true";
|
||||||
|
return fetchMembership(client, apiHeaders, url, uc);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<Membership> fetchMembership(WebClient client, MultiMap apiHeaders, String memberUrl, boolean uc) {
|
||||||
|
String cookie = apiHeaders == null ? null : apiHeaders.get(HttpHeaders.COOKIE);
|
||||||
|
if (cookie == null || cookie.isBlank()) {
|
||||||
|
return Future.succeededFuture(Membership.notPaid(null, null, "未配置 Cookie"));
|
||||||
|
}
|
||||||
|
String referer = uc ? "https://drive.uc.cn/" : "https://pan.quark.cn/";
|
||||||
|
String ua = apiHeaders.get(HttpHeaders.USER_AGENT);
|
||||||
|
if (ua == null || ua.isBlank()) {
|
||||||
|
ua = GUEST_UA;
|
||||||
|
}
|
||||||
|
return client.getAbs(memberUrl)
|
||||||
|
.putHeader(HttpHeaders.COOKIE.toString(), cookie)
|
||||||
|
.putHeader(HttpHeaders.USER_AGENT.toString(), ua)
|
||||||
|
.putHeader(HttpHeaders.REFERER.toString(), referer)
|
||||||
|
.timeout(10_000)
|
||||||
|
.send()
|
||||||
|
.map(res -> membershipFromResponse(res))
|
||||||
|
.recover(err -> Future.succeededFuture(
|
||||||
|
Membership.notPaid(null, null, "会员接口不可用")));
|
||||||
|
}
|
||||||
|
|
||||||
|
static Membership membershipFromResponse(HttpResponse<?> res) {
|
||||||
|
int status = res.statusCode();
|
||||||
|
if (status == 401 || status == 403) {
|
||||||
|
return Membership.notPaid(null, null, "会员接口拒绝访问 HTTP " + status);
|
||||||
|
}
|
||||||
|
String type = res.getHeader(HttpHeaders.CONTENT_TYPE.toString());
|
||||||
|
if (type != null && type.toLowerCase(Locale.ROOT).contains("text/html")) {
|
||||||
|
return Membership.notPaid(null, null, "会员接口返回了 HTML");
|
||||||
|
}
|
||||||
|
JsonObject json;
|
||||||
|
try {
|
||||||
|
json = res.bodyAsJsonObject();
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Membership.notPaid(null, null, "会员接口没有返回 JSON");
|
||||||
|
}
|
||||||
|
if (json == null) {
|
||||||
|
return Membership.notPaid(null, null, "会员接口没有返回 JSON");
|
||||||
|
}
|
||||||
|
Integer code = json.getInteger("code");
|
||||||
|
if (code != null && code != 0) {
|
||||||
|
return Membership.notPaid(null, null, "会员接口失败 code=" + code);
|
||||||
|
}
|
||||||
|
return judgeMembership(json.getJsonObject("data"), System.currentTimeMillis());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* H5 预览签发的公开文件地址。不带登录 Cookie。探测只读响应头和最多 64 字节,不把文件收进内存。
|
||||||
|
*/
|
||||||
|
public static Future<String> resolveH5Download(WebClient client, Vertx vertx, String pan,
|
||||||
|
String pwdId, String stoken, String fid,
|
||||||
|
String fidToken, String fileName) {
|
||||||
|
if (isBlank(fid) || isBlank(fidToken) || isBlank(pwdId) || isBlank(stoken)) {
|
||||||
|
return Future.failedFuture("分享参数不完整,无法请求 H5 预览");
|
||||||
|
}
|
||||||
|
if (isBlank(fileName)) {
|
||||||
|
return Future.failedFuture("没有真实文件名,不能把预览地址当作下载");
|
||||||
|
}
|
||||||
|
return requestRichText(client, pan, pwdId, stoken, fid, fidToken)
|
||||||
|
.compose(raw -> acceptProbed(vertx, pan, raw, fileName))
|
||||||
|
.recover(richErr -> requestVideo(client, pan, pwdId, stoken, fid, fidToken)
|
||||||
|
.compose(raw -> acceptProbed(vertx, pan, raw, fileName))
|
||||||
|
.recover(videoErr -> Future.failedFuture(joinReasons(richErr, videoErr))));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Future<String> acceptProbed(Vertx vertx, String pan, String raw, String fileName) {
|
||||||
|
if (raw != null && raw.toLowerCase(Locale.ROOT).contains(".m3u8")) {
|
||||||
|
return Future.failedFuture("只得到 m3u8 播放列表,不是文件");
|
||||||
|
}
|
||||||
|
if (!isPublicFileUrl(raw, pan)) {
|
||||||
|
return Future.failedFuture("预览地址不是公开文件 CDN");
|
||||||
|
}
|
||||||
|
return probeBody(vertx, raw, pan, 1).compose(hit -> {
|
||||||
|
if (!hit.ok) {
|
||||||
|
return Future.failedFuture(hit.reason);
|
||||||
|
}
|
||||||
|
return Future.succeededFuture(withFilename(bareFileUrl(raw), fileName));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Future<String> requestRichText(WebClient client, String pan, String pwdId, String stoken,
|
||||||
|
String fid, String fidToken) {
|
||||||
|
boolean uc = isUc(pan);
|
||||||
|
String base = uc ? "https://pc-api.uc.cn/1/clouddrive" : "https://drive.quark.cn/1/clouddrive";
|
||||||
|
String site = uc ? "https://drive.uc.cn" : "https://vt.quark.cn";
|
||||||
|
return requestPreview(client, pan, base, "h5", site, "/share/sharepage/rich_text/preview",
|
||||||
|
pwdId, stoken, fid, fidToken, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Future<String> requestVideo(WebClient client, String pan, String pwdId, String stoken,
|
||||||
|
String fid, String fidToken) {
|
||||||
|
List<String[]> attempts = isUc(pan)
|
||||||
|
? List.of(
|
||||||
|
new String[]{"https://pc-api.uc.cn/1/clouddrive", "h5", "https://drive.uc.cn"},
|
||||||
|
new String[]{"https://pc-api.uc.cn/1/clouddrive", "pc", "https://drive.uc.cn"})
|
||||||
|
: List.of(
|
||||||
|
new String[]{"https://drive.quark.cn/1/clouddrive", "h5", "https://vt.quark.cn"},
|
||||||
|
new String[]{"https://drive.quark.cn/1/clouddrive", "pc", "https://pan.quark.cn"},
|
||||||
|
new String[]{"https://drive-h.quark.cn/1/clouddrive", "h5", "https://pan.quark.cn"});
|
||||||
|
return requestVideoAt(client, pan, attempts, 0, pwdId, stoken, fid, fidToken, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Future<String> requestVideoAt(WebClient client, String pan, List<String[]> attempts, int index,
|
||||||
|
String pwdId, String stoken, String fid, String fidToken,
|
||||||
|
Throwable last) {
|
||||||
|
if (index >= attempts.size()) {
|
||||||
|
return Future.failedFuture(last == null ? new IllegalStateException("视频预览没有公开文件地址") : last);
|
||||||
|
}
|
||||||
|
String[] attempt = attempts.get(index);
|
||||||
|
return requestPreview(client, pan, attempt[0], attempt[1], attempt[2],
|
||||||
|
"/share/sharepage/video/preview", pwdId, stoken, fid, fidToken, true)
|
||||||
|
.recover(err -> requestVideoAt(client, pan, attempts, index + 1, pwdId, stoken, fid, fidToken, err));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Future<String> requestPreview(WebClient client, String pan, String base, String fr, String site,
|
||||||
|
String path, String pwdId, String stoken, String fid,
|
||||||
|
String fidToken, boolean video) {
|
||||||
|
String pr = isUc(pan) ? "UCBrowser" : "ucpro";
|
||||||
|
var req = client.getAbs(base + path)
|
||||||
|
.putHeader(HttpHeaders.USER_AGENT.toString(), GUEST_UA)
|
||||||
|
.putHeader(HttpHeaders.ACCEPT.toString(), "application/json, text/plain, */*")
|
||||||
|
.putHeader(HttpHeaders.REFERER.toString(), site + "/")
|
||||||
|
.putHeader("Origin", site)
|
||||||
|
.putHeader("x-clouddrive-st", "null")
|
||||||
|
.addQueryParam("fid", fid)
|
||||||
|
.addQueryParam("fid_token", fidToken)
|
||||||
|
.addQueryParam("fr", fr)
|
||||||
|
.addQueryParam("pr", pr)
|
||||||
|
.addQueryParam("pwd_id", pwdId)
|
||||||
|
.addQueryParam("stoken", stoken);
|
||||||
|
if (video) {
|
||||||
|
req.addQueryParam("resolution", "low,normal,high,super,2k,4k");
|
||||||
|
req.addQueryParam("supports", "fmp4,m3u8,dolby_vision");
|
||||||
|
}
|
||||||
|
return req.timeout(10_000).send().compose(res -> interpretPreview(res, pan, video));
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<String> interpretPreview(HttpResponse<?> res, String pan, boolean video) {
|
||||||
|
int status = res.statusCode();
|
||||||
|
String contentType = res.getHeader(HttpHeaders.CONTENT_TYPE.toString());
|
||||||
|
if (contentType != null && contentType.toLowerCase(Locale.ROOT).contains("text/html")) {
|
||||||
|
return Future.failedFuture("H5 预览返回了 HTML 页面,不是文件");
|
||||||
|
}
|
||||||
|
if (status >= 400) {
|
||||||
|
return Future.failedFuture("H5 预览 HTTP " + status);
|
||||||
|
}
|
||||||
|
JsonObject json;
|
||||||
|
try {
|
||||||
|
json = res.bodyAsJsonObject();
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Future.failedFuture("H5 预览不是 JSON");
|
||||||
|
}
|
||||||
|
if (json == null) {
|
||||||
|
return Future.failedFuture("H5 预览不是 JSON");
|
||||||
|
}
|
||||||
|
int code = json.getInteger("code", -1);
|
||||||
|
if (code != 0) {
|
||||||
|
return Future.failedFuture("H5 预览失败: " + sanitize(json.getString("message", "code=" + code)));
|
||||||
|
}
|
||||||
|
JsonObject data = json.getJsonObject("data", new JsonObject());
|
||||||
|
if (video) {
|
||||||
|
String picked = pickProgressiveFileUrl(data, pan);
|
||||||
|
if (isBlank(picked)) {
|
||||||
|
return Future.failedFuture("视频预览没有公开文件地址");
|
||||||
|
}
|
||||||
|
return Future.succeededFuture(picked);
|
||||||
|
}
|
||||||
|
String download = data.getString("download_url", "");
|
||||||
|
if (isBlank(download)) {
|
||||||
|
return Future.failedFuture("H5 预览没有 download_url");
|
||||||
|
}
|
||||||
|
return Future.succeededFuture(download);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从视频预览里选公开 CDN 上的渐进文件。m3u8 和登录态节点丢掉。 */
|
||||||
|
static String pickProgressiveFileUrl(JsonObject data, String pan) {
|
||||||
|
if (data == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String best = "";
|
||||||
|
int bestWidth = -1;
|
||||||
|
JsonArray list = data.getJsonArray("video_list");
|
||||||
|
if (list != null) {
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
Object raw = list.getValue(i);
|
||||||
|
if (!(raw instanceof JsonObject item)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
JsonObject info = item.getJsonObject("video_info");
|
||||||
|
String candidate = publicFileCandidate(info == null ? "" : info.getString("url", ""), pan);
|
||||||
|
if (isBlank(candidate)) {
|
||||||
|
candidate = publicFileCandidate(item.getString("url", ""), pan);
|
||||||
|
}
|
||||||
|
if (isBlank(candidate) || candidate.toLowerCase(Locale.ROOT).contains(".m3u8")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int width = widthOf(info != null ? info : item);
|
||||||
|
if (width >= bestWidth) {
|
||||||
|
best = candidate;
|
||||||
|
bestWidth = width;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isBlank(best)) {
|
||||||
|
String direct = publicFileCandidate(data.getString("download_url", ""), pan);
|
||||||
|
if (!isBlank(direct) && !direct.toLowerCase(Locale.ROOT).contains(".m3u8")) {
|
||||||
|
best = direct;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String publicFileCandidate(String url, String pan) {
|
||||||
|
if (isBlank(url) || !isPublicFileUrl(bareFileUrl(url), pan)) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return withoutFilename(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int widthOf(JsonObject obj) {
|
||||||
|
if (obj == null || !obj.containsKey("width")) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
Object value = obj.getValue("width");
|
||||||
|
if (value instanceof Number number) {
|
||||||
|
return number.intValue();
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公开文件 CDN。登录态节点(dl-pc、dl-guest、*.u-drive)和预览网页都不是。
|
||||||
|
*/
|
||||||
|
public static boolean isPublicFileUrl(String url, String pan) {
|
||||||
|
if (isBlank(url) || !url.startsWith("https://")) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String host = hostOf(url);
|
||||||
|
if (host == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String suffix = isUc(pan) ? ".drive.uc.cn" : ".drive.quark.cn";
|
||||||
|
return host.startsWith("dl-c-")
|
||||||
|
&& host.endsWith(suffix)
|
||||||
|
&& !host.contains(".u-drive.")
|
||||||
|
&& host.length() > "dl-c-".length() + suffix.length();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String hostOf(String url) {
|
||||||
|
int start = "https://".length();
|
||||||
|
int end = url.length();
|
||||||
|
for (int i = start; i < url.length(); i++) {
|
||||||
|
char c = url.charAt(i);
|
||||||
|
if (c == '/' || c == '?' || c == '#') {
|
||||||
|
end = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (end <= start) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String host = url.substring(start, end);
|
||||||
|
int colon = host.indexOf(':');
|
||||||
|
if (colon >= 0) {
|
||||||
|
host = host.substring(0, colon);
|
||||||
|
}
|
||||||
|
return host.toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String bareFileUrl(String url) {
|
||||||
|
if (isBlank(url) || !url.startsWith("http")) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
int q = url.indexOf('?');
|
||||||
|
if (q < 0) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
String base = url.substring(0, q);
|
||||||
|
StringBuilder kept = new StringBuilder();
|
||||||
|
for (String pair : url.substring(q + 1).split("&")) {
|
||||||
|
int eq = pair.indexOf('=');
|
||||||
|
String key = eq >= 0 ? pair.substring(0, eq) : pair;
|
||||||
|
if (BARE_QUERY.contains(key)) {
|
||||||
|
kept.append(kept.length() == 0 ? '?' : '&').append(pair);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return base + kept;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String withoutFilename(String url) {
|
||||||
|
if (isBlank(url) || url.indexOf('?') < 0 || !url.contains("filename=")) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
int q = url.indexOf('?');
|
||||||
|
String base = url.substring(0, q);
|
||||||
|
StringBuilder kept = new StringBuilder();
|
||||||
|
for (String pair : url.substring(q + 1).split("&")) {
|
||||||
|
int eq = pair.indexOf('=');
|
||||||
|
String key = eq >= 0 ? pair.substring(0, eq) : pair;
|
||||||
|
if ("filename".equals(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
kept.append(kept.length() == 0 ? '?' : '&').append(pair);
|
||||||
|
}
|
||||||
|
return base + kept;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 登录态接口如果实际给了公开 CDN,去掉埋点并补上文件名,调用方不要再附带 Cookie / Referer。 */
|
||||||
|
public static String presentPublicDownload(String url, String pan, String fileName) {
|
||||||
|
if (!isPublicFileUrl(bareFileUrl(url), pan)) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
String bare = bareFileUrl(url);
|
||||||
|
if (isBlank(fileName) || bare.contains("filename=")) {
|
||||||
|
return bare;
|
||||||
|
}
|
||||||
|
return withFilename(bare, fileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** CDN 用 {@code filename} 生成 Content-Disposition。跨域时浏览器会忽略 a[download]。 */
|
||||||
|
public static String withFilename(String url, String fileName) {
|
||||||
|
if (isBlank(url) || isBlank(fileName)) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
String encoded = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replace("+", "%20");
|
||||||
|
return url + (url.contains("?") ? "&" : "?") + "filename=" + encoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
static final class ProbeHit {
|
||||||
|
final boolean ok;
|
||||||
|
final String reason;
|
||||||
|
final int prefixLength;
|
||||||
|
|
||||||
|
ProbeHit(boolean ok, String reason, int prefixLength) {
|
||||||
|
this.ok = ok;
|
||||||
|
this.reason = reason;
|
||||||
|
this.prefixLength = prefixLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
static ProbeHit ok(int prefixLength) {
|
||||||
|
return new ProbeHit(true, null, prefixLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
static ProbeHit fail(String reason) {
|
||||||
|
return new ProbeHit(false, reason, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 匿名探测。只连接已经通过 {@link #isPublicFileUrl} 的地址;测试可直接调用以检查截断和 HTML 判断。
|
||||||
|
* 读满 {@value #PROBE_PREFIX_BYTES} 字节后立刻断开,不缓冲整份文件。
|
||||||
|
*/
|
||||||
|
static Future<ProbeHit> probeBody(Vertx vertx, String url, String pan, int redirectsLeft) {
|
||||||
|
if (isBlank(url) || !(url.startsWith("https://") || url.startsWith("http://127.0.0.1")
|
||||||
|
|| url.startsWith("http://localhost"))) {
|
||||||
|
return Future.succeededFuture(ProbeHit.fail("拒绝探测非公开文件地址"));
|
||||||
|
}
|
||||||
|
if (url.startsWith("https://") && !isPublicFileUrl(url, pan)) {
|
||||||
|
return Future.succeededFuture(ProbeHit.fail("拒绝探测非公开文件地址"));
|
||||||
|
}
|
||||||
|
HttpClient client = vertx.createHttpClient(new HttpClientOptions()
|
||||||
|
.setConnectTimeout(8_000)
|
||||||
|
.setIdleTimeout(10)
|
||||||
|
.setKeepAlive(false)
|
||||||
|
.setMaxHeaderSize(16 * 1024)
|
||||||
|
.setTrustAll(false)
|
||||||
|
.setVerifyHost(true));
|
||||||
|
RequestOptions options = new RequestOptions()
|
||||||
|
.setMethod(HttpMethod.GET)
|
||||||
|
.setAbsoluteURI(url)
|
||||||
|
.setTimeout(8_000);
|
||||||
|
Promise<ProbeHit> promise = Promise.promise();
|
||||||
|
client.request(options).compose(request -> {
|
||||||
|
request.setFollowRedirects(false);
|
||||||
|
request.putHeader(HttpHeaders.USER_AGENT.toString(), GUEST_UA);
|
||||||
|
request.putHeader(HttpHeaders.ACCEPT.toString(), "*/*");
|
||||||
|
request.putHeader("Range", "bytes=0-15");
|
||||||
|
return request.send();
|
||||||
|
}).compose(resp -> readPrefix(resp).compose(prefix -> {
|
||||||
|
int status = resp.statusCode();
|
||||||
|
if (status >= 300 && status < 400 && redirectsLeft > 0) {
|
||||||
|
String location = resp.getHeader(HttpHeaders.LOCATION.toString());
|
||||||
|
if (location != null && isPublicFileUrl(location, pan)) {
|
||||||
|
return probeBody(vertx, location, pan, redirectsLeft - 1);
|
||||||
|
}
|
||||||
|
return Future.succeededFuture(ProbeHit.fail("跳转目标不是公开文件 CDN"));
|
||||||
|
}
|
||||||
|
return Future.succeededFuture(judgeProbe(status,
|
||||||
|
resp.getHeader(HttpHeaders.CONTENT_TYPE.toString()),
|
||||||
|
resp.getHeader("Content-Range"),
|
||||||
|
resp.getHeader(HttpHeaders.CONTENT_LENGTH.toString()),
|
||||||
|
prefix));
|
||||||
|
})).onComplete(ar -> {
|
||||||
|
client.close();
|
||||||
|
if (ar.succeeded()) {
|
||||||
|
promise.tryComplete(ar.result());
|
||||||
|
} else {
|
||||||
|
promise.tryComplete(ProbeHit.fail("探测失败"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return promise.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Future<Buffer> readPrefix(HttpClientResponse resp) {
|
||||||
|
Promise<Buffer> promise = Promise.promise();
|
||||||
|
Buffer prefix = Buffer.buffer();
|
||||||
|
boolean[] finished = {false};
|
||||||
|
Runnable finish = () -> {
|
||||||
|
if (finished[0]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
finished[0] = true;
|
||||||
|
try {
|
||||||
|
resp.request().reset();
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// 对端已结束时 reset 会失败,前缀已经够用。
|
||||||
|
}
|
||||||
|
promise.tryComplete(prefix);
|
||||||
|
};
|
||||||
|
resp.handler(buf -> {
|
||||||
|
if (prefix.length() < PROBE_PREFIX_BYTES) {
|
||||||
|
int n = Math.min(buf.length(), PROBE_PREFIX_BYTES - prefix.length());
|
||||||
|
prefix.appendBuffer(buf, 0, n);
|
||||||
|
}
|
||||||
|
if (prefix.length() >= PROBE_PREFIX_BYTES) {
|
||||||
|
finish.run();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
resp.endHandler(v -> finish.run());
|
||||||
|
resp.exceptionHandler(err -> {
|
||||||
|
if (!finished[0]) {
|
||||||
|
promise.tryFail(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
resp.fetch(PROBE_PREFIX_BYTES);
|
||||||
|
return promise.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
static ProbeHit judgeProbe(int status, String contentType, String contentRange, String contentLength, Buffer prefix) {
|
||||||
|
if (status != 200 && status != 206) {
|
||||||
|
return ProbeHit.fail("HTTP " + status);
|
||||||
|
}
|
||||||
|
if (looksLikeHtml(contentType, prefix)) {
|
||||||
|
return ProbeHit.fail("响应是 HTML,不是文件");
|
||||||
|
}
|
||||||
|
if (contentType != null && contentType.toLowerCase(Locale.ROOT).contains("json")) {
|
||||||
|
return ProbeHit.fail("响应是 JSON,不是文件");
|
||||||
|
}
|
||||||
|
boolean ranged = status == 206 && contentRange != null && !contentRange.isBlank();
|
||||||
|
long length = -1;
|
||||||
|
if (contentLength != null && !contentLength.isBlank()) {
|
||||||
|
try {
|
||||||
|
length = Long.parseLong(contentLength.trim());
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
length = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!ranged && length == 0) {
|
||||||
|
return ProbeHit.fail("响应没有文件内容");
|
||||||
|
}
|
||||||
|
if (!ranged && (contentType == null || contentType.isBlank())) {
|
||||||
|
return ProbeHit.fail("响应没有 Content-Type,不能确认是文件");
|
||||||
|
}
|
||||||
|
return ProbeHit.ok(prefix == null ? 0 : prefix.length());
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean looksLikeHtml(String contentType, Buffer prefix) {
|
||||||
|
if (contentType != null) {
|
||||||
|
String type = contentType.toLowerCase(Locale.ROOT);
|
||||||
|
if (type.contains("text/html") || type.contains("application/xhtml")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (prefix == null || prefix.length() == 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int n = Math.min(prefix.length(), 32);
|
||||||
|
String head = prefix.getString(0, n, "UTF-8").stripLeading().toLowerCase(Locale.ROOT);
|
||||||
|
return head.startsWith("<!doctype") || head.startsWith("<html") || head.startsWith("<head");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公开文件地址不沿用目录参数里的账号请求头。返回值表示浏览器是否必须改走下载器。
|
||||||
|
*/
|
||||||
|
public static boolean prepareDownloader(Map<String, String> headers, boolean paramNeedsDownloader, boolean publicDirect) {
|
||||||
|
if (publicDirect) {
|
||||||
|
if (headers != null) {
|
||||||
|
headers.clear();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return paramNeedsDownloader || (headers != null && !headers.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String largeFileError(String pan, Throwable directError, Throwable h5Error) {
|
||||||
|
boolean uc = isUc(pan);
|
||||||
|
StringBuilder message = new StringBuilder();
|
||||||
|
if (uc) {
|
||||||
|
message.append("UC 超过 10MiB(").append(NORMAL_PARSE_MAX_BYTES)
|
||||||
|
.append(" 字节)的文件不能免登录下载。当前没有未过期的 SVIP/VIP,");
|
||||||
|
} else {
|
||||||
|
message.append("夸克超过 10MiB(").append(NORMAL_PARSE_MAX_BYTES)
|
||||||
|
.append(" 字节)的文件没有可用的未过期 SVIP/VIP 直链。");
|
||||||
|
}
|
||||||
|
message.append("H5 预览也没有返回可下载的文件地址。");
|
||||||
|
if (h5Error != null) {
|
||||||
|
message.append(" 预览: ").append(sanitize(h5Error.getMessage()));
|
||||||
|
}
|
||||||
|
if (directError != null) {
|
||||||
|
message.append(" 账号直链: ").append(sanitize(directError.getMessage()));
|
||||||
|
}
|
||||||
|
if (uc) {
|
||||||
|
message.append(" 请配置未过期的 UC SVIP/VIP Cookie:auths.uc.cookie。");
|
||||||
|
} else {
|
||||||
|
message.append(" 请配置未过期的夸克 SVIP/VIP Cookie:auths.qk.cookie。普通或已过期账号不会当作会员。");
|
||||||
|
}
|
||||||
|
return message.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
static String sanitize(String message) {
|
||||||
|
if (message == null || message.isBlank()) {
|
||||||
|
return "无详情";
|
||||||
|
}
|
||||||
|
String text = message.replaceAll("(?i)(cookie|__pus|__puus|__kp|__kps|__uid)=[^\\s;&,]+", "$1=***");
|
||||||
|
String lower = text.toLowerCase(Locale.ROOT);
|
||||||
|
if (lower.contains("<html") || lower.contains("<!doctype") || lower.contains("<head")) {
|
||||||
|
return "上游返回了 HTML 页面";
|
||||||
|
}
|
||||||
|
if (text.length() > 180) {
|
||||||
|
return text.substring(0, 180);
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String joinReasons(Throwable first, Throwable second) {
|
||||||
|
String a = first == null ? "" : sanitize(first.getMessage());
|
||||||
|
String b = second == null ? "" : sanitize(second.getMessage());
|
||||||
|
if (a.isBlank()) {
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
if (b.isBlank() || b.equals(a)) {
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
return a + ";" + b;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isUc(String pan) {
|
||||||
|
return pan != null && pan.equalsIgnoreCase("uc");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isBlank(String value) {
|
||||||
|
return value == null || value.isBlank();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
package cn.qaiu.parser.impl;
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.WebClientVertxInit;
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
|
import cn.qaiu.parser.TokenCache;
|
||||||
import cn.qaiu.util.CommonUtils;
|
import cn.qaiu.util.CommonUtils;
|
||||||
import cn.qaiu.util.CookieUtils;
|
import cn.qaiu.util.CookieUtils;
|
||||||
import cn.qaiu.util.DateTimeUtils;
|
import cn.qaiu.util.DateTimeUtils;
|
||||||
import cn.qaiu.util.FileSizeConverter;
|
import cn.qaiu.util.FileSizeConverter;
|
||||||
import cn.qaiu.util.HeaderUtils;
|
import cn.qaiu.util.HeaderUtils;
|
||||||
|
import cn.qaiu.util.QuarkAccountScope;
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
import io.vertx.core.MultiMap;
|
import io.vertx.core.MultiMap;
|
||||||
import io.vertx.core.Promise;
|
import io.vertx.core.Promise;
|
||||||
@@ -28,10 +31,7 @@ import java.util.Map;
|
|||||||
*/
|
*/
|
||||||
public class UcTool extends PanBase {
|
public class UcTool extends PanBase {
|
||||||
private static final String API_URL_PREFIX = "https://pc-api.uc.cn/1/clouddrive/";
|
private static final String API_URL_PREFIX = "https://pc-api.uc.cn/1/clouddrive/";
|
||||||
|
|
||||||
// 静态变量:缓存 __puus cookie 和过期时间
|
|
||||||
private static volatile String cachedPuus = null;
|
|
||||||
private static volatile long puusExpireTime = 0;
|
|
||||||
// __puus 有效期,默认 55 分钟(服务器实际 1 小时过期,提前 5 分钟刷新)
|
// __puus 有效期,默认 55 分钟(服务器实际 1 小时过期,提前 5 分钟刷新)
|
||||||
private static final long PUUS_TTL_MS = 55 * 60 * 1000L;
|
private static final long PUUS_TTL_MS = 55 * 60 * 1000L;
|
||||||
|
|
||||||
@@ -67,9 +67,17 @@ public class UcTool extends PanBase {
|
|||||||
|
|
||||||
// 保存 auths 引用,用于更新 cookie
|
// 保存 auths 引用,用于更新 cookie
|
||||||
private MultiMap auths;
|
private MultiMap auths;
|
||||||
|
private final String cacheKey;
|
||||||
|
/** 本次解析得到的是不带账号的公开文件地址。UC 大文件没有这条地址时不能当成免登录成功。 */
|
||||||
|
private boolean publicDirectLink;
|
||||||
|
|
||||||
public UcTool(ShareLinkInfo shareLinkInfo) {
|
public UcTool(ShareLinkInfo shareLinkInfo) {
|
||||||
super(shareLinkInfo);
|
super(shareLinkInfo);
|
||||||
|
String accountId = QuarkAccountScope.suffix(shareLinkInfo.getOtherParam());
|
||||||
|
if (accountId == null) {
|
||||||
|
accountId = "_default";
|
||||||
|
}
|
||||||
|
this.cacheKey = TokenCache.key("uc", accountId);
|
||||||
// 参考其它网盘实现,从认证配置中取 cookie 放到请求头
|
// 参考其它网盘实现,从认证配置中取 cookie 放到请求头
|
||||||
if (shareLinkInfo.getOtherParam() != null && shareLinkInfo.getOtherParam().containsKey("auths")) {
|
if (shareLinkInfo.getOtherParam() != null && shareLinkInfo.getOtherParam().containsKey("auths")) {
|
||||||
auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
||||||
@@ -77,18 +85,20 @@ public class UcTool extends PanBase {
|
|||||||
if (cookie != null && !cookie.isEmpty()) {
|
if (cookie != null && !cookie.isEmpty()) {
|
||||||
// 过滤出 UC 网盘所需的 cookie 字段
|
// 过滤出 UC 网盘所需的 cookie 字段
|
||||||
cookie = CookieUtils.filterUcQuarkCookie(cookie);
|
cookie = CookieUtils.filterUcQuarkCookie(cookie);
|
||||||
|
|
||||||
// 如果有缓存的 __puus 且未过期,使用缓存的值更新 cookie
|
// 按账号读取 __puus,避免把别的账号的会话写进当前请求
|
||||||
if (cachedPuus != null && System.currentTimeMillis() < puusExpireTime) {
|
String cachedPuus = TokenCache.getToken(cacheKey);
|
||||||
|
long puusExpire = TokenCache.getExpire(cacheKey);
|
||||||
|
if (cachedPuus != null && System.currentTimeMillis() < puusExpire) {
|
||||||
cookie = CookieUtils.updateCookieValue(cookie, "__puus", cachedPuus);
|
cookie = CookieUtils.updateCookieValue(cookie, "__puus", cachedPuus);
|
||||||
log.debug("UC: 使用缓存的 __puus (剩余有效期: {}s)", (puusExpireTime - System.currentTimeMillis()) / 1000);
|
log.debug("UC: 使用缓存的 __puus (剩余有效期: {}s)", (puusExpire - System.currentTimeMillis()) / 1000);
|
||||||
}
|
}
|
||||||
header.set(HttpHeaders.COOKIE, cookie);
|
header.set(HttpHeaders.COOKIE, cookie);
|
||||||
// 同步更新 auths
|
// 同步更新 auths
|
||||||
auths.set("cookie", cookie);
|
auths.set("cookie", cookie);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果 __puus 已过期或不存在,触发异步刷新
|
// 如果 __puus 已过期或不存在,触发异步刷新
|
||||||
if (needRefreshPuus()) {
|
if (needRefreshPuus()) {
|
||||||
log.debug("UC: __puus 需要刷新,触发异步刷新");
|
log.debug("UC: __puus 需要刷新,触发异步刷新");
|
||||||
@@ -110,7 +120,7 @@ public class UcTool extends PanBase {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// 缓存过期或不存在时需要刷新
|
// 缓存过期或不存在时需要刷新
|
||||||
return cachedPuus == null || System.currentTimeMillis() >= puusExpireTime;
|
return TokenCache.getToken(cacheKey) == null || System.currentTimeMillis() >= TokenCache.getExpire(cacheKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -164,11 +174,10 @@ public class UcTool extends PanBase {
|
|||||||
auths.set("cookie", updatedCookie);
|
auths.set("cookie", updatedCookie);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新静态缓存
|
TokenCache.putToken(cacheKey, newPuus);
|
||||||
cachedPuus = newPuus;
|
TokenCache.putExpire(cacheKey, System.currentTimeMillis() + PUUS_TTL_MS);
|
||||||
puusExpireTime = System.currentTimeMillis() + PUUS_TTL_MS;
|
|
||||||
|
log.info("UC: __puus cookie 刷新成功,有效期至: {}ms", TokenCache.getExpire(cacheKey));
|
||||||
log.info("UC: __puus cookie 刷新成功,有效期至: {}ms", puusExpireTime);
|
|
||||||
refreshPromise.complete(true);
|
refreshPromise.complete(true);
|
||||||
} else {
|
} else {
|
||||||
log.debug("UC: 响应中未包含 __puus,可能 cookie 仍然有效");
|
log.debug("UC: 响应中未包含 __puus,可能 cookie 仍然有效");
|
||||||
@@ -242,40 +251,16 @@ public class UcTool extends PanBase {
|
|||||||
log.warn("UC 提取文件信息失败,继续解析: {}", e.getMessage());
|
log.warn("UC 提取文件信息失败,继续解析: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 第三次请求获取下载链接
|
String fid = info.getString("fid");
|
||||||
var bodyJson = JsonObject.of()
|
String shareFidToken = info.getString("share_fid_token");
|
||||||
.put("fids", JsonArray.of(info.getString("fid")))
|
Future<String> download;
|
||||||
.put("pwd_id", dataKey)
|
if (QuarkFamilyDownloadPolicy.knownLarge(QuarkFamilyDownloadPolicy.sizeOf(info))) {
|
||||||
.put("stoken", stoken)
|
download = resolveUcLarge(fid, dataKey, stoken, shareFidToken, info.getString("file_name"));
|
||||||
.put("fids_token", JsonArray.of(info.getString("share_fid_token")));
|
} else {
|
||||||
client.postAbs(THIRD_REQUEST_URL)
|
download = requestUcDownload(fid, dataKey, stoken, shareFidToken);
|
||||||
.putHeaders(header)
|
}
|
||||||
.sendJsonObject(bodyJson)
|
download.onSuccess(this::finishUcParse)
|
||||||
.onSuccess(res3 -> {
|
.onFailure(t -> fail(t.getMessage() == null ? "解析失败" : t.getMessage()));
|
||||||
log.debug("第三阶段 {}", res3.body());
|
|
||||||
var resJson3 = res3.bodyAsJsonObject();
|
|
||||||
if (resJson3.getInteger("code") != 0) {
|
|
||||||
fail(FIRST_REQUEST_URL + " 返回异常: " + resJson2);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
JsonArray dataList = resJson3.getJsonArray("data");
|
|
||||||
if (dataList == null || dataList.isEmpty()) {
|
|
||||||
fail("UC API 返回的下载链接列表为空");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
String downloadUrl = dataList.getJsonObject(0).getString("download_url");
|
|
||||||
// UC网盘需要配合aria2下载,保存下载请求头
|
|
||||||
Map<String, String> downloadHeaders = new HashMap<>();
|
|
||||||
// 将header转换为Map 只需要包含cookie,user-agent,referer
|
|
||||||
downloadHeaders.put(HttpHeaders.COOKIE.toString(), header.get(HttpHeaders.COOKIE));
|
|
||||||
downloadHeaders.put(HttpHeaders.USER_AGENT.toString(), header.get(HttpHeaders.USER_AGENT));
|
|
||||||
downloadHeaders.put(HttpHeaders.REFERER.toString(), "https://fast.uc.cn/");
|
|
||||||
completeWithMeta(downloadUrl, downloadHeaders);
|
|
||||||
} catch (Exception e) {
|
|
||||||
fail("解析 UC 下载链接失败: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}).onFailure(handleFail(THIRD_REQUEST_URL));
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
fail("解析 UC 文件信息失败: " + e.getMessage());
|
fail("解析 UC 文件信息失败: " + e.getMessage());
|
||||||
}
|
}
|
||||||
@@ -286,6 +271,108 @@ public class UcTool extends PanBase {
|
|||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 大于 10MiB 才检查会员。有效 SVIP/VIP 仍走原来的账号 {@code /file/download};
|
||||||
|
* 否则只接受探测通过的 H5 文件地址。没有该地址时明确失败,不把 UC 说成免登录。
|
||||||
|
*/
|
||||||
|
private Future<String> resolveUcLarge(String fid, String pwdId, String stoken, String shareFidToken, String fileName) {
|
||||||
|
if (fid == null || fid.isEmpty()) {
|
||||||
|
return Future.failedFuture(QuarkFamilyDownloadPolicy.largeFileError("uc", null,
|
||||||
|
new IllegalStateException("缺少 fid")));
|
||||||
|
}
|
||||||
|
return QuarkFamilyDownloadPolicy.fetchMembership(client, header, true)
|
||||||
|
.compose(member -> {
|
||||||
|
if (!member.validPaid) {
|
||||||
|
return ucH5(pwdId, stoken, fid, shareFidToken, fileName)
|
||||||
|
.recover(h5Error -> Future.failedFuture(
|
||||||
|
QuarkFamilyDownloadPolicy.largeFileError("uc", null, h5Error)));
|
||||||
|
}
|
||||||
|
return requestUcDownload(fid, pwdId, stoken, shareFidToken)
|
||||||
|
.recover(directError -> ucH5(pwdId, stoken, fid, shareFidToken, fileName)
|
||||||
|
.recover(h5Error -> Future.failedFuture(
|
||||||
|
QuarkFamilyDownloadPolicy.largeFileError("uc", directError, h5Error))));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Future<String> ucH5(String pwdId, String stoken, String fid, String shareFidToken, String fileName) {
|
||||||
|
return QuarkFamilyDownloadPolicy.resolveH5Download(clientNoRedirects, WebClientVertxInit.get(),
|
||||||
|
"uc", pwdId, stoken, fid, shareFidToken, fileName)
|
||||||
|
.map(url -> {
|
||||||
|
publicDirectLink = true;
|
||||||
|
shareLinkInfo.getOtherParam().put("publicDirectLink", true);
|
||||||
|
shareLinkInfo.getOtherParam().put("previewUrl", QuarkFamilyDownloadPolicy.bareFileUrl(url));
|
||||||
|
return url;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Future<String> requestUcDownload(String fid, String pwdId, String stoken, String shareFidToken) {
|
||||||
|
Promise<String> downloadPromise = Promise.promise();
|
||||||
|
JsonObject bodyJson = JsonObject.of()
|
||||||
|
.put("fids", JsonArray.of(fid))
|
||||||
|
.put("pwd_id", pwdId)
|
||||||
|
.put("stoken", stoken);
|
||||||
|
if (shareFidToken != null && !shareFidToken.isEmpty()) {
|
||||||
|
bodyJson.put("fids_token", JsonArray.of(shareFidToken));
|
||||||
|
}
|
||||||
|
client.postAbs(THIRD_REQUEST_URL)
|
||||||
|
.putHeaders(header)
|
||||||
|
.sendJsonObject(bodyJson)
|
||||||
|
.onSuccess(res3 -> {
|
||||||
|
log.debug("UC 下载接口 {}", res3.body());
|
||||||
|
JsonObject resJson3 = res3.bodyAsJsonObject();
|
||||||
|
if (resJson3.getInteger("code") == null || resJson3.getInteger("code") != 0) {
|
||||||
|
downloadPromise.fail(THIRD_REQUEST_URL + " 返回异常: " + resJson3);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
JsonArray dataList = resJson3.getJsonArray("data");
|
||||||
|
if (dataList == null || dataList.isEmpty()) {
|
||||||
|
downloadPromise.fail("UC API 返回的下载链接列表为空");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String downloadUrl = dataList.getJsonObject(0).getString("download_url");
|
||||||
|
if (downloadUrl == null || downloadUrl.isEmpty()) {
|
||||||
|
downloadPromise.fail("未找到下载链接");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
downloadPromise.complete(downloadUrl);
|
||||||
|
} catch (Exception e) {
|
||||||
|
downloadPromise.fail("解析 UC 下载链接失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.onFailure(t -> downloadPromise.fail("请求下载链接失败: " + t.getMessage()));
|
||||||
|
return downloadPromise.future();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishUcParse(String downloadUrl) {
|
||||||
|
String presented = presentUcIfPublic(downloadUrl);
|
||||||
|
if (publicDirectLink) {
|
||||||
|
completeWithMeta(presented, Map.of());
|
||||||
|
shareLinkInfo.getOtherParam().put("needDownloader", false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
completeWithMeta(presented, buildDownloadHeaders(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String presentUcIfPublic(String downloadUrl) {
|
||||||
|
String presented = QuarkFamilyDownloadPolicy.presentPublicDownload(downloadUrl, "uc", currentUcFileName());
|
||||||
|
if (!presented.equals(downloadUrl) || QuarkFamilyDownloadPolicy.isPublicFileUrl(presented, "uc")) {
|
||||||
|
publicDirectLink = true;
|
||||||
|
shareLinkInfo.getOtherParam().put("publicDirectLink", true);
|
||||||
|
shareLinkInfo.getOtherParam().put("previewUrl", QuarkFamilyDownloadPolicy.bareFileUrl(presented));
|
||||||
|
}
|
||||||
|
return presented;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String currentUcFileName() {
|
||||||
|
Object info = shareLinkInfo.getOtherParam().get("fileInfo");
|
||||||
|
if (info instanceof FileInfo file && file.getFileName() != null && !file.getFileName().isBlank()) {
|
||||||
|
return file.getFileName();
|
||||||
|
}
|
||||||
|
Object name = shareLinkInfo.getOtherParam().get("fileName");
|
||||||
|
return name == null ? "" : name.toString();
|
||||||
|
}
|
||||||
|
|
||||||
// 目录解析
|
// 目录解析
|
||||||
@Override
|
@Override
|
||||||
public Future<List<FileInfo>> parseFileList() {
|
public Future<List<FileInfo>> parseFileList() {
|
||||||
@@ -466,29 +553,41 @@ public class UcTool extends PanBase {
|
|||||||
if (shareFidToken != null) {
|
if (shareFidToken != null) {
|
||||||
extParams.put("share_fid_token", shareFidToken);
|
extParams.put("share_fid_token", shareFidToken);
|
||||||
}
|
}
|
||||||
|
extParams.put("size", fileSize);
|
||||||
|
extParams.put("needDownloader", true);
|
||||||
|
Map<String, String> dlHeaders = new HashMap<>();
|
||||||
|
String listCookie = header.get(HttpHeaders.COOKIE);
|
||||||
|
if (listCookie != null && !listCookie.isEmpty()) {
|
||||||
|
dlHeaders.put(HttpHeaders.COOKIE.toString(), listCookie);
|
||||||
|
}
|
||||||
|
dlHeaders.put(HttpHeaders.USER_AGENT.toString(), header.get(HttpHeaders.USER_AGENT));
|
||||||
|
dlHeaders.put(HttpHeaders.REFERER.toString(), "https://fast.uc.cn/");
|
||||||
|
extParams.put("downloadHeaders", dlHeaders);
|
||||||
fileInfo.setExtParameters(extParams);
|
fileInfo.setExtParameters(extParams);
|
||||||
// 设置解析URL(用于下载)
|
// 设置解析URL(用于下载)
|
||||||
JsonObject paramJson = new JsonObject(extParams);
|
JsonObject paramJson = new JsonObject(extParams);
|
||||||
|
paramJson.put("fileName", fileName);
|
||||||
String param = CommonUtils.urlBase64Encode(paramJson.encode());
|
String param = CommonUtils.urlBase64Encode(paramJson.encode());
|
||||||
fileInfo.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
|
// 透传 auth,避免下载/转存时变成 guest
|
||||||
getDomainName(), shareLinkInfo.getType(), param));
|
fileInfo.setParserUrl(appendAuthQuery(String.format("%s/v2/redirectUrl/%s/%s",
|
||||||
|
getDomainName(), shareLinkInfo.getType(), param)));
|
||||||
} else {
|
} else {
|
||||||
// 文件夹
|
// 文件夹
|
||||||
fileInfo.setFileType("folder");
|
fileInfo.setFileType("folder");
|
||||||
fileInfo.setSize(0L);
|
fileInfo.setSize(0L);
|
||||||
fileInfo.setSizeStr("0B");
|
fileInfo.setSizeStr("0B");
|
||||||
// 设置目录解析URL(用于递归解析子目录)
|
// 递归子目录须透传 auth,否则会丢失认证
|
||||||
// 对 URL 参数进行编码,确保特殊字符正确传递
|
|
||||||
try {
|
try {
|
||||||
String encodedUrl = URLEncoder.encode(shareLinkInfo.getShareUrl(), StandardCharsets.UTF_8.toString());
|
String encodedUrl = URLEncoder.encode(shareLinkInfo.getShareUrl(), StandardCharsets.UTF_8.toString());
|
||||||
String encodedDirId = URLEncoder.encode(fid, StandardCharsets.UTF_8.toString());
|
String encodedDirId = URLEncoder.encode(fid, StandardCharsets.UTF_8.toString());
|
||||||
String encodedStoken = URLEncoder.encode(stoken, StandardCharsets.UTF_8.toString());
|
String encodedStoken = URLEncoder.encode(stoken, StandardCharsets.UTF_8.toString());
|
||||||
fileInfo.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&stoken=%s",
|
fileInfo.setParserUrl(appendAuthQuery(String.format(
|
||||||
getDomainName(), encodedUrl, encodedDirId, encodedStoken));
|
"%s/v2/getFileList?url=%s&dirId=%s&stoken=%s",
|
||||||
|
getDomainName(), encodedUrl, encodedDirId, encodedStoken)));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// 如果编码失败,使用原始值
|
fileInfo.setParserUrl(appendAuthQuery(String.format(
|
||||||
fileInfo.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&stoken=%s",
|
"%s/v2/getFileList?url=%s&dirId=%s&stoken=%s",
|
||||||
getDomainName(), shareLinkInfo.getShareUrl(), fid, stoken));
|
getDomainName(), shareLinkInfo.getShareUrl(), fid, stoken)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -510,6 +609,9 @@ public class UcTool extends PanBase {
|
|||||||
promise.fail("缺少必要的参数");
|
promise.fail("缺少必要的参数");
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 会话无 cookie 时,回退使用入口参数中已带的 cookie
|
||||||
|
ensureCookieFromParam(paramJson);
|
||||||
|
|
||||||
String fid = paramJson.getString("fid");
|
String fid = paramJson.getString("fid");
|
||||||
String pwdId = paramJson.getString("pwd_id");
|
String pwdId = paramJson.getString("pwd_id");
|
||||||
@@ -522,48 +624,78 @@ public class UcTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
log.debug("UC parseById: fid={}, pwd_id={}, stoken={}", fid, pwdId, stoken);
|
log.debug("UC parseById: fid={}, pwd_id={}, stoken={}", fid, pwdId, stoken);
|
||||||
|
|
||||||
// 调用第三次请求获取下载链接
|
String fileName = paramJson.getString("fileName", "");
|
||||||
JsonObject bodyJson = JsonObject.of()
|
Future<String> download;
|
||||||
.put("fids", JsonArray.of(fid))
|
if (QuarkFamilyDownloadPolicy.knownLarge(QuarkFamilyDownloadPolicy.sizeOf(paramJson))) {
|
||||||
.put("pwd_id", pwdId)
|
download = resolveUcLarge(fid, pwdId, stoken, shareFidToken, fileName);
|
||||||
.put("stoken", stoken);
|
} else {
|
||||||
|
download = requestUcDownload(fid, pwdId, stoken, shareFidToken);
|
||||||
if (shareFidToken != null && !shareFidToken.isEmpty()) {
|
|
||||||
bodyJson.put("fids_token", JsonArray.of(shareFidToken));
|
|
||||||
}
|
}
|
||||||
|
download.onSuccess(downloadUrl -> {
|
||||||
client.postAbs(THIRD_REQUEST_URL)
|
shareLinkInfo.getOtherParam().put("fileName", fileName);
|
||||||
.putHeaders(header)
|
String presented = presentUcIfPublic(downloadUrl);
|
||||||
.sendJsonObject(bodyJson)
|
if (publicDirectLink) {
|
||||||
.onSuccess(res -> {
|
shareLinkInfo.getOtherParam().put("downloadHeaders", new HashMap<>());
|
||||||
log.debug("UC parseById 响应: {}", res.body());
|
shareLinkInfo.getOtherParam().put("needDownloader", false);
|
||||||
JsonObject resJson = res.bodyAsJsonObject();
|
} else {
|
||||||
if (resJson.getInteger("code") != 0) {
|
shareLinkInfo.getOtherParam().put("downloadHeaders", buildDownloadHeaders(paramJson));
|
||||||
promise.fail(THIRD_REQUEST_URL + " 返回异常: " + resJson);
|
shareLinkInfo.getOtherParam().put("needDownloader", true);
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
JsonArray dataList = resJson.getJsonArray("data");
|
|
||||||
if (dataList == null || dataList.isEmpty()) {
|
|
||||||
promise.fail("UC API 返回的下载链接列表为空");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
String downloadUrl = dataList.getJsonObject(0).getString("download_url");
|
|
||||||
if (downloadUrl == null || downloadUrl.isEmpty()) {
|
|
||||||
promise.fail("未找到下载链接");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
promise.complete(downloadUrl);
|
|
||||||
} catch (Exception e) {
|
|
||||||
promise.fail("解析 UC 下载链接失败: " + e.getMessage());
|
|
||||||
}
|
}
|
||||||
|
promise.complete(presented);
|
||||||
})
|
})
|
||||||
.onFailure(t -> promise.fail("请求下载链接失败: " + t.getMessage()));
|
.onFailure(t -> promise.fail(t.getMessage() == null ? "请求下载链接失败" : t.getMessage()));
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会话无 cookie 时,从入口参数 downloadHeaders 回填到请求头。
|
||||||
|
*/
|
||||||
|
private void ensureCookieFromParam(JsonObject paramJson) {
|
||||||
|
String cookie = header.get(HttpHeaders.COOKIE);
|
||||||
|
if (cookie != null && !cookie.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String paramCookie = extractCookieFromParam(paramJson);
|
||||||
|
if (paramCookie != null && !paramCookie.isEmpty()) {
|
||||||
|
header.set(HttpHeaders.COOKIE, CookieUtils.filterUcQuarkCookie(paramCookie));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String extractCookieFromParam(JsonObject paramJson) {
|
||||||
|
if (paramJson == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
JsonObject paramHeaders = paramJson.getJsonObject("downloadHeaders");
|
||||||
|
if (paramHeaders == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String cookie = paramHeaders.getString("cookie");
|
||||||
|
return cookie != null ? cookie : paramHeaders.getString("Cookie");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建下载请求头:会话 cookie 优先,缺失时回退入口参数中的 downloadHeaders。
|
||||||
|
*/
|
||||||
|
private Map<String, String> buildDownloadHeaders(JsonObject paramJson) {
|
||||||
|
Map<String, String> downloadHeaders = new HashMap<>();
|
||||||
|
String cookie = header.get(HttpHeaders.COOKIE);
|
||||||
|
if (cookie == null || cookie.isEmpty()) {
|
||||||
|
cookie = extractCookieFromParam(paramJson);
|
||||||
|
}
|
||||||
|
if (cookie != null && !cookie.isEmpty()) {
|
||||||
|
downloadHeaders.put(HttpHeaders.COOKIE.toString(), cookie);
|
||||||
|
}
|
||||||
|
String ua = header.get(HttpHeaders.USER_AGENT);
|
||||||
|
if (ua == null || ua.isEmpty()) {
|
||||||
|
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
|
||||||
|
}
|
||||||
|
downloadHeaders.put(HttpHeaders.USER_AGENT.toString(), ua);
|
||||||
|
downloadHeaders.put(HttpHeaders.REFERER.toString(), "https://fast.uc.cn/");
|
||||||
|
return downloadHeaders;
|
||||||
|
}
|
||||||
|
|
||||||
// public static void main(String[] args) {
|
// public static void main(String[] args) {
|
||||||
// // https://drive.uc.cn/s/12450d1694844?public=1
|
// // https://drive.uc.cn/s/12450d1694844?public=1
|
||||||
// new UcTool(ShareLinkInfo.newBuilder().shareKey("12450d1694844").build()).parse().onSuccess(
|
// new UcTool(ShareLinkInfo.newBuilder().shareKey("12450d1694844").build()).parse().onSuccess(
|
||||||
|
|||||||
@@ -67,11 +67,7 @@ public class WsTool extends PanBase {
|
|||||||
String filepid = asJson(res2).getJsonObject("data").getString("ufileid"); // 文件夹pid
|
String filepid = asJson(res2).getJsonObject("data").getString("ufileid"); // 文件夹pid
|
||||||
String filebid = asJson(res2).getJsonObject("data").getString("boxid"); // 文件夹bid
|
String filebid = asJson(res2).getJsonObject("data").getString("boxid"); // 文件夹bid
|
||||||
|
|
||||||
// 调试输出文件夹信息
|
log.debug("文件夹期限: {}, 大小: {}, pid: {}, bid: {}", filetime, filesize, filepid, filebid);
|
||||||
System.out.println("文件夹期限: " + filetime);
|
|
||||||
System.out.println("文件夹大小: " + filesize);
|
|
||||||
System.out.println("文件夹pid: " + filepid);
|
|
||||||
System.out.println("文件夹bid: " + filebid);
|
|
||||||
|
|
||||||
// 获取文件信息
|
// 获取文件信息
|
||||||
httpClient.postAbs(SHARE_URL_API + "ufile/list").putHeaders(headers)
|
httpClient.postAbs(SHARE_URL_API + "ufile/list").putHeaders(headers)
|
||||||
@@ -97,9 +93,7 @@ public class WsTool extends PanBase {
|
|||||||
String filefid = asJson(res3).getJsonObject("data")
|
String filefid = asJson(res3).getJsonObject("data")
|
||||||
.getJsonArray("fileList").getJsonObject(0).getString("fid"); // 文件fid
|
.getJsonArray("fileList").getJsonObject(0).getString("fid"); // 文件fid
|
||||||
|
|
||||||
// 调试输出文件信息
|
log.debug("文件名称: {}, fid: {}", filename, filefid);
|
||||||
System.out.println("文件名称: " + filename);
|
|
||||||
System.out.println("文件fid: " + filefid);
|
|
||||||
|
|
||||||
// 检查文件是否失效
|
// 检查文件是否失效
|
||||||
httpClient.postAbs(SHARE_URL_API + "dl/sign").putHeaders(headers)
|
httpClient.postAbs(SHARE_URL_API + "dl/sign").putHeaders(headers)
|
||||||
@@ -114,8 +108,7 @@ public class WsTool extends PanBase {
|
|||||||
// 获取直链
|
// 获取直链
|
||||||
String fileurl = asJson(res4).getJsonObject("data").getString("url");
|
String fileurl = asJson(res4).getJsonObject("data").getString("url");
|
||||||
|
|
||||||
// 调试输出文件直链
|
log.debug("文件直链: {}", fileurl);
|
||||||
System.out.println("文件直链: " + fileurl);
|
|
||||||
|
|
||||||
if (!fileurl.equals("")) {
|
if (!fileurl.equals("")) {
|
||||||
promise.complete(URLDecoder.decode(fileurl, StandardCharsets.UTF_8));
|
promise.complete(URLDecoder.decode(fileurl, StandardCharsets.UTF_8));
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user