mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-11-25 14:57:00 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
451bd30798 | ||
|
|
ef03956944 | ||
|
|
542d246aab | ||
|
|
feff1b88c1 | ||
|
|
a7d41b0107 | ||
|
|
24c22fad7f | ||
|
|
a86b26d668 |
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.11。
|
||||
placeholder: "0.4.11"
|
||||
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.11。不确定就写获取方式。
|
||||
placeholder: "0.4.11"
|
||||
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,8 @@
|
||||
## 更新内容
|
||||
|
||||
- 城通网盘:免密分享,以及带访问密码的单文件和目录,都先走匿名 ALTCHA。已用项目解析器实测带密码 PDF(4005749 字节,文件头 `%PDF-`、文件尾 `%%EOF`)和目录内 zip(158842 字节,文件头 `PK`,可解压)。官方 `/v4` 只在匿名结果仍是 Cloudflare Turnstile、且自己配置了登录令牌时作为可选回退。登录态没有实测。
|
||||
- 永硕 E 盘:适配新版密码入口页。`ys168.com` 会跟随重定向到对应的 `ysepan.com` 后再验证密码。已实测 `sohehe4.ysepan.com`(密码 `1234`)列出目录,并通过 `parseById` 下载 134041 字节的 MRPG 文件和 128 字节的文本文件。
|
||||
|
||||
## 限制
|
||||
|
||||
这次只修复并实测了上述城通和永硕样例,不表示所有分享都可用。服务端不能解开 Cloudflare Turnstile。没有配置城通登录令牌时,如果匿名 ALTCHA 之后仍然返回 Turnstile,带密码分享会失败。永硕 `ysupan.com` 旧接口,以及部分直链端口,这次没有改。
|
||||
@@ -302,5 +302,6 @@ jobs:
|
||||
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
|
||||
@@ -19,10 +19,10 @@ QQ交流群:1017480890
|
||||
|
||||
|
||||
> 本平台所有音乐解析工具不再维护,请移步[Sonder播放器](https://sodecode.qaiu.top)
|
||||
> 需要百度,迅雷,UC,夸克的完整支持请使用[专业版](https://189.qaiu.top)
|
||||
> 需要百度、迅雷的完整支持请使用[专业版](https://189.qaiu.top)。夸克网盘、UC网盘已包含在开源版。
|
||||
|
||||
## 介绍
|
||||
> netdisk-fast-download网盘直链解析可以把云盘分享链接转为直链,可广泛应用于各类下载站,资源站,个人博客,图床,APP下载更新,视频点播等领域。支持市面各大主流云盘的文件分享以及文件夹分享链接,已支持蓝奏云/蓝奏云优享/移动云云空间/小飞机盘/亿方云/123云盘/永硕E盘/Cloudreve等,支持加密分享,以及部分网盘文件夹分享。
|
||||
> netdisk-fast-download网盘直链解析可以把云盘分享链接转为直链,可广泛应用于各类下载站,资源站,个人博客,图床,APP下载更新,视频点播等领域。支持市面各大主流云盘的文件分享以及文件夹分享链接,已支持蓝奏云/蓝奏云优享/移动云云空间/小飞机盘/亿方云/123云盘/夸克网盘/UC网盘/永硕E盘/Cloudreve等,支持加密分享,以及部分网盘文件夹分享。
|
||||
|
||||
[官方文档](https://nfd-parser.github.io/)
|
||||
[API接入](https://nfdparser.apifox.cn/)
|
||||
@@ -64,7 +64,7 @@ wget -O v01 "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%
|
||||
|
||||
**注意⚠️小飞机解析有IP限制,多数云服务商的大陆IP会被拦截(可以自行配置代理),和本程序无关**
|
||||
**注意⚠️收到很多用户反馈,小飞机近期封号频繁,请尽可能选择其他网盘分享**
|
||||
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提issues,请先检查分享是否有效。**
|
||||
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提 issues,请先检查分享是否有效。**反馈时使用 [问题模板](https://github.com/qaiu/netdisk-fast-download/issues/new/choose),只提供可公开的测试分享,不要粘贴 Cookie、令牌或账号密码。
|
||||
|
||||
## 网盘支持情况:
|
||||
> 20230824 123云盘解析大文件(>100MB)失效,需要登录
|
||||
@@ -80,6 +80,8 @@ wget -O v01 "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%
|
||||
- [123云盘-ye](https://www.123pan.com/) ⚠️仅建议本地部署使用。公共云解析没有共享 123 账号;下载返回 5112 / 请登录后下载时,在本机配置 `auths.ye.authorization`(Windows 可直接用 run.bat)
|
||||
- ~[115网盘(失效)-p115](https://115.com/)~
|
||||
- [文叔叔-ws](https://www.wenshushu.cn/)
|
||||
- [夸克网盘-qk](https://pan.quark.cn/)
|
||||
- [UC网盘-uc](https://fast.uc.cn/)
|
||||
- [联想乐云-le](https://lecloud.lenovo.com/)
|
||||
- [QQ邮箱云盘-qqw](https://mail.qq.com/)
|
||||
- [QQ闪传-qqsc](https://nutty.qq.com/nutty/ssr/26797.html)
|
||||
@@ -104,8 +106,6 @@ wget -O v01 "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%
|
||||
- 百度网盘开放平台-bd
|
||||
- 迅雷云盘开放平台-xl
|
||||
- [光鸭云盘开放平台-gy](https://www.guangyapan.com)
|
||||
- [夸克云盘-qk](https://pan.quark.cn/)
|
||||
- [UC云盘-uc](https://fast.uc.cn/)
|
||||
- [移动云盘-p139](https://yun.139.com/)
|
||||
- [联通云盘-pwo](https://pan.wo.cn/)
|
||||
- [天翼云盘-p189](https://cloud.189.cn/)
|
||||
@@ -184,8 +184,8 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
|
||||
**网盘认证要求**:
|
||||
| 网盘 | 认证要求 | 说明 |
|
||||
|------|---------|------|
|
||||
| 夸克网盘(QK) | 小文件可免登录 | 小文件走访客直链。文件夹会先列目录再进入。超过访客大小限制(上游 23018,本次核对约 90MB 失败、约 12MB–27MB 成功)必须配置 `auths.qk.cookie` 或请求 `auth`。未配置 Cookie 时不会转存 |
|
||||
| UC网盘(UC) | **必须** | 不能免登录,必须配置 Cookie |
|
||||
| 夸克网盘(QK) | 不超过 10MiB 可走原解析 | 不大于 `10 * 1024 * 1024` 字节(含等于该值)保持原来的分享解析。更大的文件仅在会员接口确认未过期 SVIP/VIP 时使用该账号直链;否则使用探测通过的 H5 文件地址并附上真实文件名。普通或过期 Cookie 不算会员 |
|
||||
| UC网盘(UC) | **不能免登录** | 小文件仍要 Cookie。超过 10MiB 时同样只认未过期 SVIP/VIP 的账号直链;没有时才尝试 H5 文件地址。H5 没有可下载文件就返回明确错误,不会把 UC 当成免登录 |
|
||||
| 小飞机网盘(FJ) | 可选 | 大文件(>100MB)需要认证 |
|
||||
| 蓝奏优享(IZ) | 可选 | 大文件需要认证 |
|
||||
| 123网盘(YE) | 下载通常需要 | 分享列表经常可以不登录读取。下载接口常见 5112 / 请登录后下载 / 您需要注册登录或付费后下载,请在**本机**配置 `auths.ye.authorization`(与 `token` 等价)或账号密码。公共云解析没有共享 123 账号。约 10MB 小文件有时可以直链,大文件和风控必须用你自己的账号。短链:`ye:分享key@提取码`;`#` 片段会去掉;`yun.123pan.com`、`www.123pan.com`、`*.share.123pan.cn` 同一类 |
|
||||
@@ -383,13 +383,13 @@ json返回数据格式示例:
|
||||
| 文叔叔 | √ | √ | 10G | 5GB |
|
||||
| 永硕E盘 | √ | √(空间密码) | 视套餐 | 视套餐 |
|
||||
| WPS云文档 | √ | X | 5G(免费) | 10M(免费)/2G(会员) |
|
||||
| 夸克网盘 | 小文件 | √ | 10G | 访客有大小限制(23018) |
|
||||
| UC网盘 | x | √ | 10G | 不限大小 |
|
||||
| 夸克网盘 | ≤10MiB 原解析 | √ | 10G | 更大文件要有效 SVIP/VIP,或可用的 H5 文件地址 |
|
||||
| UC网盘 | x | √ | 10G | 不能免登录;大文件规则同夸克 |
|
||||
| 飞书云盘 | √ | X | 15G | 不限大小 |
|
||||
|
||||
免登录边界(阈值由网盘决定,不是本项目写死的):
|
||||
|
||||
- **夸克**:小文件可以不登录。本次核对约 12MB–27MB 的访客直链成功,约 90MB 返回 `23018`。分享根目录如果只是文件夹,解析会继续进入子目录。超过限制时配置 `auths.qk.cookie`。UC 不能免登录。百度大约 100MB 以内有直链,属于专业版,这次没有改解析器。
|
||||
- **夸克 / 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 的小文件有时能直链。
|
||||
|
||||
# 打包部署
|
||||
@@ -470,7 +470,7 @@ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtow
|
||||
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
|
||||
```shell
|
||||
cd ~
|
||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.9/netdisk-fast-download-linux-amd64.zip
|
||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.11/netdisk-fast-download-linux-amd64.zip
|
||||
unzip netdisk-fast-download.zip
|
||||
cd netdisk-fast-download
|
||||
bash service-install.sh
|
||||
@@ -527,7 +527,7 @@ nfd-proxy搭建http代理服务器
|
||||
参考https://github.com/nfd-parser/nfd-proxy
|
||||
|
||||
### 认证信息配置说明
|
||||
夸克小文件可以不登录;大文件要本机 Cookie。123 的下载在公共解析站上基本都要你自己的 Authorization,云端没有共用账号。
|
||||
夸克不超过 10MiB 可以不登录;更大的文件要本机未过期的 SVIP/VIP Cookie,或上游确实返回了可下载的 H5 文件地址。UC 不能免登录。123 的下载在公共解析站上基本都要你自己的 Authorization,云端没有共用账号。
|
||||
|
||||
修改配置文件:
|
||||
app-dev.yml
|
||||
@@ -535,14 +535,22 @@ app-dev.yml
|
||||
```yaml
|
||||
### 解析认证相关
|
||||
auths:
|
||||
# 夸克大文件:auths.qk.cookie
|
||||
# 夸克 / UC 大于 10MiB(10 * 1024 * 1024 字节)时才会查询会员接口。
|
||||
# 只有未过期的 SVIP/VIP 才使用该账号直链;不要把普通 Cookie 写成会员。
|
||||
# qk:
|
||||
# cookie: 浏览器里夸克网盘的 Cookie
|
||||
# uc:
|
||||
# cookie: 浏览器里 UC 网盘的 Cookie
|
||||
# 123:优先填 authorization。账号密码若触发验证码会失败,本项目不处理验证码。
|
||||
ye:
|
||||
username: 你的用户名
|
||||
password: 你的密码
|
||||
# authorization: 浏览器登录后的 authorToken / sso-token
|
||||
# 城通免密和带密码分享都先匿名解析。仅当仍被 Turnstile 拦住时才需要登录令牌。
|
||||
# 登录 https://pan.ctfile.com 后,从 Session Storage 复制 refresh_token。
|
||||
# ct:
|
||||
# refresh_token: 登录后的 refresh_token
|
||||
# token: 可选,当前 access token
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package cn.qaiu.entity;
|
||||
|
||||
import cn.qaiu.util.QuarkAccountScope;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -85,12 +87,19 @@ public class ShareLinkInfo {
|
||||
public String getCacheKey() {
|
||||
// 将type和shareKey组合成一个字符串作为缓存key
|
||||
String key = type + ":" + shareKey;
|
||||
if (type.equals("p115")) {
|
||||
if (type != null && type.equals("p115")) {
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,345 +1,112 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.PanBase;
|
||||
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 cn.qaiu.util.FileSizeConverter;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.WorkerExecutor;
|
||||
import io.vertx.core.json.JsonArray;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.client.HttpRequest;
|
||||
import io.vertx.uritemplate.UriTemplate;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* <a href="https://www.ctfile.com">诚通网盘</a>
|
||||
* 城通网盘。免密和带访问密码的分享都先走匿名网页接口和 ALTCHA v2。
|
||||
* 官方客户端 {@code /v4} 只在匿名结果仍是 Turnstile、且调用方自己配置了登录令牌时回退。
|
||||
*/
|
||||
public class CtTool extends PanBase {
|
||||
private static final String API_URL_PREFIX = "https://webapi.ctfile.com";
|
||||
|
||||
private static final String SHARE_FILE_URL_PREFIX = "https://ctfile.com/file/";
|
||||
private static final String AJAX_ACCEPT = "application/json, text/javascript, */*; q=0.01";
|
||||
private static final String BROWSER_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
|
||||
private static final int FILE_LIST_PAGE_SIZE = 200;
|
||||
private static final int MAX_FILE_LIST_PAGES = 50;
|
||||
private static final int DEFAULT_MAX_LIST_PAGES = 50;
|
||||
|
||||
// https://webapi.ctfile.com/getfile.php?path=f&f=64115194-17569800420720-06c697&
|
||||
// passcode=7609&r=0.6611183001986635&ref=&url=https%3A%2F%2Furl94.ctfile.com%2Ff%2F64115194-17569800420720-06c697%3Fp%3D7609
|
||||
private static final String API1 = API_URL_PREFIX + "/getfile.php?path={path}" +
|
||||
"&f={shareKey}&passcode={pwd}&r={rand}&ref=&url={url}";
|
||||
private static final Object WORKER_LOCK = new Object();
|
||||
private static volatile WorkerExecutor sharedWorker;
|
||||
private static volatile boolean workerShutdown;
|
||||
|
||||
// https://webapi.ctfile.com/get_down_url.php?uid=64115194&fid=17569800420720&
|
||||
// file_chk=af5c8757a49cbc69a557eb3da59b246c&start_time=1780471868&wait_seconds=0&rd=0.36...
|
||||
private static final String API2 = API_URL_PREFIX + "/get_down_url.php?" +
|
||||
"uid={uid}&fid={fid}&file_chk={file_chk}" +
|
||||
"&start_time={start_time}&wait_seconds={wait_seconds}&rd={rand}";
|
||||
|
||||
// https://webapi.ctfile.com/getdir.php?path=d&d=64115194-164803691-48508c&
|
||||
// folder_id=164803691&fk=decb36&passcode=7609&r=0.23...&ref=&url=https://url94.ctfile.com/d/...
|
||||
private static final String API_GETDIR = API_URL_PREFIX + "/getdir.php?path={path}" +
|
||||
"&d={shareKey}&folder_id={folder_id}&fk={fk}&passcode={pwd}&r={rand}&ref=&url={url}";
|
||||
|
||||
// DataTables参数,用于获取目录文件列表
|
||||
private static final String FILE_LIST_PARAMS_TEMPLATE = "&sEcho=1&iColumns=4&sColumns=%2C%2C%2C" +
|
||||
"&iDisplayStart={start}&iDisplayLength={length}" +
|
||||
"&mDataProp_0=0&sSearch_0=&bRegex_0=false&bSearchable_0=true&bSortable_0=false" +
|
||||
"&mDataProp_1=1&sSearch_1=&bRegex_1=false&bSearchable_1=true&bSortable_1=true" +
|
||||
"&mDataProp_2=2&sSearch_2=&bRegex_2=false&bSearchable_2=true&bSortable_2=true" +
|
||||
"&mDataProp_3=3&sSearch_3=&bRegex_3=false&bSearchable_3=true&bSortable_3=true" +
|
||||
"&sSearch=&bRegex=false" +
|
||||
"&iSortCol_0=3&sSortDir_0=desc&iSortingCols=1";
|
||||
|
||||
// 文件列表HTML解析正则
|
||||
private static final Pattern FILE_ID_PATTERN = Pattern.compile("value=[\"']f(\\d+)[\"']");
|
||||
private static final Pattern FOLDER_ID_PATTERN = Pattern.compile("value=[\"']d(\\d+)[\"']");
|
||||
private static final Pattern FILE_HREF_PATTERN = Pattern.compile("href=[\"']#/f/([^\"']+)[\"']");
|
||||
private static final Pattern FILE_NAME_PATTERN = Pattern.compile("<a\\b[^>]*>([^<]+)</a>", Pattern.CASE_INSENSITIVE);
|
||||
private static final Pattern FILE_ICON_PATTERN = Pattern.compile("alt=[\"']([^\"']+)[\"']");
|
||||
private static final Pattern SUBDIR_PATTERN = Pattern.compile("load_subdir\\s*\\((\\d+)\\s*,\\s*['\"]([^'\"]+)['\"]\\)");
|
||||
|
||||
/**
|
||||
* 子类重写此构造方法不需要添加额外逻辑
|
||||
* 如:
|
||||
* <blockquote><pre>
|
||||
* public XxTool(String key, String pwd) {
|
||||
* super(key, pwd);
|
||||
* }
|
||||
* </pre></blockquote>
|
||||
*
|
||||
* @param shareLinkInfo 分享链接信息
|
||||
*/
|
||||
public CtTool(ShareLinkInfo shareLinkInfo) {
|
||||
super(shareLinkInfo);
|
||||
}
|
||||
|
||||
public static void shutdownWorkerExecutor() {
|
||||
synchronized (WORKER_LOCK) {
|
||||
workerShutdown = true;
|
||||
if (sharedWorker != null) {
|
||||
sharedWorker.close();
|
||||
sharedWorker = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<String> parse() {
|
||||
final String shareKey = shareLinkInfo.getShareKey();
|
||||
if (shareKey == null || shareKey.indexOf('-') == -1) {
|
||||
fail("shareKey格式不正确找不到'-': {}", shareKey);
|
||||
String shareKey = shareLinkInfo.getShareKey();
|
||||
if (shareKey == null || shareKey.isBlank()) {
|
||||
fail("shareKey为空");
|
||||
return promise.future();
|
||||
}
|
||||
String[] split = shareKey.split("-");
|
||||
if (split.length < 2 || split[0].isBlank() || split[1].isBlank()) {
|
||||
fail("shareKey格式不正确: {}", shareKey);
|
||||
return promise.future();
|
||||
}
|
||||
String fallbackUid = split[0], fallbackFid = split[1];
|
||||
String path = extractPath(shareLinkInfo.getShareUrl());
|
||||
|
||||
HttpRequest<Buffer> bufferHttpRequest1 = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API1))
|
||||
.setTemplateParam("path", path)
|
||||
.setTemplateParam("shareKey", shareKey)
|
||||
.setTemplateParam("pwd", shareLinkInfo.getSharePassword())
|
||||
.setTemplateParam("rand", String.valueOf(Math.random()))
|
||||
.setTemplateParam("url", shareLinkInfo.getShareUrl()), shareLinkInfo.getShareUrl());
|
||||
|
||||
bufferHttpRequest1
|
||||
.send().onSuccess(res -> {
|
||||
try {
|
||||
var resJson = asJson(res);
|
||||
if (resJson == null || resJson.isEmpty()) {
|
||||
fail("解析失败, 上游返回空响应或非JSON响应");
|
||||
return;
|
||||
}
|
||||
Object fileValue = resJson.getValue("file");
|
||||
if (!(fileValue instanceof JsonObject)) {
|
||||
fail("解析失败, 文件信息为空或格式错误, 可能分享已失效: {}", resJson);
|
||||
return;
|
||||
}
|
||||
var fileJson = (JsonObject) fileValue;
|
||||
String uid = resolveDownloadUid(fileJson, fallbackUid);
|
||||
String fid = resolveDownloadFid(fileJson, fallbackFid);
|
||||
String fileChk = fileJson.getString("file_chk");
|
||||
String startTime = valueToString(fileJson.getValue("start_time"));
|
||||
String waitSeconds = valueToString(fileJson.getValue("wait_seconds"));
|
||||
if (uid.isBlank() || fid.isBlank() || fileChk == null || fileChk.isBlank()
|
||||
|| startTime.isBlank() || waitSeconds.isBlank()) {
|
||||
fail("解析失败, 下载参数不完整, 可能分享已失效或者分享密码不对: {}", fileJson);
|
||||
return;
|
||||
}
|
||||
|
||||
// 提取文件信息并存储
|
||||
FileInfo fileInfo = new FileInfo()
|
||||
.setFileName(fileJson.getString("file_name"))
|
||||
.setFileId(fid)
|
||||
.setSizeStr(fileJson.getString("file_size"))
|
||||
.setCreateTime(fileJson.getString("file_time"))
|
||||
.setCreateBy(fileJson.getString("username"))
|
||||
.setFileType("file")
|
||||
.setPanType(shareLinkInfo.getType());
|
||||
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
|
||||
|
||||
HttpRequest<Buffer> bufferHttpRequest2 = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API2))
|
||||
.setTemplateParam("uid", uid)
|
||||
.setTemplateParam("fid", fid)
|
||||
.setTemplateParam("file_chk", fileChk)
|
||||
.setTemplateParam("start_time", startTime)
|
||||
.setTemplateParam("wait_seconds", waitSeconds)
|
||||
.setTemplateParam("rand", String.valueOf(Math.random())), shareLinkInfo.getShareUrl());
|
||||
bufferHttpRequest2
|
||||
.send().onSuccess(res2 -> handleDownloadUrlResponse(res2))
|
||||
.onFailure(t -> fail("下载链接请求失败: {}", t.getMessage()));
|
||||
} catch (Exception e) {
|
||||
fail("解析失败: {}", e.getMessage());
|
||||
}
|
||||
}).onFailure(t -> fail("文件信息请求失败: {}", t.getMessage()));
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
private void handleDownloadUrlResponse(io.vertx.ext.web.client.HttpResponse<Buffer> res) {
|
||||
try {
|
||||
JsonObject resJson = asJson(res);
|
||||
if (resJson == null || resJson.isEmpty()) {
|
||||
fail("解析失败, 下载接口返回空响应或非JSON响应");
|
||||
return;
|
||||
}
|
||||
String downloadUrl = resJson.getString("downurl");
|
||||
if (downloadUrl == null || downloadUrl.isBlank()) {
|
||||
fail("解析失败, 可能分享已失效: json: {} 字段 {} 不存在", resJson, "downurl");
|
||||
return;
|
||||
}
|
||||
|
||||
// 存储下载元数据,包括必要的请求头
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
headers.put("User-Agent", BROWSER_UA);
|
||||
if (shareLinkInfo.getShareUrl() != null && !shareLinkInfo.getShareUrl().isBlank()) {
|
||||
headers.put("Referer", shareLinkInfo.getShareUrl());
|
||||
}
|
||||
|
||||
// 使用新的 completeWithMeta 方法
|
||||
completeWithMeta(downloadUrl, headers);
|
||||
} catch (Exception e) {
|
||||
fail("解析失败, 下载接口响应处理异常: {}", e.getMessage());
|
||||
worker().executeBlocking(() -> {
|
||||
ParsedDownload link = resolveDownload(shareKey);
|
||||
shareLinkInfo.getOtherParam().put("fileInfo", fileInfoFrom(link.file));
|
||||
if (link.fileDir != null && !link.fileDir.isBlank()) {
|
||||
shareLinkInfo.getOtherParam().put("ctFileDir", link.fileDir);
|
||||
}
|
||||
return link;
|
||||
}, false).onSuccess(link -> {
|
||||
if (link.headers == null || link.headers.isEmpty()) {
|
||||
complete(link.url);
|
||||
} else {
|
||||
completeWithMeta(link.url, link.headers);
|
||||
}
|
||||
}).onFailure(error -> fail("{}", rootMessage(error)));
|
||||
} catch (RuntimeException e) {
|
||||
fail("{}", e.getMessage());
|
||||
}
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<List<FileInfo>> parseFileList() {
|
||||
Promise<List<FileInfo>> listPromise = Promise.promise();
|
||||
|
||||
final String shareKey = shareLinkInfo.getShareKey();
|
||||
final String shareUrl = shareLinkInfo.getShareUrl();
|
||||
final String pwd = shareLinkInfo.getSharePassword();
|
||||
|
||||
// shareKey格式: uid-folder_id-hash (例如 64115194-164803691-48508c)
|
||||
if (shareKey == null) {
|
||||
listPromise.fail(baseMsg() + " shareKey为空");
|
||||
String shareKey = shareLinkInfo.getShareKey();
|
||||
if (shareKey == null || shareKey.isBlank()) {
|
||||
listPromise.fail(baseMsg() + " - 解析异常: shareKey为空");
|
||||
return listPromise.future();
|
||||
}
|
||||
String[] split = shareKey.split("-");
|
||||
if (split.length < 2) {
|
||||
listPromise.fail(baseMsg() + " shareKey格式不正确: " + 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());
|
||||
}
|
||||
String path = extractPath(shareUrl);
|
||||
Object dirId = shareLinkInfo.getOtherParam() == null ? null : shareLinkInfo.getOtherParam().get("dirId");
|
||||
DirectoryContext directoryContext = resolveDirectoryContext(shareUrl, dirId);
|
||||
|
||||
HttpRequest<Buffer> getDirRequest = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API_GETDIR))
|
||||
.setTemplateParam("path", path)
|
||||
.setTemplateParam("shareKey", shareKey)
|
||||
.setTemplateParam("folder_id", directoryContext.folderId)
|
||||
.setTemplateParam("fk", directoryContext.folderKey)
|
||||
.setTemplateParam("pwd", pwd != null ? pwd : "")
|
||||
.setTemplateParam("rand", String.valueOf(Math.random()))
|
||||
.setTemplateParam("url", shareUrl), shareUrl);
|
||||
|
||||
getDirRequest.send().onSuccess(res -> {
|
||||
try {
|
||||
var resJson = asJson(res);
|
||||
if (resJson == null || resJson.isEmpty()) {
|
||||
failListPromise(listPromise, baseMsg() + " 目录解析失败: 上游返回空响应或非JSON响应");
|
||||
return;
|
||||
}
|
||||
if (!resJson.containsKey("file")) {
|
||||
failListPromise(listPromise, baseMsg() + " 目录解析失败: " + resJson.encode());
|
||||
return;
|
||||
}
|
||||
Object dirInfoValue = resJson.getValue("file");
|
||||
if (!(dirInfoValue instanceof JsonObject)) {
|
||||
failListPromise(listPromise, baseMsg() + " 目录解析失败: file字段格式错误: " + resJson.encode());
|
||||
return;
|
||||
}
|
||||
JsonObject dirInfo = (JsonObject) dirInfoValue;
|
||||
Object fileListUrlValue = dirInfo.getValue("url");
|
||||
String fileListRelUrl = fileListUrlValue instanceof String ? ((String) fileListUrlValue).trim() : "";
|
||||
if (fileListRelUrl.isBlank()) {
|
||||
failListPromise(listPromise, baseMsg() + " " + buildDirectoryFailureMessage(resJson, dirInfo));
|
||||
return;
|
||||
}
|
||||
|
||||
fetchFileListPage(toCtApiUrl(fileListRelUrl), 0, 0, new ArrayList<>(), listPromise,
|
||||
shareLinkInfo.getType(), getDomainName(), shareUrl, pwd);
|
||||
} catch (Exception e) {
|
||||
failListPromise(listPromise, baseMsg() + " 目录解析失败: " + e.getMessage());
|
||||
}
|
||||
}).onFailure(t -> failListPromise(listPromise, t));
|
||||
|
||||
return listPromise.future();
|
||||
}
|
||||
|
||||
private void fetchFileListPage(String fileListBaseUrl, int start, int pageIndex, List<FileInfo> fileList,
|
||||
Promise<List<FileInfo>> listPromise, String panType, String domainName,
|
||||
String shareUrl, String pwd) {
|
||||
try {
|
||||
if (pageIndex >= MAX_FILE_LIST_PAGES) {
|
||||
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 分页超过最大限制 " + MAX_FILE_LIST_PAGES
|
||||
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
|
||||
return;
|
||||
}
|
||||
|
||||
String fileListUrl = appendQueryParams(fileListBaseUrl,
|
||||
buildFileListParams(start, FILE_LIST_PAGE_SIZE) + "&_=" + System.currentTimeMillis());
|
||||
withCtAjaxHeaders(clientSession.getAbs(fileListUrl), shareUrl)
|
||||
.send()
|
||||
.onSuccess(res -> handleFileListPageResponse(fileListBaseUrl, start, pageIndex, fileList,
|
||||
listPromise, panType, domainName, shareUrl, pwd, res))
|
||||
.onFailure(t -> failListPromise(listPromise, t));
|
||||
} catch (Exception e) {
|
||||
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: " + e.getMessage()
|
||||
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
|
||||
}
|
||||
}
|
||||
|
||||
private void handleFileListPageResponse(String fileListBaseUrl, int start, int pageIndex, List<FileInfo> fileList,
|
||||
Promise<List<FileInfo>> listPromise, String panType, String domainName,
|
||||
String shareUrl, String pwd, io.vertx.ext.web.client.HttpResponse<Buffer> res) {
|
||||
try {
|
||||
var listJson = asJson(res);
|
||||
if (listJson == null || listJson.isEmpty()) {
|
||||
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 上游返回空响应或非JSON响应"
|
||||
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
|
||||
return;
|
||||
}
|
||||
Object aaDataValue = listJson.getValue("aaData");
|
||||
if (!(aaDataValue instanceof JsonArray)) {
|
||||
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: aaData为空: " + listJson.encode());
|
||||
return;
|
||||
}
|
||||
JsonArray aaData = (JsonArray) aaDataValue;
|
||||
for (int i = 0; i < aaData.size(); i++) {
|
||||
try {
|
||||
Object rowValue = aaData.getValue(i);
|
||||
if (!(rowValue instanceof JsonArray)) {
|
||||
log.warn("城通文件列表行格式错误: {}", rowValue);
|
||||
continue;
|
||||
}
|
||||
FileInfo fileInfo = parseFileListRow((JsonArray) rowValue, panType,
|
||||
domainName, shareUrl, pwd);
|
||||
if (fileInfo != null) {
|
||||
fileList.add(fileInfo);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("解析文件行失败: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
int nextStart = start + aaData.size();
|
||||
int total = parseFileListTotal(listJson);
|
||||
if (isUnexpectedEmptyFileListPage(start, aaData.size(), total)) {
|
||||
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 上游返回空分页"
|
||||
+ " (start=" + start + ", total=" + total + ")");
|
||||
return;
|
||||
}
|
||||
if (shouldFetchNextFileListPage(start, aaData.size(), total)) {
|
||||
fetchFileListPage(fileListBaseUrl, nextStart, pageIndex + 1, fileList,
|
||||
listPromise, panType, domainName, shareUrl, pwd);
|
||||
} else {
|
||||
completeListPromise(listPromise, fileList);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: " + e.getMessage()
|
||||
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<String> parseById() {
|
||||
Object paramValue = shareLinkInfo.getOtherParam().get("paramJson");
|
||||
if (!(paramValue instanceof JsonObject)) {
|
||||
Promise<String> parsePromise = Promise.promise();
|
||||
parsePromise.fail(baseMsg() + " 缺少下载参数paramJson");
|
||||
return parsePromise.future();
|
||||
fail("缺少下载参数paramJson");
|
||||
return promise.future();
|
||||
}
|
||||
JsonObject paramJson = (JsonObject) paramValue;
|
||||
if (!applyFileParam(shareLinkInfo, paramJson)) {
|
||||
Promise<String> parsePromise = Promise.promise();
|
||||
parsePromise.fail(baseMsg() + " 下载参数id为空");
|
||||
return parsePromise.future();
|
||||
if (!applyFileParam(shareLinkInfo, (JsonObject) paramValue)) {
|
||||
fail("下载参数id为空");
|
||||
return promise.future();
|
||||
}
|
||||
return parse();
|
||||
}
|
||||
@@ -350,324 +117,298 @@ public class CtTool extends PanBase {
|
||||
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;
|
||||
}
|
||||
|
||||
static String resolveDownloadUid(JsonObject fileJson, String fallbackUid) {
|
||||
return firstNonBlank(valueToString(fileJson.getValue("userid")), fallbackUid);
|
||||
}
|
||||
|
||||
static String resolveDownloadFid(JsonObject fileJson, String fallbackFid) {
|
||||
return firstNonBlank(valueToString(fileJson.getValue("file_id")), fallbackFid);
|
||||
}
|
||||
|
||||
private HttpRequest<Buffer> withCtAjaxHeaders(HttpRequest<Buffer> request, String shareUrl) {
|
||||
request.putHeader("User-Agent", BROWSER_UA)
|
||||
.putHeader("Accept", AJAX_ACCEPT)
|
||||
.putHeader("X-Requested-With", "XMLHttpRequest");
|
||||
if (shareUrl != null && !shareUrl.isBlank()) {
|
||||
request.putHeader("Referer", shareUrl);
|
||||
private ParsedDownload resolveDownload(String shareKey) throws Exception {
|
||||
if (requiresV4()) {
|
||||
return downloadWithV4(shareKey);
|
||||
}
|
||||
String origin = extractOrigin(shareUrl);
|
||||
if (!origin.isBlank()) {
|
||||
request.putHeader("Origin", origin);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
static FileInfo parseFileListRow(JsonArray row, String panType, String domainName, String shareUrl, String pwd) {
|
||||
if (row == null || row.size() < 2) {
|
||||
return null;
|
||||
}
|
||||
String checkboxHtml = rowString(row, 0);
|
||||
String nameCellHtml = rowString(row, 1);
|
||||
String sizeStr = rowString(row, 2).trim();
|
||||
String dateStr = rowString(row, 3).trim();
|
||||
if (nameCellHtml.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String fileName = matchFirst(FILE_NAME_PATTERN, nameCellHtml);
|
||||
String fileIcon = matchFirst(FILE_ICON_PATTERN, nameCellHtml);
|
||||
if (fileName == null || fileName.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Matcher subdirMatcher = SUBDIR_PATTERN.matcher(nameCellHtml);
|
||||
boolean hasSubdirCall = subdirMatcher.find();
|
||||
if (hasSubdirCall || "folder".equalsIgnoreCase(fileIcon)) {
|
||||
String folderId = hasSubdirCall ? subdirMatcher.group(1) : null;
|
||||
String folderKey = hasSubdirCall ? subdirMatcher.group(2) : "";
|
||||
if (folderId == null) {
|
||||
folderId = matchFirst(FOLDER_ID_PATTERN, checkboxHtml);
|
||||
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;
|
||||
}
|
||||
}
|
||||
if (folderId == null || folderId.isBlank()) {
|
||||
}
|
||||
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 dirId = folderId + ":" + folderKey;
|
||||
FileInfo fileInfo = new FileInfo()
|
||||
.setFileName(fileName.trim())
|
||||
.setFileId(folderId)
|
||||
.setSize(0L)
|
||||
.setSizeStr(sizeStr.isBlank() ? "0B" : sizeStr)
|
||||
String folderKey = row.getString("folderKey", "");
|
||||
fileInfo.setFileId(folderId)
|
||||
.setFileType("folder")
|
||||
.setFileIcon(fileIcon)
|
||||
.setPanType(panType)
|
||||
.setParserUrl(buildFolderParserUrl(domainName, shareUrl, dirId, pwd));
|
||||
if (!dateStr.isBlank()) {
|
||||
fileInfo.setCreateTime(dateStr).setUpdateTime(dateStr);
|
||||
}
|
||||
.setSize(0L)
|
||||
.setSizeStr("0B")
|
||||
.setParserUrl(buildFolderParserUrl(info, folderId + ":" + (folderKey == null ? "" : folderKey), password));
|
||||
return fileInfo;
|
||||
}
|
||||
|
||||
String fileShareKey = matchFirst(FILE_HREF_PATTERN, nameCellHtml);
|
||||
if (fileShareKey == null || fileShareKey.isBlank()) {
|
||||
if (!"file".equals(kind)) {
|
||||
return null;
|
||||
}
|
||||
String fileId = matchFirst(FILE_ID_PATTERN, checkboxHtml);
|
||||
JsonObject paramJson = new JsonObject()
|
||||
.put("id", fileShareKey)
|
||||
.put("fileName", fileName.trim())
|
||||
.put("pwd", pwd == null ? "" : pwd);
|
||||
String param = CommonUtils.urlBase64Encode(paramJson.encode());
|
||||
long sizeBytes = 0;
|
||||
try {
|
||||
sizeBytes = sizeStr.isBlank() ? 0 : FileSizeConverter.convertToBytes(sizeStr);
|
||||
} catch (Exception ignored) {
|
||||
String fileKey = fileKeyFromHref(row.getString("href", ""));
|
||||
if (fileKey.isBlank()) {
|
||||
fileKey = CtfileSession.text(row.getValue("fileId"));
|
||||
}
|
||||
|
||||
FileInfo fileInfo = new FileInfo()
|
||||
.setFileName(fileName.trim())
|
||||
.setFileId(fileId)
|
||||
.setSizeStr(sizeStr)
|
||||
.setSize(sizeBytes)
|
||||
.setFileType(fileIcon != null ? fileIcon : "file")
|
||||
.setFileIcon(fileIcon)
|
||||
.setPanType(panType)
|
||||
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
|
||||
domainName, panType, param));
|
||||
if (!dateStr.isBlank()) {
|
||||
fileInfo.setCreateTime(dateStr).setUpdateTime(dateStr);
|
||||
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(String domainName, String shareUrl, String dirId, String pwd) {
|
||||
String url = String.format("%s/v2/getFileList?url=%s&dirId=%s",
|
||||
domainName, urlEncode(shareUrl), urlEncode(dirId));
|
||||
if (pwd != null && !pwd.isBlank()) {
|
||||
url += "&pwd=" + urlEncode(pwd);
|
||||
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;
|
||||
}
|
||||
|
||||
static String extractQueryParam(String url, String paramName) {
|
||||
if (url == null || paramName == null) return null;
|
||||
int qIdx = url.indexOf('?');
|
||||
if (qIdx < 0) return null;
|
||||
String query = url.substring(qIdx + 1);
|
||||
int fragmentIdx = query.indexOf('#');
|
||||
if (fragmentIdx >= 0) {
|
||||
query = query.substring(0, fragmentIdx);
|
||||
private static String fileKeyFromHref(String href) {
|
||||
if (href == null || href.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
for (String param : query.split("&")) {
|
||||
int eqIdx = param.indexOf('=');
|
||||
if (eqIdx > 0 && urlDecode(param.substring(0, eqIdx)).equals(paramName)) {
|
||||
return urlDecode(param.substring(eqIdx + 1));
|
||||
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 null;
|
||||
return rest.substring(0, cut);
|
||||
}
|
||||
|
||||
static String extractPath(String shareUrl) {
|
||||
if (shareUrl == null) {
|
||||
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 "";
|
||||
}
|
||||
int comIdx = shareUrl.indexOf("com/");
|
||||
if (comIdx < 0) {
|
||||
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;
|
||||
}
|
||||
|
||||
int pathStart = comIdx + 4;
|
||||
int pathEnd = shareUrl.indexOf('/', pathStart);
|
||||
if (pathEnd < 0) {
|
||||
pathEnd = shareUrl.indexOf('?', pathStart);
|
||||
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();
|
||||
}
|
||||
if (pathEnd < 0) {
|
||||
pathEnd = shareUrl.length();
|
||||
}
|
||||
return shareUrl.substring(pathStart, pathEnd);
|
||||
}
|
||||
|
||||
static String extractFolderKey(String shareUrl) {
|
||||
return trimToEmpty(extractQueryParam(shareUrl, "fk"));
|
||||
}
|
||||
|
||||
static DirectoryContext resolveDirectoryContext(String shareUrl, Object dirIdObj) {
|
||||
String dirId = dirIdObj == null ? "" : urlDecode(String.valueOf(dirIdObj).trim());
|
||||
if (!dirId.isBlank()) {
|
||||
String[] split = dirId.split(":", 2);
|
||||
return new DirectoryContext(trimToDefault(split[0], "undefined"),
|
||||
split.length > 1 ? trimToEmpty(split[1]) : "");
|
||||
}
|
||||
|
||||
String queryFolderId = firstNonBlank(extractQueryParam(shareUrl, "folder_id"), extractQueryParam(shareUrl, "d"));
|
||||
String queryFk = extractFolderKey(shareUrl);
|
||||
if (!queryFolderId.isBlank() || !queryFk.isBlank()) {
|
||||
return new DirectoryContext(trimToDefault(queryFolderId, "undefined"), queryFk);
|
||||
}
|
||||
return new DirectoryContext("undefined", "");
|
||||
}
|
||||
|
||||
static String buildDirectoryFailureMessage(JsonObject resJson, JsonObject dirInfo) {
|
||||
String code = valueToString(resJson.getValue("code"));
|
||||
String message = valueToString(dirInfo.getValue("message"));
|
||||
if (message != null && !message.isBlank()) {
|
||||
return "目录解析失败: " + message + " (code=" + code + ")";
|
||||
}
|
||||
if ("423".equals(code)) {
|
||||
return "目录解析失败: 需要访问密码或该分享受限 (code=423)";
|
||||
}
|
||||
return "目录解析失败: 文件列表URL为空, 上游响应: " + resJson.encode();
|
||||
}
|
||||
|
||||
static String buildFileListParams(int start, int length) {
|
||||
return FILE_LIST_PARAMS_TEMPLATE
|
||||
.replace("{start}", String.valueOf(Math.max(0, start)))
|
||||
.replace("{length}", String.valueOf(Math.max(1, length)));
|
||||
}
|
||||
|
||||
static int parseFileListTotal(JsonObject listJson) {
|
||||
int displayTotal = parseInteger(listJson.getValue("iTotalDisplayRecords"), -1);
|
||||
return displayTotal >= 0 ? displayTotal : parseInteger(listJson.getValue("iTotalRecords"), -1);
|
||||
}
|
||||
|
||||
static boolean shouldFetchNextFileListPage(int start, int rowCount, int total) {
|
||||
if (rowCount <= 0) {
|
||||
return false;
|
||||
}
|
||||
int fetchedThrough = start + rowCount;
|
||||
return total < 0 ? rowCount >= FILE_LIST_PAGE_SIZE : fetchedThrough < total;
|
||||
}
|
||||
|
||||
static boolean isUnexpectedEmptyFileListPage(int start, int rowCount, int total) {
|
||||
return total >= 0 && start < total && rowCount <= 0;
|
||||
}
|
||||
|
||||
private static int parseInteger(Object value, int defaultValue) {
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).intValue();
|
||||
}
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(value.toString());
|
||||
} catch (NumberFormatException e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
private static void failListPromise(Promise<List<FileInfo>> listPromise, String message) {
|
||||
if (!listPromise.future().isComplete()) {
|
||||
listPromise.fail(message);
|
||||
}
|
||||
}
|
||||
|
||||
private static void failListPromise(Promise<List<FileInfo>> listPromise, Throwable throwable) {
|
||||
if (!listPromise.future().isComplete()) {
|
||||
listPromise.fail(throwable);
|
||||
}
|
||||
}
|
||||
|
||||
private static void completeListPromise(Promise<List<FileInfo>> listPromise, List<FileInfo> fileList) {
|
||||
if (!listPromise.future().isComplete()) {
|
||||
listPromise.complete(fileList);
|
||||
}
|
||||
}
|
||||
|
||||
private static String toCtApiUrl(String url) {
|
||||
if (url.startsWith("http://") || url.startsWith("https://")) {
|
||||
return url;
|
||||
}
|
||||
return API_URL_PREFIX + url;
|
||||
}
|
||||
|
||||
private static String appendQueryParams(String url, String params) {
|
||||
String normalizedParams = params != null && params.startsWith("&") ? params.substring(1) : params;
|
||||
return url + (url.contains("?") ? "&" : "?") + normalizedParams;
|
||||
}
|
||||
|
||||
private static String rowString(JsonArray row, int index) {
|
||||
if (row == null || index >= row.size()) {
|
||||
return "";
|
||||
}
|
||||
return valueToString(row.getValue(index));
|
||||
}
|
||||
|
||||
private static String valueToString(Object value) {
|
||||
return value == null ? "" : value.toString();
|
||||
}
|
||||
|
||||
private static String matchFirst(Pattern pattern, String text) {
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
return matcher.find() ? matcher.group(1) : null;
|
||||
}
|
||||
|
||||
private static String firstNonBlank(String first, String second) {
|
||||
return !trimToEmpty(first).isBlank() ? trimToEmpty(first) : trimToEmpty(second);
|
||||
}
|
||||
|
||||
private static String trimToDefault(String value, String defaultValue) {
|
||||
String result = trimToEmpty(value);
|
||||
return result.isBlank() ? defaultValue : result;
|
||||
}
|
||||
|
||||
private static String trimToEmpty(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
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 String urlDecode(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
private static String extractOrigin(String shareUrl) {
|
||||
try {
|
||||
URI uri = URI.create(shareUrl);
|
||||
if (uri.getScheme() == null || uri.getHost() == null) {
|
||||
return "";
|
||||
private static WorkerExecutor worker() {
|
||||
synchronized (WORKER_LOCK) {
|
||||
if (workerShutdown) {
|
||||
throw new IllegalStateException("城通解析线程池已关闭");
|
||||
}
|
||||
String origin = uri.getScheme() + "://" + uri.getHost();
|
||||
return uri.getPort() > 0 ? origin + ":" + uri.getPort() : origin;
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
if (sharedWorker == null) {
|
||||
sharedWorker = WebClientVertxInit.get().createSharedWorkerExecutor("ctfile-worker", 4);
|
||||
}
|
||||
return sharedWorker;
|
||||
}
|
||||
}
|
||||
|
||||
static final class DirectoryContext {
|
||||
final String folderId;
|
||||
final String folderKey;
|
||||
private static final class ParsedDownload {
|
||||
final String url;
|
||||
final java.util.Map<String, String> headers;
|
||||
final JsonObject file;
|
||||
final String fileDir;
|
||||
|
||||
DirectoryContext(String folderId, String folderKey) {
|
||||
this.folderId = folderId;
|
||||
this.folderKey = folderKey;
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.PanBase;
|
||||
@@ -8,6 +9,7 @@ import cn.qaiu.util.CommonUtils;
|
||||
import cn.qaiu.util.CookieUtils;
|
||||
import cn.qaiu.util.FileSizeConverter;
|
||||
import cn.qaiu.util.HeaderUtils;
|
||||
import cn.qaiu.util.QuarkAccountScope;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Promise;
|
||||
@@ -66,8 +68,10 @@ public class QkTool extends PanBase {
|
||||
"夸克要求登录后才能下载。请配置 Cookie(auths.qk.cookie,或请求参数 auth)。"
|
||||
+ "小文件可以免登录直链;这个报错表示当前文件需要账号,请到 Cookie/auth 配置里补登录态。";
|
||||
|
||||
// 静态变量:缓存已转存的文件 (分享key -> 转存文件ID)
|
||||
// 静态变量:缓存已转存的文件 (账号范围 + 分享文件 -> 转存文件ID)
|
||||
private static final Map<String, String> savedFileCache = new java.util.concurrent.ConcurrentHashMap<>();
|
||||
/** 本次解析得到的是不带账号的公开文件地址。 */
|
||||
private boolean publicDirectLink;
|
||||
|
||||
private final MultiMap header = HeaderUtils.parseHeaders("""
|
||||
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) quark-cloud-drive/2.5.20 Chrome/100.0.4896.160 Electron/18.3.5.4-b478491100 Safari/537.36 Channel/pckk_other_ch
|
||||
@@ -249,7 +253,7 @@ public class QkTool extends PanBase {
|
||||
// 根目录可能只是文件夹(#282)。先列出再进入,找到文件后再取直链。
|
||||
findDownloadableFiles(pwdId, stoken, "0", 0)
|
||||
.compose(files -> resolveListedFiles(files, pwdId, stoken))
|
||||
.onSuccess(downloadUrl -> completeWithMeta(downloadUrl, buildDownloadHeaders(null)))
|
||||
.onSuccess(this::finishParse)
|
||||
.onFailure(t -> fail(t.getMessage() == null ? "解析失败" : t.getMessage()));
|
||||
})
|
||||
.onFailure(handleFail(TOKEN_URL));
|
||||
@@ -261,14 +265,83 @@ public class QkTool extends PanBase {
|
||||
if (files == null || files.isEmpty()) {
|
||||
return Future.failedFuture(EMPTY_SHARE_MSG);
|
||||
}
|
||||
JsonObject primary = files.get(0);
|
||||
if (QuarkFamilyDownloadPolicy.knownLarge(fileSize(primary))) {
|
||||
rememberFile(primary);
|
||||
return resolveLargeFile(primary, pwdId, stoken);
|
||||
}
|
||||
if (hasQuarkCookie()) {
|
||||
JsonObject first = files.get(0);
|
||||
rememberFile(first);
|
||||
return resolveDownloadUrl(first.getString("fid"), pwdId, stoken, first.getString("share_fid_token"));
|
||||
rememberFile(primary);
|
||||
return resolveDownloadUrl(primary.getString("fid"), pwdId, stoken, primary.getString("share_fid_token"));
|
||||
}
|
||||
return resolveGuestDownloads(orderGuestCandidates(files), pwdId, stoken, 0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 大于 10MiB:有效 SVIP/VIP 走现有账号直链(含原有转存回退);否则只要探测通过的 H5 文件地址。
|
||||
*/
|
||||
private Future<String> resolveLargeFile(JsonObject file, String pwdId, String stoken) {
|
||||
String fid = file.getString("fid");
|
||||
String shareFidToken = file.getString("share_fid_token");
|
||||
String fileName = file.getString("file_name", "");
|
||||
if (fid == null || fid.isEmpty()) {
|
||||
return Future.failedFuture(QuarkFamilyDownloadPolicy.largeFileError("qk", null,
|
||||
new IllegalStateException("缺少 fid")));
|
||||
}
|
||||
return QuarkFamilyDownloadPolicy.fetchMembership(client, header, false)
|
||||
.compose(member -> {
|
||||
if (!member.validPaid) {
|
||||
return h5Download(pwdId, stoken, fid, shareFidToken, fileName)
|
||||
.recover(h5Error -> Future.failedFuture(
|
||||
QuarkFamilyDownloadPolicy.largeFileError("qk", null, h5Error)));
|
||||
}
|
||||
return resolveDownloadUrl(fid, pwdId, stoken, shareFidToken)
|
||||
.recover(directError -> h5Download(pwdId, stoken, fid, shareFidToken, fileName)
|
||||
.recover(h5Error -> Future.failedFuture(
|
||||
QuarkFamilyDownloadPolicy.largeFileError("qk", directError, h5Error))));
|
||||
});
|
||||
}
|
||||
|
||||
private Future<String> h5Download(String pwdId, String stoken, String fid, String shareFidToken, String fileName) {
|
||||
return QuarkFamilyDownloadPolicy.resolveH5Download(clientNoRedirects, WebClientVertxInit.get(),
|
||||
"qk", pwdId, stoken, fid, shareFidToken, fileName)
|
||||
.map(url -> {
|
||||
publicDirectLink = true;
|
||||
shareLinkInfo.getOtherParam().put("publicDirectLink", true);
|
||||
shareLinkInfo.getOtherParam().put("previewUrl", QuarkFamilyDownloadPolicy.bareFileUrl(url));
|
||||
return url;
|
||||
});
|
||||
}
|
||||
|
||||
private void finishParse(String downloadUrl) {
|
||||
String presented = presentIfPublic(downloadUrl);
|
||||
if (publicDirectLink) {
|
||||
completeWithMeta(presented, Map.of());
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", false);
|
||||
return;
|
||||
}
|
||||
completeWithMeta(presented, buildDownloadHeaders(null));
|
||||
}
|
||||
|
||||
private String presentIfPublic(String downloadUrl) {
|
||||
String presented = QuarkFamilyDownloadPolicy.presentPublicDownload(downloadUrl, "qk", currentFileName());
|
||||
if (!presented.equals(downloadUrl) || QuarkFamilyDownloadPolicy.isPublicFileUrl(presented, "qk")) {
|
||||
publicDirectLink = true;
|
||||
shareLinkInfo.getOtherParam().put("publicDirectLink", true);
|
||||
shareLinkInfo.getOtherParam().put("previewUrl", QuarkFamilyDownloadPolicy.bareFileUrl(presented));
|
||||
}
|
||||
return presented;
|
||||
}
|
||||
|
||||
private String currentFileName() {
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 访客没有 Cookie,不能转存。先试接口排序下的第一个文件;
|
||||
* 若夸克返回 23018,再按体积从小到大试同目录里的其他文件。
|
||||
@@ -280,7 +353,7 @@ public class QkTool extends PanBase {
|
||||
}
|
||||
JsonObject file = files.get(index);
|
||||
String fid = file.getString("fid");
|
||||
if (fid == null || fid.isEmpty()) {
|
||||
if (fid == null || fid.isEmpty() || QuarkFamilyDownloadPolicy.knownLarge(fileSize(file))) {
|
||||
return resolveGuestDownloads(files, pwdId, stoken, index + 1, attempts);
|
||||
}
|
||||
return getShareDownloadLink(fid, pwdId, stoken, file.getString("share_fid_token"))
|
||||
@@ -764,6 +837,7 @@ public class QkTool extends PanBase {
|
||||
if (shareFidToken != null) {
|
||||
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);
|
||||
@@ -834,13 +908,29 @@ public class QkTool extends PanBase {
|
||||
|
||||
log.debug("夸克 parseById: fid={}, pwd_id={}, stoken={}", fid, pwdId, stoken);
|
||||
|
||||
resolveDownloadUrl(fid, pwdId, stoken, shareFidToken)
|
||||
.onSuccess(downloadUrl -> {
|
||||
Map<String, String> downloadHeaders = buildDownloadHeaders(paramJson);
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", downloadHeaders);
|
||||
shareLinkInfo.getOtherParam().put("fileName", paramJson.getString("fileName", ""));
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", true);
|
||||
promise.complete(downloadUrl);
|
||||
String fileName = paramJson.getString("fileName", "");
|
||||
Future<String> download;
|
||||
if (QuarkFamilyDownloadPolicy.knownLarge(QuarkFamilyDownloadPolicy.sizeOf(paramJson))) {
|
||||
JsonObject file = new JsonObject()
|
||||
.put("fid", fid)
|
||||
.put("share_fid_token", shareFidToken)
|
||||
.put("file_name", fileName)
|
||||
.put("size", QuarkFamilyDownloadPolicy.sizeOf(paramJson));
|
||||
download = resolveLargeFile(file, pwdId, stoken);
|
||||
} else {
|
||||
download = resolveDownloadUrl(fid, pwdId, stoken, shareFidToken);
|
||||
}
|
||||
download.onSuccess(downloadUrl -> {
|
||||
shareLinkInfo.getOtherParam().put("fileName", fileName);
|
||||
String presented = presentIfPublic(downloadUrl);
|
||||
if (publicDirectLink) {
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", new HashMap<>());
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", false);
|
||||
} else {
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", buildDownloadHeaders(paramJson));
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", true);
|
||||
}
|
||||
promise.complete(presented);
|
||||
})
|
||||
.onFailure(promise::fail);
|
||||
|
||||
@@ -904,7 +994,8 @@ public class QkTool extends PanBase {
|
||||
*/
|
||||
private Future<String> saveAndDownload(String pwdId, String stoken, String shareFid, String shareFidToken) {
|
||||
Promise<String> promise = Promise.promise();
|
||||
String fileCacheKey = pwdId + "_" + (shareFid == null ? "" : shareFid);
|
||||
String scope = QuarkAccountScope.suffix(shareLinkInfo.getOtherParam());
|
||||
String fileCacheKey = (scope == null ? "_" : scope) + ":" + pwdId + "_" + (shareFid == null ? "" : shareFid);
|
||||
|
||||
// 本地缓存命中 → 跳过转存,直接用已转存 fid 取链
|
||||
String cachedFid = savedFileCache.get(fileCacheKey);
|
||||
|
||||
@@ -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;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.PanBase;
|
||||
import cn.qaiu.parser.TokenCache;
|
||||
import cn.qaiu.util.CommonUtils;
|
||||
import cn.qaiu.util.CookieUtils;
|
||||
import cn.qaiu.util.DateTimeUtils;
|
||||
import cn.qaiu.util.FileSizeConverter;
|
||||
import cn.qaiu.util.HeaderUtils;
|
||||
import cn.qaiu.util.QuarkAccountScope;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Promise;
|
||||
@@ -28,10 +31,7 @@ import java.util.Map;
|
||||
*/
|
||||
public class UcTool extends PanBase {
|
||||
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 分钟刷新)
|
||||
private static final long PUUS_TTL_MS = 55 * 60 * 1000L;
|
||||
|
||||
@@ -67,9 +67,17 @@ public class UcTool extends PanBase {
|
||||
|
||||
// 保存 auths 引用,用于更新 cookie
|
||||
private MultiMap auths;
|
||||
private final String cacheKey;
|
||||
/** 本次解析得到的是不带账号的公开文件地址。UC 大文件没有这条地址时不能当成免登录成功。 */
|
||||
private boolean publicDirectLink;
|
||||
|
||||
public UcTool(ShareLinkInfo shareLinkInfo) {
|
||||
super(shareLinkInfo);
|
||||
String accountId = QuarkAccountScope.suffix(shareLinkInfo.getOtherParam());
|
||||
if (accountId == null) {
|
||||
accountId = "_default";
|
||||
}
|
||||
this.cacheKey = TokenCache.key("uc", accountId);
|
||||
// 参考其它网盘实现,从认证配置中取 cookie 放到请求头
|
||||
if (shareLinkInfo.getOtherParam() != null && shareLinkInfo.getOtherParam().containsKey("auths")) {
|
||||
auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
||||
@@ -77,18 +85,20 @@ public class UcTool extends PanBase {
|
||||
if (cookie != null && !cookie.isEmpty()) {
|
||||
// 过滤出 UC 网盘所需的 cookie 字段
|
||||
cookie = CookieUtils.filterUcQuarkCookie(cookie);
|
||||
|
||||
// 如果有缓存的 __puus 且未过期,使用缓存的值更新 cookie
|
||||
if (cachedPuus != null && System.currentTimeMillis() < puusExpireTime) {
|
||||
|
||||
// 按账号读取 __puus,避免把别的账号的会话写进当前请求
|
||||
String cachedPuus = TokenCache.getToken(cacheKey);
|
||||
long puusExpire = TokenCache.getExpire(cacheKey);
|
||||
if (cachedPuus != null && System.currentTimeMillis() < puusExpire) {
|
||||
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);
|
||||
// 同步更新 auths
|
||||
auths.set("cookie", cookie);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 如果 __puus 已过期或不存在,触发异步刷新
|
||||
if (needRefreshPuus()) {
|
||||
log.debug("UC: __puus 需要刷新,触发异步刷新");
|
||||
@@ -110,7 +120,7 @@ public class UcTool extends PanBase {
|
||||
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);
|
||||
}
|
||||
|
||||
// 更新静态缓存
|
||||
cachedPuus = newPuus;
|
||||
puusExpireTime = System.currentTimeMillis() + PUUS_TTL_MS;
|
||||
|
||||
log.info("UC: __puus cookie 刷新成功,有效期至: {}ms", puusExpireTime);
|
||||
TokenCache.putToken(cacheKey, newPuus);
|
||||
TokenCache.putExpire(cacheKey, System.currentTimeMillis() + PUUS_TTL_MS);
|
||||
|
||||
log.info("UC: __puus cookie 刷新成功,有效期至: {}ms", TokenCache.getExpire(cacheKey));
|
||||
refreshPromise.complete(true);
|
||||
} else {
|
||||
log.debug("UC: 响应中未包含 __puus,可能 cookie 仍然有效");
|
||||
@@ -242,35 +251,16 @@ public class UcTool extends PanBase {
|
||||
log.warn("UC 提取文件信息失败,继续解析: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// 第三次请求获取下载链接
|
||||
var bodyJson = JsonObject.of()
|
||||
.put("fids", JsonArray.of(info.getString("fid")))
|
||||
.put("pwd_id", dataKey)
|
||||
.put("stoken", stoken)
|
||||
.put("fids_token", JsonArray.of(info.getString("share_fid_token")));
|
||||
client.postAbs(THIRD_REQUEST_URL)
|
||||
.putHeaders(header)
|
||||
.sendJsonObject(bodyJson)
|
||||
.onSuccess(res3 -> {
|
||||
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 需配合下载器(带 cookie),保存下载请求头
|
||||
completeWithMeta(downloadUrl, buildDownloadHeaders(null));
|
||||
} catch (Exception e) {
|
||||
fail("解析 UC 下载链接失败: " + e.getMessage());
|
||||
}
|
||||
}).onFailure(handleFail(THIRD_REQUEST_URL));
|
||||
String fid = info.getString("fid");
|
||||
String shareFidToken = info.getString("share_fid_token");
|
||||
Future<String> download;
|
||||
if (QuarkFamilyDownloadPolicy.knownLarge(QuarkFamilyDownloadPolicy.sizeOf(info))) {
|
||||
download = resolveUcLarge(fid, dataKey, stoken, shareFidToken, info.getString("file_name"));
|
||||
} else {
|
||||
download = requestUcDownload(fid, dataKey, stoken, shareFidToken);
|
||||
}
|
||||
download.onSuccess(this::finishUcParse)
|
||||
.onFailure(t -> fail(t.getMessage() == null ? "解析失败" : t.getMessage()));
|
||||
} catch (Exception e) {
|
||||
fail("解析 UC 文件信息失败: " + e.getMessage());
|
||||
}
|
||||
@@ -281,6 +271,108 @@ public class UcTool extends PanBase {
|
||||
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
|
||||
public Future<List<FileInfo>> parseFileList() {
|
||||
@@ -461,6 +553,7 @@ public class UcTool extends PanBase {
|
||||
if (shareFidToken != null) {
|
||||
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);
|
||||
@@ -531,49 +624,27 @@ public class UcTool extends PanBase {
|
||||
}
|
||||
|
||||
log.debug("UC parseById: fid={}, pwd_id={}, stoken={}", fid, pwdId, stoken);
|
||||
|
||||
// 调用第三次请求获取下载链接
|
||||
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));
|
||||
|
||||
String fileName = paramJson.getString("fileName", "");
|
||||
Future<String> download;
|
||||
if (QuarkFamilyDownloadPolicy.knownLarge(QuarkFamilyDownloadPolicy.sizeOf(paramJson))) {
|
||||
download = resolveUcLarge(fid, pwdId, stoken, shareFidToken, fileName);
|
||||
} else {
|
||||
download = requestUcDownload(fid, pwdId, stoken, shareFidToken);
|
||||
}
|
||||
|
||||
client.postAbs(THIRD_REQUEST_URL)
|
||||
.putHeaders(header)
|
||||
.sendJsonObject(bodyJson)
|
||||
.onSuccess(res -> {
|
||||
log.debug("UC parseById 响应: {}", res.body());
|
||||
JsonObject resJson = res.bodyAsJsonObject();
|
||||
if (resJson.getInteger("code") != 0) {
|
||||
promise.fail(THIRD_REQUEST_URL + " 返回异常: " + resJson);
|
||||
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;
|
||||
}
|
||||
// 存储下载请求头,供目录解析 getFileDownInfo 接口使用
|
||||
// 优先用当前会话 cookie;缺失时回退入口参数中已带的 cookie
|
||||
Map<String, String> downloadHeaders = buildDownloadHeaders(paramJson);
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", downloadHeaders);
|
||||
shareLinkInfo.getOtherParam().put("fileName", paramJson.getString("fileName", ""));
|
||||
promise.complete(downloadUrl);
|
||||
} catch (Exception e) {
|
||||
promise.fail("解析 UC 下载链接失败: " + e.getMessage());
|
||||
download.onSuccess(downloadUrl -> {
|
||||
shareLinkInfo.getOtherParam().put("fileName", fileName);
|
||||
String presented = presentUcIfPublic(downloadUrl);
|
||||
if (publicDirectLink) {
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", new HashMap<>());
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", false);
|
||||
} else {
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", buildDownloadHeaders(paramJson));
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", true);
|
||||
}
|
||||
promise.complete(presented);
|
||||
})
|
||||
.onFailure(t -> promise.fail("请求下载链接失败: " + t.getMessage()));
|
||||
.onFailure(t -> promise.fail(t.getMessage() == null ? "请求下载链接失败" : t.getMessage()));
|
||||
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import io.vertx.ext.web.client.HttpRequest;
|
||||
import io.vertx.ext.web.client.HttpResponse;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
@@ -27,6 +28,9 @@ import java.util.regex.Pattern;
|
||||
* 永硕E盘(主 ysepan.com / ys168.com,备 cccpan.com / ysupan.com / uupan.net / ysok.net)
|
||||
* <p>
|
||||
* 空间分享形如 https://{space}.ysepan.com/ ,需空间访问密码时通过 sharePassword 传入。
|
||||
* <p>
|
||||
* 2026-11 起密码空间改为入口页:令牌在 {@code data-verification-token},登录名在 {@code data-dlmc}。
|
||||
* {@code ys168.com} 会 302 到 {@code ysepan.com},密码验证必须发往跳转后的主机。
|
||||
*/
|
||||
public class YsTool extends PanBase {
|
||||
|
||||
@@ -34,10 +38,17 @@ public class YsTool extends PanBase {
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
||||
+ "(KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36";
|
||||
|
||||
private static final Pattern ANTIFORGERY_PATTERN =
|
||||
/** 旧版入口脚本:{@code RequestVerificationToken': '...'} */
|
||||
private static final Pattern ANTIFORGERY_LEGACY_PATTERN =
|
||||
Pattern.compile("RequestVerificationToken'\\s*:\\s*'([^']+)'");
|
||||
/** 新版入口页:{@code data-verification-token="..."} */
|
||||
private static final Pattern ANTIFORGERY_ATTR_PATTERN =
|
||||
Pattern.compile("data-verification-token\\s*=\\s*([\"'])([^\"']+)\\1");
|
||||
private static final Pattern DLMC_ATTR_PATTERN =
|
||||
Pattern.compile("data-dlmc\\s*=\\s*([\"'])([^\"']+)\\1");
|
||||
private static final Pattern HTXX_PATTERN =
|
||||
Pattern.compile("window\\.htxx\\s*=\\s*(\\{.*?});", Pattern.DOTALL);
|
||||
private static final int MAX_HOME_REDIRECTS = 5;
|
||||
private static final Pattern JWT_COOKIE_PATTERN =
|
||||
Pattern.compile("jwttk_[^=]+=([^;\\s]+)");
|
||||
|
||||
@@ -141,21 +152,49 @@ public class YsTool extends PanBase {
|
||||
}
|
||||
|
||||
private Future<Session> ensureSession() {
|
||||
Promise<Session> p = Promise.promise();
|
||||
String space = spaceName();
|
||||
if (StringUtils.isBlank(space)) {
|
||||
p.fail(baseMsg() + " - 空间名为空");
|
||||
return p.future();
|
||||
return Future.failedFuture(baseMsg() + " - 空间名为空");
|
||||
}
|
||||
// 手动跟随跳转,才能把后续密码验证发到最终主机(ys168.com -> ysepan.com)
|
||||
return fetchSpaceHome(spaceOrigin() + "/", 0)
|
||||
.compose(home -> handleSpaceHome(home.origin(), space, home.response()));
|
||||
}
|
||||
|
||||
String origin = spaceOrigin();
|
||||
clientSession.getAbs(origin + "/")
|
||||
/**
|
||||
* 关闭自动重定向并逐跳记录最终地址。Cookie(含 .AspNetCore.Antiforgery.* 与 jwttk_*)
|
||||
* 仍由同一个 clientSession 保存,供密码验证和接口请求带上。
|
||||
*/
|
||||
private Future<FetchedHome> fetchSpaceHome(String url, int redirects) {
|
||||
Promise<FetchedHome> p = Promise.promise();
|
||||
clientSession.getAbs(url)
|
||||
.followRedirects(false)
|
||||
.putHeader("User-Agent", BROWSER_UA)
|
||||
.putHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||
.send()
|
||||
.compose(res -> handleSpaceHome(origin, space, res))
|
||||
.onSuccess(p::complete)
|
||||
.onFailure(p::fail);
|
||||
.onSuccess(res -> {
|
||||
int status = res.statusCode();
|
||||
if (status >= 300 && status < 400 && status != 304) {
|
||||
if (redirects >= MAX_HOME_REDIRECTS) {
|
||||
p.fail(baseMsg() + " - 空间首页重定向次数过多");
|
||||
return;
|
||||
}
|
||||
String next = resolveRedirect(url, res.getHeader("Location"));
|
||||
if (next == null) {
|
||||
p.fail(baseMsg() + " - 空间首页重定向无效");
|
||||
return;
|
||||
}
|
||||
fetchSpaceHome(next, redirects + 1).onComplete(p);
|
||||
return;
|
||||
}
|
||||
String origin = originOf(url);
|
||||
if (origin == null) {
|
||||
p.fail(baseMsg() + " - 空间地址无效");
|
||||
return;
|
||||
}
|
||||
p.complete(new FetchedHome(origin, res));
|
||||
})
|
||||
.onFailure(t -> p.fail(baseMsg() + " - 打开空间失败: " + t.getMessage()));
|
||||
return p.future();
|
||||
}
|
||||
|
||||
@@ -172,8 +211,8 @@ public class YsTool extends PanBase {
|
||||
return Future.succeededFuture(toSession(origin, space, jwt, htxx));
|
||||
}
|
||||
|
||||
// 需要空间密码
|
||||
if (html.contains("VerifyPassword") || html.contains("loginPopup")) {
|
||||
// 需要空间密码(新版入口页或旧版 loginPopup / VerifyPassword)
|
||||
if (isPasswordPage(html)) {
|
||||
String pwd = shareLinkInfo.getSharePassword();
|
||||
if (StringUtils.isBlank(pwd)) {
|
||||
return Future.failedFuture(baseMsg() + " - 空间需要访问密码");
|
||||
@@ -182,21 +221,25 @@ public class YsTool extends PanBase {
|
||||
if (StringUtils.isBlank(antiforgery)) {
|
||||
return Future.failedFuture(baseMsg() + " - 无法获取防伪令牌");
|
||||
}
|
||||
return verifyPassword(origin, space, pwd, antiforgery)
|
||||
.compose(verifiedJwt -> reloadSpace(origin, space, verifiedJwt));
|
||||
String dlmc = StringUtils.defaultIfBlank(extractDlmc(html), space);
|
||||
// 新版 VerifyPassword 只返回 {"success":true},jwttk 在入口页就已经下发
|
||||
return verifyPassword(origin, dlmc, pwd, antiforgery)
|
||||
.compose(verifiedJwt -> reloadSpace(origin, space,
|
||||
StringUtils.defaultIfBlank(verifiedJwt, jwt)));
|
||||
}
|
||||
|
||||
return Future.failedFuture(baseMsg() + " - 无法解析空间信息");
|
||||
}
|
||||
|
||||
private Future<String> verifyPassword(String origin, String space, String pwd, String antiforgery) {
|
||||
private Future<String> verifyPassword(String origin, String dlmc, String pwd, String antiforgery) {
|
||||
Promise<String> p = Promise.promise();
|
||||
JsonObject body = new JsonObject()
|
||||
.put("password", pwd)
|
||||
.put("dlmc", space)
|
||||
.put("dlmc", dlmc)
|
||||
.put("remember", false);
|
||||
|
||||
clientSession.postAbs(origin + "/?handler=VerifyPassword")
|
||||
clientSession.postAbs(verifyPasswordEndpoint(origin))
|
||||
.followRedirects(false)
|
||||
.putHeader("User-Agent", BROWSER_UA)
|
||||
.putHeader("Content-Type", "application/json")
|
||||
.putHeader("Origin", origin)
|
||||
@@ -205,18 +248,18 @@ public class YsTool extends PanBase {
|
||||
.sendJsonObject(body)
|
||||
.onSuccess(res -> {
|
||||
try {
|
||||
if (res.statusCode() >= 400) {
|
||||
p.fail(baseMsg() + " - " + passwordFailureMessage(res.statusCode(), res.bodyAsString()));
|
||||
return;
|
||||
}
|
||||
JsonObject json = res.bodyAsJsonObject();
|
||||
if (json == null || !Boolean.TRUE.equals(json.getBoolean("success"))) {
|
||||
String msg = json != null ? json.getString("message", "密码错误") : "密码验证失败";
|
||||
p.fail(baseMsg() + " - " + msg);
|
||||
return;
|
||||
}
|
||||
String jwt = extractJwt(res);
|
||||
if (StringUtils.isBlank(jwt)) {
|
||||
p.fail(baseMsg() + " - 密码验证成功但未返回会话令牌");
|
||||
return;
|
||||
}
|
||||
p.complete(jwt);
|
||||
// 响应里若刷新了 jwttk 就用新的;否则调用方回退到入口页令牌
|
||||
p.complete(StringUtils.defaultString(extractJwt(res)));
|
||||
} catch (Exception e) {
|
||||
p.fail(baseMsg() + " - 密码验证响应异常: " + e.getMessage());
|
||||
}
|
||||
@@ -226,27 +269,18 @@ public class YsTool extends PanBase {
|
||||
}
|
||||
|
||||
private Future<Session> reloadSpace(String origin, String space, String verifiedJwt) {
|
||||
Promise<Session> p = Promise.promise();
|
||||
clientSession.getAbs(origin + "/")
|
||||
.putHeader("User-Agent", BROWSER_UA)
|
||||
.putHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||
.send()
|
||||
.onSuccess(res -> {
|
||||
String html = res.bodyAsString() != null ? res.bodyAsString() : "";
|
||||
JsonObject htxx = extractHtxx(html);
|
||||
String jwt = StringUtils.defaultIfBlank(extractJwt(res), verifiedJwt);
|
||||
if (htxx == null || StringUtils.isBlank(htxx.getString("qqdz"))) {
|
||||
p.fail(baseMsg() + " - 密码验证后仍无法进入空间");
|
||||
return;
|
||||
}
|
||||
if (StringUtils.isBlank(jwt)) {
|
||||
p.fail(baseMsg() + " - 密码验证后无法获取会话令牌");
|
||||
return;
|
||||
}
|
||||
p.complete(toSession(origin, space, jwt, htxx));
|
||||
})
|
||||
.onFailure(t -> p.fail(baseMsg() + " - 重新加载空间失败: " + t.getMessage()));
|
||||
return p.future();
|
||||
return fetchSpaceHome(origin + "/", 0).compose(home -> {
|
||||
String html = home.response().bodyAsString() != null ? home.response().bodyAsString() : "";
|
||||
JsonObject htxx = extractHtxx(html);
|
||||
String jwt = StringUtils.defaultIfBlank(extractJwt(home.response()), verifiedJwt);
|
||||
if (htxx == null || StringUtils.isBlank(htxx.getString("qqdz"))) {
|
||||
return Future.failedFuture(baseMsg() + " - 密码验证后仍无法进入空间");
|
||||
}
|
||||
if (StringUtils.isBlank(jwt)) {
|
||||
return Future.failedFuture(baseMsg() + " - 密码验证后无法获取会话令牌");
|
||||
}
|
||||
return Future.succeededFuture(toSession(home.origin(), space, jwt, htxx));
|
||||
});
|
||||
}
|
||||
|
||||
private Session toSession(String origin, String space, String jwt, JsonObject htxx) {
|
||||
@@ -620,24 +654,134 @@ public class YsTool extends PanBase {
|
||||
}
|
||||
|
||||
private String spaceOrigin() {
|
||||
String shareUrl = shareLinkInfo.getShareUrl();
|
||||
if (StringUtils.isNotBlank(shareUrl)) {
|
||||
try {
|
||||
java.net.URI uri = java.net.URI.create(shareUrl);
|
||||
String scheme = uri.getScheme() != null ? uri.getScheme() : "https";
|
||||
return scheme + "://" + uri.getHost();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
String fromUrl = originOf(shareLinkInfo.getShareUrl());
|
||||
if (fromUrl != null) {
|
||||
return fromUrl;
|
||||
}
|
||||
return "https://" + spaceName() + ".ysepan.com";
|
||||
}
|
||||
|
||||
private static String extractAntiforgery(String html) {
|
||||
Matcher m = ANTIFORGERY_PATTERN.matcher(html);
|
||||
return m.find() ? m.group(1) : null;
|
||||
static boolean isPasswordPage(String html) {
|
||||
if (StringUtils.isBlank(html)) {
|
||||
return false;
|
||||
}
|
||||
return html.contains("VerifyPassword")
|
||||
|| html.contains("loginPopup")
|
||||
|| html.contains("data-verification-token")
|
||||
|| html.contains("id=\"entryConfig\"")
|
||||
|| html.contains("id=\"loginForm\"")
|
||||
|| html.contains("id='entryConfig'")
|
||||
|| html.contains("id='loginForm'");
|
||||
}
|
||||
|
||||
private static JsonObject extractHtxx(String html) {
|
||||
/**
|
||||
* 优先新版 data-verification-token,其次旧版脚本里的 RequestVerificationToken。
|
||||
*/
|
||||
static String extractAntiforgery(String html) {
|
||||
if (html == null) {
|
||||
return null;
|
||||
}
|
||||
Matcher attr = ANTIFORGERY_ATTR_PATTERN.matcher(html);
|
||||
if (attr.find()) {
|
||||
return attr.group(2);
|
||||
}
|
||||
Matcher legacy = ANTIFORGERY_LEGACY_PATTERN.matcher(html);
|
||||
return legacy.find() ? legacy.group(1) : null;
|
||||
}
|
||||
|
||||
static String extractDlmc(String html) {
|
||||
if (html == null) {
|
||||
return null;
|
||||
}
|
||||
Matcher matcher = DLMC_ATTR_PATTERN.matcher(html);
|
||||
return matcher.find() ? matcher.group(2) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把密码接口的失败响应转成可展示的短句。上游对错误密码返回 HTTP 400,
|
||||
* 正文是 {@code code=invalid_password}。不回传响应原文,避免带上令牌。
|
||||
*/
|
||||
static String passwordFailureMessage(int statusCode, String body) {
|
||||
try {
|
||||
if (body != null && body.trim().startsWith("{")) {
|
||||
JsonObject json = new JsonObject(body);
|
||||
String code = StringUtils.defaultString(json.getString("code"));
|
||||
String message = safePasswordMessage(json.getString("message"));
|
||||
if ("invalid_password".equals(code)) {
|
||||
return message != null ? message : "密码错误";
|
||||
}
|
||||
if (message != null) {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return "密码验证失败 HTTP " + statusCode;
|
||||
}
|
||||
|
||||
private static String safePasswordMessage(String message) {
|
||||
if (StringUtils.isBlank(message)) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = message.trim();
|
||||
if (trimmed.length() > 80) {
|
||||
return null;
|
||||
}
|
||||
String lower = trimmed.toLowerCase();
|
||||
if (lower.contains("eyj") || trimmed.contains("CfDJ") || lower.contains("jwttk")
|
||||
|| lower.contains("cookie") || lower.contains("token")) {
|
||||
return null;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/** 密码验证地址。origin 必须是重定向结束后的主机,不能用 ys168.com 原站。 */
|
||||
static String verifyPasswordEndpoint(String origin) {
|
||||
return origin + "/?handler=VerifyPassword";
|
||||
}
|
||||
|
||||
static String resolveRedirect(String currentUrl, String location) {
|
||||
if (StringUtils.isBlank(currentUrl) || StringUtils.isBlank(location)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
URI resolved = URI.create(currentUrl.trim()).resolve(location.trim());
|
||||
if (resolved.getScheme() == null || resolved.getHost() == null) {
|
||||
return null;
|
||||
}
|
||||
return resolved.toString();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static String originOf(String url) {
|
||||
if (StringUtils.isBlank(url)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
URI uri = URI.create(url.trim());
|
||||
if (uri.getScheme() == null || uri.getHost() == null) {
|
||||
return null;
|
||||
}
|
||||
String scheme = uri.getScheme();
|
||||
int port = uri.getPort();
|
||||
boolean defaultPort = port < 0
|
||||
|| ("https".equalsIgnoreCase(scheme) && port == 443)
|
||||
|| ("http".equalsIgnoreCase(scheme) && port == 80);
|
||||
if (defaultPort) {
|
||||
return scheme + "://" + uri.getHost();
|
||||
}
|
||||
return scheme + "://" + uri.getHost() + ":" + port;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static JsonObject extractHtxx(String html) {
|
||||
if (html == null) {
|
||||
return null;
|
||||
}
|
||||
Matcher m = HTXX_PATTERN.matcher(html);
|
||||
if (!m.find()) {
|
||||
return null;
|
||||
@@ -686,6 +830,9 @@ public class YsTool extends PanBase {
|
||||
return URLEncoder.encode(StringUtils.defaultString(value), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private record FetchedHome(String origin, HttpResponse<Buffer> response) {
|
||||
}
|
||||
|
||||
private record Session(String origin, String space, String jwt, String apiBase) {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package cn.qaiu.util;
|
||||
|
||||
import io.vertx.core.MultiMap;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 夸克 / UC 账号缓存范围。只产出不可逆短指纹,不包含 Cookie 原文。
|
||||
* 有 {@code _configId} 时按配置隔离;否则按过滤后的会话 Cookie 隔离。
|
||||
*/
|
||||
public final class QuarkAccountScope {
|
||||
|
||||
private QuarkAccountScope() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 可放进缓存 key 的短指纹;没有账号时返回 null,调用方继续使用分享级缓存
|
||||
*/
|
||||
public static String suffix(Map<String, Object> otherParam) {
|
||||
if (otherParam == null || !(otherParam.get("auths") instanceof MultiMap auths)) {
|
||||
return null;
|
||||
}
|
||||
String configId = auths.get("_configId");
|
||||
if (configId != null && !configId.isBlank()) {
|
||||
return "cfg-" + digest(configId.trim());
|
||||
}
|
||||
String cookie = CookieUtils.filterUcQuarkCookie(auths.get("cookie"));
|
||||
if (cookie == null || cookie.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return "ck-" + digest(cookie);
|
||||
}
|
||||
|
||||
private static String digest(String value) {
|
||||
try {
|
||||
byte[] hash = MessageDigest.getInstance("SHA-256")
|
||||
.digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder out = new StringBuilder(16);
|
||||
for (int i = 0; i < 8; i++) {
|
||||
out.append(String.format("%02x", hash[i]));
|
||||
}
|
||||
return out.toString();
|
||||
} catch (Exception e) {
|
||||
return Integer.toHexString(value.hashCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class AltchaV2SolverTest {
|
||||
|
||||
private static final String NONCE = "00112233445566778899aabbccddeeff";
|
||||
private static final String SALT = "0102030405060708090a0b0c0d0e0f10";
|
||||
|
||||
@Test
|
||||
public void pbkdf2MatchesAltchaVector() {
|
||||
byte[] password = password(NONCE, 7);
|
||||
byte[] derived = AltchaV2Solver.pbkdf2(password, AltchaV2Solver.decodeHex(SALT, "salt"), 100, 32);
|
||||
assertEquals("dce8b41d12bd8245a12f9fbca56d1d5db2924c1bfe02b924be69f6d89dc1721b",
|
||||
AltchaV2Solver.toHex(derived));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void productionCostMatchesCounterZero() {
|
||||
byte[] derived = AltchaV2Solver.pbkdf2(password(NONCE, 0),
|
||||
AltchaV2Solver.decodeHex(SALT, "salt"), 1200, 32);
|
||||
assertEquals("c24bb34595d0df8688c53e6be3b63e4a0fb0f2d9f732b5c4daebc46fba958bf7",
|
||||
AltchaV2Solver.toHex(derived));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void solverFindsPrefixedCounterAndBuildsPayload() {
|
||||
byte[] derived = AltchaV2Solver.pbkdf2(password(NONCE, 3),
|
||||
AltchaV2Solver.decodeHex(SALT, "salt"), 50, 32);
|
||||
String prefix = AltchaV2Solver.toHex(derived).substring(0, 8);
|
||||
JsonObject challenge = challenge(50, prefix, "sig-test");
|
||||
AltchaV2Solver.Solution solution = AltchaV2Solver.solve(challenge, 20, 5_000);
|
||||
assertEquals(3, solution.counter);
|
||||
assertTrue(solution.derivedKeyHex.startsWith(prefix));
|
||||
|
||||
JsonObject payload = new JsonObject(new String(Base64.getDecoder().decode(AltchaV2Solver.payload(challenge, solution))));
|
||||
assertEquals("sig-test", payload.getJsonObject("challenge").getString("signature"));
|
||||
assertEquals("PBKDF2/SHA-256", payload.getJsonObject("challenge").getJsonObject("parameters").getString("algorithm"));
|
||||
assertEquals(3, payload.getJsonObject("solution").getInteger("counter").intValue());
|
||||
assertEquals(solution.derivedKeyHex, payload.getJsonObject("solution").getString("derivedKey"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void impossiblePrefixStopsAtTheCounterCap() {
|
||||
byte[] beyondCap = AltchaV2Solver.pbkdf2(password(NONCE, 40),
|
||||
AltchaV2Solver.decodeHex(SALT, "salt"), 20, 32);
|
||||
JsonObject challenge = challenge(20, AltchaV2Solver.toHex(beyondCap).substring(0, 8), "sig");
|
||||
try {
|
||||
AltchaV2Solver.solve(challenge, 8, 5_000);
|
||||
fail("expected the search to stop");
|
||||
} catch (IllegalStateException e) {
|
||||
assertTrue(e.getMessage().contains("超时"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsCostAboveTheSafetyCap() {
|
||||
JsonObject challenge = challenge(AltchaV2Solver.MAX_COST + 1, "00", "sig");
|
||||
try {
|
||||
AltchaV2Solver.solve(challenge, 1, 1_000);
|
||||
fail("expected cost to be rejected");
|
||||
} catch (IllegalArgumentException e) {
|
||||
assertTrue(e.getMessage().contains("cost"));
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonObject challenge(int cost, String keyPrefix, String signature) {
|
||||
return new JsonObject()
|
||||
.put("parameters", new JsonObject()
|
||||
.put("algorithm", "PBKDF2/SHA-256")
|
||||
.put("cost", cost)
|
||||
.put("keyLength", 32)
|
||||
.put("nonce", NONCE)
|
||||
.put("salt", SALT)
|
||||
.put("keyPrefix", keyPrefix))
|
||||
.put("signature", signature);
|
||||
}
|
||||
|
||||
private static byte[] password(String nonceHex, int counter) {
|
||||
byte[] nonce = AltchaV2Solver.decodeHex(nonceHex, "nonce");
|
||||
byte[] password = new byte[nonce.length + 4];
|
||||
System.arraycopy(nonce, 0, password, 0, nonce.length);
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.ParserCreate;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.json.JsonArray;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
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.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* 城通真实联调。默认不跑:
|
||||
* mvn -pl parser -DskipTests=false -Dctfile.live=true -Dtest=CtToolLiveTest test
|
||||
*/
|
||||
public class CtToolLiveTest {
|
||||
|
||||
private static final String FREE_FILE = "https://474b.com/file/4015376-131945810";
|
||||
private static final String PASSWORD_FILE =
|
||||
"https://url94.ctfile.com/f/64115194-17569800420720-06c697?p=7609";
|
||||
private static final String PASSWORD_FILE_WITHOUT_PASSWORD =
|
||||
"https://url94.ctfile.com/f/64115194-17569800420720-06c697";
|
||||
private static final String PASSWORD_DIR =
|
||||
"https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609";
|
||||
private static final String PASSWORD_FILE_WRONG =
|
||||
"https://url94.ctfile.com/f/64115194-17569800420720-06c697?p=0000";
|
||||
|
||||
private static Vertx vertx;
|
||||
|
||||
@AfterClass
|
||||
public static void tearDown() throws Exception {
|
||||
CtfileSession.clearCachedPasses();
|
||||
if (vertx != null) {
|
||||
CtTool.shutdownWorkerExecutor();
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void freeFileDownloadsRealPdfBytes() throws Exception {
|
||||
liveOnly();
|
||||
CtTool tool = tool(FREE_FILE);
|
||||
String url = tool.parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
||||
FileInfo info = (FileInfo) tool.getShareLinkInfo().getOtherParam().get("fileInfo");
|
||||
assertNotNull(info);
|
||||
assertTrue(info.getFileName().endsWith(".pdf"));
|
||||
assertTrue(info.getSize() > 1000);
|
||||
assertTrue(url.startsWith("https://"));
|
||||
|
||||
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
|
||||
HttpResponse<byte[]> head = client.send(HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Range", "bytes=0-15")
|
||||
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
assertTrue("head status " + head.statusCode(), head.statusCode() == 206 || head.statusCode() == 200);
|
||||
String magic = new String(head.body(), 0, Math.min(5, head.body().length), StandardCharsets.ISO_8859_1);
|
||||
assertEquals("%PDF-", magic);
|
||||
String range = head.headers().firstValue("content-range").orElse("");
|
||||
String length = head.headers().firstValue("content-length").orElse("");
|
||||
assertTrue(range.endsWith("/" + info.getSize()) || length.equals(String.valueOf(info.getSize()))
|
||||
|| range.contains("/" + info.getSize()));
|
||||
|
||||
long size = info.getSize();
|
||||
HttpResponse<byte[]> tail = client.send(HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Range", "bytes=" + Math.max(0, size - 20) + "-" + (size - 1))
|
||||
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
String ending = new String(tail.body(), StandardCharsets.ISO_8859_1);
|
||||
assertTrue(ending.contains("%%EOF"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sameSessionListsParentDirectory() throws Exception {
|
||||
liveOnly();
|
||||
ShareLinkInfo info = ParserCreate.fromShareUrl(FREE_FILE).getShareLinkInfo();
|
||||
try (CtfileSession session = CtfileSession.open(info)) {
|
||||
JsonObject resource = session.loadResource("file", info.getShareKey(),
|
||||
CtfileSession.ShareTarget.from(info), "", "");
|
||||
JsonObject file = CtfileSession.dataOf(resource).getJsonObject("file");
|
||||
String fileDir = file.getString("file_dir", "");
|
||||
int marker = fileDir.indexOf("/d/");
|
||||
assertTrue(fileDir, marker >= 0);
|
||||
String dirId = fileDir.substring(marker + 3);
|
||||
int query = dirId.indexOf('?');
|
||||
if (query >= 0) {
|
||||
dirId = dirId.substring(0, query);
|
||||
}
|
||||
JsonObject listing = session.listing("dir", dirId, new CtfileSession.ShareTarget("0", "", "0"),
|
||||
"", resource, 0, 20);
|
||||
JsonArray rows = CtfileSession.rowsOf(listing);
|
||||
assertTrue(rows.size() > 0);
|
||||
ShareLinkInfo directory = ShareLinkInfo.newBuilder()
|
||||
.type("ctd")
|
||||
.panName("城通网盘-目录")
|
||||
.shareKey(dirId)
|
||||
.shareUrl("https://474b.com/d/" + dirId)
|
||||
.build();
|
||||
directory.getOtherParam().put("domainName", "https://nfd.example");
|
||||
int named = 0;
|
||||
for (int i = 0; i < rows.size(); i++) {
|
||||
FileInfo item = CtTool.toFileInfo(rows.getJsonObject(i), directory);
|
||||
if (item != null && item.getFileName() != null && !item.getFileName().isBlank()) {
|
||||
named++;
|
||||
assertNotNull(item.getParserUrl());
|
||||
}
|
||||
}
|
||||
assertTrue(named > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void passwordFileDownloadsAnonymously() throws Exception {
|
||||
liveOnly();
|
||||
CtTool tool = tool(PASSWORD_FILE);
|
||||
String url = tool.parse().toCompletionStage().toCompletableFuture().get(120, TimeUnit.SECONDS);
|
||||
FileInfo info = (FileInfo) tool.getShareLinkInfo().getOtherParam().get("fileInfo");
|
||||
assertEquals("欢迎使用微盘.pdf", info.getFileName());
|
||||
assertEquals(Long.valueOf(4005749L), info.getSize());
|
||||
byte[] body = download(url);
|
||||
assertEquals(4005749, body.length);
|
||||
assertTrue(new String(body, 0, 5, StandardCharsets.ISO_8859_1).startsWith("%PDF-"));
|
||||
assertTrue(new String(body, body.length - 16, 16, StandardCharsets.ISO_8859_1).contains("%%EOF"));
|
||||
assertEquals("cce8357689762fd1acd1f73fcd7e83d62b4e9bcee6fccf0c9b8f46d26ee74902", sha256(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void passwordDirectoryListsAndDownloadsZipAnonymously() throws Exception {
|
||||
liveOnly();
|
||||
CtTool directory = tool(PASSWORD_DIR);
|
||||
List<FileInfo> files = directory.parseFileList().toCompletionStage().toCompletableFuture()
|
||||
.get(120, TimeUnit.SECONDS);
|
||||
assertEquals(3, files.size());
|
||||
FileInfo zip = null;
|
||||
for (FileInfo file : files) {
|
||||
assertNotNull(file.getParserUrl());
|
||||
assertTrue(file.getParserUrl().contains("pwd=7609") || decodedParam(file).getString("pwd").equals("7609"));
|
||||
if ("osm_model_20260602_153158.zip".equals(file.getFileName())) {
|
||||
zip = file;
|
||||
}
|
||||
}
|
||||
assertNotNull(zip);
|
||||
assertEquals(Long.valueOf(158842L), zip.getSize());
|
||||
ShareLinkInfo child = ShareLinkInfo.newBuilder()
|
||||
.type("ct")
|
||||
.panName("城通网盘")
|
||||
.shareKey("pending")
|
||||
.shareUrl("https://ctfile.com/file/pending")
|
||||
.build();
|
||||
child.getOtherParam().put("paramJson", decodedParam(zip));
|
||||
child.getOtherParam().put("domainName", "https://nfd.example");
|
||||
CtTool downloader = new CtTool(child);
|
||||
String url = downloader.parseById().toCompletionStage().toCompletableFuture().get(120, TimeUnit.SECONDS);
|
||||
byte[] body = download(url);
|
||||
assertEquals(158842, body.length);
|
||||
assertEquals('P', (char) body[0]);
|
||||
assertEquals('K', (char) body[1]);
|
||||
int entries = 0;
|
||||
try (ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(body))) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zipIn.getNextEntry()) != null) {
|
||||
byte[] ignored = zipIn.readAllBytes();
|
||||
assertTrue(entry.getName() != null);
|
||||
assertTrue(ignored.length >= 0);
|
||||
zipIn.closeEntry();
|
||||
entries++;
|
||||
}
|
||||
}
|
||||
assertTrue(entries > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingPasswordAndMissingShareStayDistinct() throws Exception {
|
||||
liveOnly();
|
||||
String withoutPassword = failure(tool(PASSWORD_FILE_WITHOUT_PASSWORD).parse());
|
||||
assertTrue(withoutPassword, withoutPassword.contains("需要访问密码"));
|
||||
assertFalse(withoutPassword, withoutPassword.contains("未配置城通账号"));
|
||||
|
||||
String wrongPassword = failure(tool(PASSWORD_FILE_WRONG).parse());
|
||||
assertTrue(wrongPassword, wrongPassword.contains("访问密码不正确"));
|
||||
assertFalse(wrongPassword, wrongPassword.contains("未配置城通账号"));
|
||||
|
||||
String missingFile = failure(tool("https://474b.com/file/4015376-1").parse());
|
||||
assertTrue(missingFile, missingFile.contains("不存在或已过期"));
|
||||
|
||||
String missingOwner = failure(tool("https://474b.com/file/0-0").parse());
|
||||
assertTrue(missingOwner, missingOwner.contains("不存在或已过期"));
|
||||
}
|
||||
|
||||
private static JsonObject decodedParam(FileInfo file) {
|
||||
String url = file.getParserUrl();
|
||||
return new JsonObject(decodeUrlBase64(url.substring(url.lastIndexOf('/') + 1)));
|
||||
}
|
||||
|
||||
private static String decodeUrlBase64(String value) {
|
||||
String padded = value;
|
||||
int mod = padded.length() % 4;
|
||||
if (mod != 0) {
|
||||
padded += "=".repeat(4 - mod);
|
||||
}
|
||||
return new String(java.util.Base64.getUrlDecoder().decode(padded), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static byte[] download(String url) throws Exception {
|
||||
HttpResponse<byte[]> response = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(20))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build()
|
||||
.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(120)).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
assertEquals(200, response.statusCode());
|
||||
return response.body();
|
||||
}
|
||||
|
||||
private static String sha256(byte[] body) throws Exception {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(body);
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (byte value : digest) {
|
||||
hex.append(String.format("%02x", value));
|
||||
}
|
||||
return hex.toString();
|
||||
}
|
||||
|
||||
private static void liveOnly() {
|
||||
Assume.assumeTrue("set -Dctfile.live=true to call ctfile", Boolean.getBoolean("ctfile.live"));
|
||||
if (vertx == null) {
|
||||
vertx = Vertx.vertx();
|
||||
WebClientVertxInit.init(vertx);
|
||||
}
|
||||
}
|
||||
|
||||
private static CtTool tool(String url) {
|
||||
return (CtTool) ParserCreate.fromShareUrl(url).createTool();
|
||||
}
|
||||
|
||||
private static String failure(io.vertx.core.Future<?> future) throws Exception {
|
||||
try {
|
||||
future.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
||||
return "";
|
||||
} catch (Exception e) {
|
||||
Throwable current = e;
|
||||
StringBuilder message = new StringBuilder();
|
||||
while (current != null) {
|
||||
if (current.getMessage() != null) {
|
||||
message.append(current.getMessage()).append('\n');
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
if (message.length() == 0) {
|
||||
throw e;
|
||||
}
|
||||
return message.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.impl.CtfileSession.Decision;
|
||||
import cn.qaiu.parser.impl.CtfileSession.Kind;
|
||||
import cn.qaiu.parser.impl.CtfileSession.ShareTarget;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CtfileResponseTest {
|
||||
|
||||
@Test
|
||||
public void classifiesNotFoundInvalidPasswordAndCaptcha() {
|
||||
Decision missing = CtfileSession.classify(json(404, null, "File was not found."), 404, "");
|
||||
assertEquals(Kind.NOT_FOUND, missing.kind);
|
||||
assertTrue(missing.message.contains("不存在或已过期"));
|
||||
assertFalse(missing.message.contains("密码"));
|
||||
|
||||
Decision unsigned = CtfileSession.classify(json(403, null, "Unsigned file link is not accepted."), 403, "");
|
||||
assertEquals(Kind.INVALID, unsigned.kind);
|
||||
|
||||
Decision needPassword = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"captcha_type\":\"turnstile\",\"capabilities\":{\"passcodeRequired\":true}},"
|
||||
+ "\"msg\":\"Share passcode is required.\"}"), 423, "");
|
||||
assertEquals(Kind.NEED_PASSWORD, needPassword.kind);
|
||||
assertTrue(needPassword.message.contains("需要访问密码"));
|
||||
|
||||
Decision wrong = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"error_type\":\"passcode_incorrect\",\"captcha_type\":\"turnstile\","
|
||||
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"incorrect\"}"), 423, "7609");
|
||||
assertEquals(Kind.BAD_PASSWORD, wrong.kind);
|
||||
|
||||
Decision turnstile = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"turnstile\","
|
||||
+ "\"capabilities\":{\"passcodeRequired\":true,\"ownerId\":64115194}},"
|
||||
+ "\"msg\":\"Share passcode needs a new human check.\"}"), 423, "7609");
|
||||
assertEquals(Kind.TURNSTILE, turnstile.kind);
|
||||
assertEquals("64115194", turnstile.ownerId);
|
||||
assertTrue(turnstile.message.contains("Turnstile"));
|
||||
assertFalse(turnstile.message.contains("密码"));
|
||||
|
||||
Decision altcha = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"altcha\","
|
||||
+ "\"capabilities\":{\"passcodeRequired\":false,\"ownerId\":4015376}},"
|
||||
+ "\"msg\":\"Share access needs a human check.\"}"), 423, "");
|
||||
assertEquals(Kind.ALTCHA, altcha.kind);
|
||||
assertEquals("4015376", altcha.ownerId);
|
||||
|
||||
Decision ok = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":200,\"data\":{\"access_pass\":\"v1.aaa.bbb\",\"capabilities\":{\"ownerId\":4015376}}}"), 200, "");
|
||||
assertEquals(Kind.OK, ok.kind);
|
||||
assertEquals("v1.aaa.bbb", ok.accessPass);
|
||||
|
||||
Decision labeledTurnstile = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"turnstile\","
|
||||
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"Share passcode needs a new human check.\"}"),
|
||||
423, "pw");
|
||||
assertTrue(CtfileSession.shouldSolveAltcha(labeledTurnstile));
|
||||
assertFalse(CtfileSession.shouldSolveAltcha(needPassword));
|
||||
Decision wrongAfterAltcha = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"error_type\":\"passcode_incorrect\",\"captcha_type\":\"turnstile\","
|
||||
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"Share passcode is incorrect.\"}"),
|
||||
423, "0000");
|
||||
assertEquals(Kind.BAD_PASSWORD, wrongAfterAltcha.kind);
|
||||
assertFalse(CtfileSession.shouldSolveAltcha(wrongAfterAltcha));
|
||||
|
||||
ShareLinkInfo passwordShare = ShareLinkInfo.newBuilder()
|
||||
.type("ct")
|
||||
.shareKey("11-22-ab")
|
||||
.sharePassword("pw")
|
||||
.shareUrl("https://example.test/f/11-22-ab?p=pw")
|
||||
.build();
|
||||
assertFalse(CtTool.requiresV4(passwordShare));
|
||||
passwordShare.getOtherParam().put("ctV4FileId", "f22");
|
||||
assertTrue(CtTool.requiresV4(passwordShare));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resourceQueryKeepsTokensAndEncodesThem() {
|
||||
Map<String, String> query = CtfileSession.resourceQuery("file", "4015376-131945810",
|
||||
new ShareTarget("0", "", "0"), "7609", "a+b/c=", "turn stile", "v1.aaa.bbb");
|
||||
String form = CtfileSession.form(query);
|
||||
assertTrue(form.contains("kind=file"));
|
||||
assertTrue(form.contains("passcode=7609"));
|
||||
assertTrue(form.contains("altcha_token=a%2Bb%2Fc%3D"));
|
||||
assertTrue(form.contains("turnstile_token=turn+stile") || form.contains("turnstile_token=turn%20stile"));
|
||||
assertTrue(form.contains("access_pass=v1.aaa.bbb"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listingRowBecomesFileAndFolderLinks() {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
||||
.type("ctd")
|
||||
.panName("城通网盘-目录")
|
||||
.shareKey("64115194-164803691-48508c")
|
||||
.sharePassword("7609")
|
||||
.shareUrl("https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609")
|
||||
.build();
|
||||
info.getOtherParam().put("domainName", "https://nfd.example");
|
||||
|
||||
FileInfo folder = CtTool.toFileInfo(new JsonObject()
|
||||
.put("kind", "folder")
|
||||
.put("name", "2022")
|
||||
.put("folderId", 54597713)
|
||||
.put("folderKey", "bf0603")
|
||||
.put("date", "2023-02-22"), info);
|
||||
assertEquals("folder", folder.getFileType());
|
||||
assertTrue(folder.getParserUrl().contains("dirId="));
|
||||
assertTrue(folder.getParserUrl().contains("54597713"));
|
||||
assertTrue(folder.getParserUrl().contains("pwd=7609"));
|
||||
|
||||
FileInfo file = CtTool.toFileInfo(new JsonObject()
|
||||
.put("kind", "file")
|
||||
.put("name", "notes.pdf")
|
||||
.put("href", "#/f/t-token")
|
||||
.put("fileId", 415670738)
|
||||
.put("extension", "pdf")
|
||||
.put("size", "1 MB")
|
||||
.put("size_bytes", 1048576)
|
||||
.put("date", "2019-12-31"), info);
|
||||
assertEquals("t-token", fileId(file));
|
||||
assertEquals(Long.valueOf(1048576L), file.getSize());
|
||||
assertEquals("pdf", file.getFileType());
|
||||
assertTrue(file.getParserUrl().startsWith("https://nfd.example/v2/redirectUrl/ctd/"));
|
||||
}
|
||||
|
||||
private static JsonObject json(int code, JsonObject data, String message) {
|
||||
JsonObject body = new JsonObject().put("code", code).put("msg", message);
|
||||
if (data != null) {
|
||||
body.put("data", data);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
private static String fileId(FileInfo file) {
|
||||
String url = file.getParserUrl();
|
||||
String encoded = url.substring(url.lastIndexOf('/') + 1);
|
||||
return new JsonObject(decodeUrlBase64(encoded)).getString("id");
|
||||
}
|
||||
|
||||
private static String decodeUrlBase64(String value) {
|
||||
String padded = value;
|
||||
int mod = padded.length() % 4;
|
||||
if (mod != 0) {
|
||||
padded += "=".repeat(4 - mod);
|
||||
}
|
||||
byte[] bytes = java.util.Base64.getUrlDecoder().decode(padded);
|
||||
return new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.impl.CtfileV4Client.V4CallException;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CtfileV4Test {
|
||||
|
||||
private static final String FILE_LINK = "xtc11-f22-ab-pw";
|
||||
private static final String DIR_LINK = "xtc11-d33-cd-pw";
|
||||
|
||||
@Test
|
||||
public void webShareBecomesXtlink() {
|
||||
assertEquals(FILE_LINK, CtfileXtlink.fromShare("11-22-ab", "pw", false));
|
||||
assertEquals(DIR_LINK, CtfileXtlink.fromShare("11-33-cd", "pw", true));
|
||||
assertEquals("xturl44-f55", CtfileXtlink.fromShare("44-55", "", false));
|
||||
assertEquals("xturl11-d33-cd", CtfileXtlink.fromShare("11-33-cd", null, true));
|
||||
assertEquals("xtc1-d2-ab-pw", CtfileXtlink.fromShare("xtc1-d2-ab-pw", "other", true));
|
||||
assertNull(CtfileXtlink.fromShare("t-signed", "pw", true));
|
||||
assertEquals("f22", CtfileXtlink.prefixedId("22", false));
|
||||
assertEquals("22", CtfileXtlink.bareId("f22"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestBodiesMatchTheClientProtocol() {
|
||||
JsonObject list = CtfileV4Client.listBody(DIR_LINK, "33", 1, 2);
|
||||
assertEquals(DIR_LINK, list.getString("xtlink"));
|
||||
assertEquals(33L, list.getLong("folder_id").longValue());
|
||||
assertEquals(1, list.getInteger("start").intValue());
|
||||
assertEquals(2, list.getInteger("pagesize").intValue());
|
||||
|
||||
JsonObject auth = CtfileV4Client.authBody(FILE_LINK, "f22");
|
||||
assertEquals("f22", auth.getString("ids"));
|
||||
|
||||
JsonObject fetch = CtfileV4Client.fetchBody(FILE_LINK, "22", "sig");
|
||||
assertEquals("22", fetch.getString("file_id"));
|
||||
assertEquals("sig", fetch.getString("download_sign"));
|
||||
assertEquals(0, fetch.getInteger("carrier").intValue());
|
||||
|
||||
assertFalse(CtfileV4Client.refreshBody("rt", false).containsKey("rotate_token"));
|
||||
assertTrue(CtfileV4Client.refreshBody("rt", true).getBoolean("rotate_token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void errorCodesStaySpecific() {
|
||||
assertTrue(CtfileV4Client.describeFailure(401, "无效或过期的refresh token", "api.auth.invalid_refresh_token")
|
||||
.contains("refresh_token 无效或已过期"));
|
||||
assertTrue(CtfileV4Client.describeFailure(401, "无效的令牌或账户已锁定", "").contains("登录令牌无效或账号已锁定"));
|
||||
assertEquals("城通账号已锁定", CtfileV4Client.describeFailure(401, "账户已锁定", ""));
|
||||
assertEquals("访问密码不正确", CtfileV4Client.describeFailure(403, "访问密码不正确", "api.passcode"));
|
||||
assertTrue(CtfileV4Client.describeFailure(404, "分享不存在", "").contains("不存在或已过期"));
|
||||
assertTrue(CtfileV4Client.describeFailure(401, "请扫码完成登录保护", "qr_required").contains("扫码"));
|
||||
V4CallException invalid = new V4CallException(401, "无效的令牌或账户已锁定", "");
|
||||
assertTrue(invalid.authenticationFailure());
|
||||
assertFalse(new V4CallException(403, "访问密码不正确", "passcode").authenticationFailure());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listRowBecomesDownloadParamWithXtlink() {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
||||
.type("ctd")
|
||||
.panName("城通网盘-目录")
|
||||
.shareKey("11-33-cd")
|
||||
.sharePassword("pw")
|
||||
.shareUrl("https://example.test/d/11-33-cd?p=pw")
|
||||
.build();
|
||||
info.getOtherParam().put("domainName", "https://nfd.example");
|
||||
FileInfo file = CtfileV4Client.toFileInfo(new JsonObject()
|
||||
.put("key", "f22")
|
||||
.put("name", "notes.pdf")
|
||||
.put("icon", "pdf")
|
||||
.put("size", 12)
|
||||
.put("date", "2024-01-02"), info, DIR_LINK);
|
||||
assertEquals("notes.pdf", file.getFileName());
|
||||
assertEquals(Long.valueOf(12L), file.getSize());
|
||||
assertTrue(file.getParserUrl().contains("/v2/redirectUrl/ctd/"));
|
||||
|
||||
JsonObject param = new JsonObject(decode(file.getParserUrl().substring(file.getParserUrl().lastIndexOf('/') + 1)));
|
||||
assertEquals("f22", param.getString("id"));
|
||||
assertEquals(DIR_LINK, param.getString("xtlink"));
|
||||
assertEquals("pw", param.getString("pwd"));
|
||||
|
||||
ShareLinkInfo download = ShareLinkInfo.newBuilder().type("ctd").sharePassword("").build();
|
||||
assertTrue(CtTool.applyFileParam(download, param));
|
||||
assertEquals("f22", download.getOtherParam().get("ctV4FileId"));
|
||||
assertEquals("11-33-cd", download.getShareKey());
|
||||
|
||||
FileInfo folder = CtfileV4Client.toFileInfo(new JsonObject()
|
||||
.put("fid", "d33")
|
||||
.put("name", "2022")
|
||||
.put("is_folder", true), info, DIR_LINK);
|
||||
assertEquals("folder", folder.getFileType());
|
||||
assertTrue(folder.getParserUrl().contains("dirId=33"));
|
||||
assertTrue(folder.getParserUrl().contains("pwd=pw"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void credentialsComeFromAuthsAndDoNotTreatSharePasswordAsLogin() {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
||||
.type("ct")
|
||||
.shareKey("11-22-ab")
|
||||
.sharePassword("pw")
|
||||
.build();
|
||||
assertFalse(CtfileV4Client.hasCredentials(info));
|
||||
MultiMap auths = MultiMap.caseInsensitiveMultiMap();
|
||||
auths.set("refresh_token", "refresh-value");
|
||||
auths.set("authorization", "Bearer access-value");
|
||||
auths.set("_configId", "home");
|
||||
info.getOtherParam().put("auths", auths);
|
||||
CtfileV4Client.Credentials credentials = CtfileV4Client.credentials(info);
|
||||
assertEquals("refresh-value", credentials.refreshToken);
|
||||
assertEquals("access-value", credentials.accessToken);
|
||||
assertTrue(credentials.usable());
|
||||
assertTrue(CtfileV4Client.missingAccountMessage().contains("auths.ct.refresh_token"));
|
||||
}
|
||||
|
||||
private static String decode(String value) {
|
||||
String padded = value;
|
||||
int mod = padded.length() % 4;
|
||||
if (mod != 0) {
|
||||
padded += "=".repeat(4 - mod);
|
||||
}
|
||||
return new String(java.util.Base64.getUrlDecoder().decode(padded), java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@@ -36,12 +37,17 @@ public class QkToolGuestFolderLiveTest {
|
||||
String url = tool.parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
||||
assertNotNull(url);
|
||||
assertTrue(url.startsWith("http"));
|
||||
assertTrue("guest download host, got " + url, url.contains("dl-guest"));
|
||||
FileInfo fileInfo = (FileInfo) info.getOtherParam().get("fileInfo");
|
||||
assertNotNull(fileInfo);
|
||||
assertNotNull(fileInfo.getFileName());
|
||||
assertTrue("expected a small file, got " + fileInfo.getSize() + " " + fileInfo.getFileName(),
|
||||
fileInfo.getSize() > 0 && fileInfo.getSize() < 40L * 1024 * 1024);
|
||||
assertTrue(fileInfo.getSize() > 0);
|
||||
if (fileInfo.getSize() > QuarkFamilyDownloadPolicy.NORMAL_PARSE_MAX_BYTES) {
|
||||
assertTrue("large file should be a public dl-c url, got " + url, url.contains("dl-c-"));
|
||||
assertTrue(url.contains("filename="));
|
||||
assertFalse(url.contains("dl-guest"));
|
||||
} else {
|
||||
assertTrue("guest download host, got " + url, url.contains("dl-guest"));
|
||||
}
|
||||
} finally {
|
||||
if (tool != null) {
|
||||
tool.close();
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.impl.QuarkFamilyDownloadPolicy.Membership;
|
||||
import cn.qaiu.parser.impl.QuarkFamilyDownloadPolicy.ProbeHit;
|
||||
import cn.qaiu.util.QuarkAccountScope;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.json.JsonArray;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.client.WebClient;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* 夸克 / UC 大文件策略。会员、体积、文件名和响应分类不访问网盘。
|
||||
* 本地 HTTP 只验证探测不会收完整文件,以及 HTML / JSON 不会被当成下载。
|
||||
*/
|
||||
public class QuarkFamilyDownloadPolicyTest {
|
||||
|
||||
private static final long NOW = 1_700_000_000_000L;
|
||||
private static final String SECRET = "__pus=super-secret-cookie; __puus=another-secret";
|
||||
|
||||
private static Vertx vertx;
|
||||
private static HttpServer server;
|
||||
private static WebClient client;
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void startServer() throws Exception {
|
||||
vertx = Vertx.vertx();
|
||||
client = WebClient.create(vertx);
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
server = vertx.createHttpServer().requestHandler(req -> {
|
||||
String path = req.path();
|
||||
if ("/member-valid".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end(new JsonObject().put("code", 0).put("data", new JsonObject()
|
||||
.put("member_type", "SUPER_VIP").put("exp_at", 4_102_416_000_000L)).encode());
|
||||
} else if ("/member-auth".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end(new JsonObject().put("code", 31001).put("message", "未登录").encode());
|
||||
} else if ("/member-html".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "text/html").end("<html>login</html>");
|
||||
} else if ("/preview-html".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "text/html; charset=utf-8")
|
||||
.end("<!DOCTYPE html><html><body>preview page</body></html>");
|
||||
} else if ("/preview-missing".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end(new JsonObject().put("code", 0).put("data", new JsonObject()).encode());
|
||||
} else if ("/preview-page".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end(new JsonObject().put("code", 0).put("data", new JsonObject()
|
||||
.put("download_url", "https://vt.quark.cn/preview?foo=1")).encode());
|
||||
} else if ("/zip".equals(path)) {
|
||||
byte[] body = new byte[256 * 1024];
|
||||
body[0] = 'P';
|
||||
body[1] = 'K';
|
||||
req.response().putHeader("Content-Type", "application/zip")
|
||||
.putHeader("Content-Length", Integer.toString(body.length))
|
||||
.end(Buffer.buffer(body));
|
||||
} else if ("/html-file".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "text/html")
|
||||
.end("<html><body>not a file</body></html>");
|
||||
} else if ("/json-file".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end("{\"code\":412,\"message\":\"html-not-file\"}");
|
||||
} else if ("/empty".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "text/plain").putHeader("Content-Length", "0").end();
|
||||
} else if ("/redirect".equals(path)) {
|
||||
req.response().setStatusCode(302).putHeader("Location", "https://pan.quark.cn/login").end();
|
||||
} else {
|
||||
req.response().setStatusCode(404).end();
|
||||
}
|
||||
});
|
||||
server.listen(0).onComplete(ar -> {
|
||||
if (ar.succeeded()) {
|
||||
port = ar.result().actualPort();
|
||||
}
|
||||
latch.countDown();
|
||||
});
|
||||
assertTrue(latch.await(10, TimeUnit.SECONDS));
|
||||
assertTrue(port > 0);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void stopServer() {
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
if (server != null) {
|
||||
server.close();
|
||||
}
|
||||
if (vertx != null) {
|
||||
vertx.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void thresholdKeepsEqualSizeOnNormalPath() {
|
||||
long limit = QuarkFamilyDownloadPolicy.NORMAL_PARSE_MAX_BYTES;
|
||||
assertEquals(10L * 1024 * 1024, limit);
|
||||
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(0));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(limit - 1));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(limit));
|
||||
assertTrue(QuarkFamilyDownloadPolicy.knownLarge(limit + 1));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(Long.MAX_VALUE));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(-1));
|
||||
assertEquals(limit, QuarkFamilyDownloadPolicy.sizeOf(new JsonObject().put("size", limit)));
|
||||
assertEquals(Long.MAX_VALUE, QuarkFamilyDownloadPolicy.sizeOf(new JsonObject()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void membershipRequiresTierAndFutureExpiry() {
|
||||
assertTrue(judge("SUPER_VIP", NOW + 1).validPaid);
|
||||
assertTrue(judge("VIP", NOW + 60_000).validPaid);
|
||||
assertTrue(judge("EXP_SVIP", NOW + 60_000).validPaid);
|
||||
assertTrue(judge("EXP_VIP", NOW + 60_000).validPaid);
|
||||
assertTrue(judge("Z_VIP", NOW + 60_000).validPaid);
|
||||
assertTrue(judge("vip", NOW + 1).validPaid);
|
||||
|
||||
Membership expired = judge("SUPER_VIP", NOW);
|
||||
assertFalse(expired.validPaid);
|
||||
assertTrue(expired.reason.contains("过期"));
|
||||
|
||||
Membership past = judge("VIP", NOW - 1);
|
||||
assertFalse(past.validPaid);
|
||||
|
||||
Membership normal = judge("NORMAL", NOW + 60_000);
|
||||
assertFalse(normal.validPaid);
|
||||
assertTrue(normal.reason.contains("不是"));
|
||||
|
||||
Membership unknown = judge("MINI", NOW + 60_000);
|
||||
assertFalse(unknown.validPaid);
|
||||
|
||||
Membership noType = QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject().put("exp_at", NOW + 1), NOW);
|
||||
assertFalse(noType.validPaid);
|
||||
assertTrue(noType.reason.contains("member_type"));
|
||||
|
||||
Membership noExp = QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject().put("member_type", "SVIP"), NOW);
|
||||
assertFalse(noExp.validPaid);
|
||||
|
||||
Membership missingExp = QuarkFamilyDownloadPolicy.judgeMembership(
|
||||
new JsonObject().put("member_type", "SUPER_VIP"), NOW);
|
||||
assertFalse(missingExp.validPaid);
|
||||
assertTrue(missingExp.reason.contains("exp_at"));
|
||||
|
||||
long seconds = (NOW + 5_000) / 1000;
|
||||
assertTrue(QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject()
|
||||
.put("member_type", "VIP").put("exp_at", seconds), NOW).validPaid);
|
||||
assertNull(QuarkFamilyDownloadPolicy.judgeMembership(null, NOW).memberType);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void memberHttpAuthHtmlAndMissingCookieAreNotPaid() throws Exception {
|
||||
Membership valid = await(QuarkFamilyDownloadPolicy.fetchMembership(client, cookieHeaders(),
|
||||
url("/member-valid"), false));
|
||||
assertTrue(valid.validPaid);
|
||||
assertEquals("SUPER_VIP", valid.memberType);
|
||||
|
||||
Membership auth = await(QuarkFamilyDownloadPolicy.fetchMembership(client, cookieHeaders(),
|
||||
url("/member-auth"), true));
|
||||
assertFalse(auth.validPaid);
|
||||
assertTrue(auth.reason.contains("31001"));
|
||||
|
||||
Membership html = await(QuarkFamilyDownloadPolicy.fetchMembership(client, cookieHeaders(),
|
||||
url("/member-html"), true));
|
||||
assertFalse(html.validPaid);
|
||||
assertTrue(html.reason.contains("HTML"));
|
||||
|
||||
Membership missing = await(QuarkFamilyDownloadPolicy.fetchMembership(client, MultiMap.caseInsensitiveMultiMap(),
|
||||
url("/member-valid"), false));
|
||||
assertFalse(missing.validPaid);
|
||||
assertTrue(missing.reason.contains("未配置"));
|
||||
assertFalse(missing.reason.contains("super-secret"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void previewHtmlMissingAndWebpageAreNotDownloads() throws Exception {
|
||||
String html = awaitFailure(client.getAbs(url("/preview-html")).send()
|
||||
.compose(res -> QuarkFamilyDownloadPolicy.interpretPreview(res, "qk", false)));
|
||||
assertTrue(html.contains("HTML"));
|
||||
|
||||
String missing = awaitFailure(client.getAbs(url("/preview-missing")).send()
|
||||
.compose(res -> QuarkFamilyDownloadPolicy.interpretPreview(res, "uc", false)));
|
||||
assertTrue(missing.contains("download_url"));
|
||||
|
||||
String page = await(client.getAbs(url("/preview-page")).send()
|
||||
.compose(res -> QuarkFamilyDownloadPolicy.interpretPreview(res, "qk", false)));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl(page, "qk"));
|
||||
assertTrue(page.contains("vt.quark.cn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void publicCdnHostsAreSeparateForQuarkAndUc() {
|
||||
String quark = "https://dl-c-zb-u.drive.quark.cn/a/b?auth_key=1&sp=100&token=t&abt=9";
|
||||
String uc = "https://dl-c-zb.drive.uc.cn/a/b?auth_key=1&sp=100&token=t";
|
||||
assertTrue(QuarkFamilyDownloadPolicy.isPublicFileUrl(quark, "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl(quark, "uc"));
|
||||
assertTrue(QuarkFamilyDownloadPolicy.isPublicFileUrl(uc, "uc"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl(uc, "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://dl-c-sz.u-drive.quark.cn/a", "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://dl-pc.sz.drive.quark.cn/a", "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://dl-guest-1.drive.quark.cn/a", "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://vt.quark.cn/preview", "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://drive.uc.cn/s/abc", "uc"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("http://dl-c-zb.drive.uc.cn/a", "uc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filenameUsesUtf8AndDropsTrackingParams() throws Exception {
|
||||
String raw = "https://dl-c-zb.drive.quark.cn/a/b?auth_key=9&abt=1&sp=100&token=abc&filename=old";
|
||||
String bare = QuarkFamilyDownloadPolicy.bareFileUrl(raw);
|
||||
assertFalse(bare.contains("abt="));
|
||||
assertFalse(bare.contains("filename="));
|
||||
String named = QuarkFamilyDownloadPolicy.withFilename(bare, "报告 (1).zip");
|
||||
assertTrue(named.contains("filename="));
|
||||
assertFalse(named.contains("报告"));
|
||||
String value = named.substring(named.indexOf("filename=") + "filename=".length());
|
||||
assertEquals("报告 (1).zip", URLDecoder.decode(value, StandardCharsets.UTF_8));
|
||||
assertFalse(value.contains(" "));
|
||||
assertFalse(value.contains("+"));
|
||||
String fromAccount = QuarkFamilyDownloadPolicy.presentPublicDownload(raw, "qk", "报告 (1).zip");
|
||||
assertTrue(fromAccount.contains("filename="));
|
||||
assertFalse(fromAccount.contains("abt="));
|
||||
assertEquals("https://dl-pc.sz.drive.quark.cn/a?auth_key=1",
|
||||
QuarkFamilyDownloadPolicy.presentPublicDownload(
|
||||
"https://dl-pc.sz.drive.quark.cn/a?auth_key=1", "qk", "a.zip"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void videoPickerKeepsProgressiveFileAndDropsPlaylist() {
|
||||
JsonObject data = new JsonObject().put("video_list", new JsonArray()
|
||||
.add(new JsonObject().put("video_info", new JsonObject()
|
||||
.put("width", 1920)
|
||||
.put("url", "https://dl-c-zb.drive.quark.cn/high.m3u8?auth_key=1&token=t")))
|
||||
.add(new JsonObject().put("video_info", new JsonObject()
|
||||
.put("width", 1280)
|
||||
.put("url", "https://dl-pc.sz.drive.quark.cn/login.mp4?auth_key=1")))
|
||||
.add(new JsonObject().put("video_info", new JsonObject()
|
||||
.put("width", 640)
|
||||
.put("url", "https://dl-c-sz.drive.quark.cn/low.mp4?auth_key=2&token=t&abt=1"))));
|
||||
assertEquals("https://dl-c-sz.drive.quark.cn/low.mp4?auth_key=2&token=t&abt=1",
|
||||
QuarkFamilyDownloadPolicy.pickProgressiveFileUrl(data, "qk"));
|
||||
assertEquals("", QuarkFamilyDownloadPolicy.pickProgressiveFileUrl(new JsonObject()
|
||||
.put("download_url", "https://pan.quark.cn/s/abc"), "qk"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void probeRejectsHtmlJsonAndEmptyAndCapsZipPrefix() throws Exception {
|
||||
ProbeHit zip = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/zip"), "qk", 1));
|
||||
assertTrue(zip.ok);
|
||||
assertTrue(zip.prefixLength > 0);
|
||||
assertTrue(zip.prefixLength <= 64);
|
||||
|
||||
ProbeHit html = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/html-file"), "qk", 1));
|
||||
assertFalse(html.ok);
|
||||
assertTrue(html.reason.contains("HTML"));
|
||||
|
||||
ProbeHit json = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/json-file"), "uc", 1));
|
||||
assertFalse(json.ok);
|
||||
assertTrue(json.reason.contains("JSON"));
|
||||
|
||||
ProbeHit empty = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/empty"), "qk", 1));
|
||||
assertFalse(empty.ok);
|
||||
|
||||
ProbeHit redirect = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/redirect"), "qk", 1));
|
||||
assertFalse(redirect.ok);
|
||||
assertTrue(redirect.reason.contains("不是公开文件"));
|
||||
|
||||
ProbeHit rangedHtml = QuarkFamilyDownloadPolicy.judgeProbe(206, "text/html", "bytes 0-0/9", "1",
|
||||
Buffer.buffer("<html>"));
|
||||
assertFalse(rangedHtml.ok);
|
||||
ProbeHit rangedZip = QuarkFamilyDownloadPolicy.judgeProbe(206, "application/zip", "bytes 0-15/99", null,
|
||||
Buffer.buffer("PK"));
|
||||
assertTrue(rangedZip.ok);
|
||||
ProbeHit denied = QuarkFamilyDownloadPolicy.judgeProbe(412, "text/html", null, null, Buffer.buffer("<html>"));
|
||||
assertFalse(denied.ok);
|
||||
assertTrue(denied.reason.contains("412"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void errorsStayActionableAndHideSecrets() {
|
||||
RuntimeException leaked = new RuntimeException("失败 cookie=" + SECRET + " <html>login</html>");
|
||||
String uc = QuarkFamilyDownloadPolicy.largeFileError("uc", leaked,
|
||||
new IllegalStateException("H5 预览没有 download_url"));
|
||||
String qk = QuarkFamilyDownloadPolicy.largeFileError("qk", null,
|
||||
new IllegalStateException("<!DOCTYPE html>"));
|
||||
assertTrue(uc.contains("不能免登录"));
|
||||
assertTrue(uc.contains("auths.uc.cookie"));
|
||||
assertTrue(uc.contains("10MiB"));
|
||||
assertFalse(uc.contains("super-secret"));
|
||||
assertFalse(uc.contains("<html"));
|
||||
assertTrue(qk.contains("auths.qk.cookie"));
|
||||
assertTrue(qk.contains("HTML"));
|
||||
assertFalse(qk.contains("免登录下载"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void publicDirectDropsAccountHeaders() {
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
headers.put("cookie", SECRET);
|
||||
headers.put("Referer", "https://pan.quark.cn/");
|
||||
assertFalse(QuarkFamilyDownloadPolicy.prepareDownloader(headers, true, true));
|
||||
assertTrue(headers.isEmpty());
|
||||
|
||||
Map<String, String> account = new LinkedHashMap<>();
|
||||
account.put("cookie", "account-cookie");
|
||||
assertTrue(QuarkFamilyDownloadPolicy.prepareDownloader(account, true, false));
|
||||
assertEquals("account-cookie", account.get("cookie"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accountCacheScopeDoesNotReuseAnotherCookie() {
|
||||
Map<String, Object> guest = new HashMap<>();
|
||||
assertNull(QuarkAccountScope.suffix(guest));
|
||||
|
||||
Map<String, Object> first = authParam(SECRET);
|
||||
Map<String, Object> second = authParam("__pus=other-account; __uid=2");
|
||||
Map<String, Object> same = authParam(SECRET);
|
||||
String a = QuarkAccountScope.suffix(first);
|
||||
String b = QuarkAccountScope.suffix(second);
|
||||
assertEquals(a, QuarkAccountScope.suffix(same));
|
||||
assertNotEquals(a, b);
|
||||
assertFalse(a.contains("super-secret"));
|
||||
assertFalse(b.contains("__pus"));
|
||||
|
||||
ShareLinkInfo guestInfo = share("qk", guest);
|
||||
ShareLinkInfo accountInfo = share("qk", first);
|
||||
ShareLinkInfo otherInfo = share("UC", second);
|
||||
assertEquals("qk:key", guestInfo.getCacheKey());
|
||||
assertTrue(accountInfo.getCacheKey().startsWith("qk:key#"));
|
||||
assertNotEquals(accountInfo.getCacheKey(), otherInfo.getCacheKey().replace("UC:", "qk:"));
|
||||
assertFalse(accountInfo.getCacheKey().contains("super-secret"));
|
||||
assertFalse(otherInfo.getCacheKey().contains("other-account"));
|
||||
}
|
||||
|
||||
private static Membership judge(String type, long expAt) {
|
||||
return QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject()
|
||||
.put("member_type", type).put("exp_at", expAt), NOW);
|
||||
}
|
||||
|
||||
private static MultiMap cookieHeaders() {
|
||||
return MultiMap.caseInsensitiveMultiMap().set("cookie", SECRET);
|
||||
}
|
||||
|
||||
private static String url(String path) {
|
||||
return "http://127.0.0.1:" + port + path;
|
||||
}
|
||||
|
||||
private static Map<String, Object> authParam(String cookie) {
|
||||
MultiMap auths = MultiMap.caseInsensitiveMultiMap().set("cookie", cookie);
|
||||
Map<String, Object> other = new HashMap<>();
|
||||
other.put("auths", auths);
|
||||
return other;
|
||||
}
|
||||
|
||||
private static ShareLinkInfo share(String type, Map<String, Object> other) {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().type(type).shareKey("key").build();
|
||||
info.setOtherParam(other);
|
||||
return info;
|
||||
}
|
||||
|
||||
private static <T> T await(io.vertx.core.Future<T> future) throws Exception {
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
AtomicReference<T> value = new AtomicReference<>();
|
||||
AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
future.onComplete(ar -> {
|
||||
if (ar.succeeded()) {
|
||||
value.set(ar.result());
|
||||
} else {
|
||||
error.set(ar.cause());
|
||||
}
|
||||
latch.countDown();
|
||||
});
|
||||
assertTrue(latch.await(10, TimeUnit.SECONDS));
|
||||
if (error.get() != null) {
|
||||
throw new AssertionError(error.get().getMessage(), error.get());
|
||||
}
|
||||
return value.get();
|
||||
}
|
||||
|
||||
private static String awaitFailure(io.vertx.core.Future<?> future) throws Exception {
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
future.onComplete(ar -> {
|
||||
if (ar.failed()) {
|
||||
error.set(ar.cause());
|
||||
}
|
||||
latch.countDown();
|
||||
});
|
||||
assertTrue(latch.await(10, TimeUnit.SECONDS));
|
||||
assertTrue(error.get() != null);
|
||||
return error.get().getMessage() == null ? "" : error.get().getMessage();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* 永硕入口页解析与重定向的离线测试,不访问网络。
|
||||
*/
|
||||
public class YsToolPasswordPageTest {
|
||||
|
||||
private static final String NEW_GATE = ""
|
||||
+ "<div id=\"entryConfig\" style=\"display:none\" data-dlmc=\"qaiu\"\n"
|
||||
+ " data-verification-token=\"new-token_value.1\"></div>\n"
|
||||
+ "<form id=\"loginForm\"></form>\n";
|
||||
|
||||
private static final String OLD_GATE = ""
|
||||
+ "<script>var cfg = { RequestVerificationToken': 'legacy-token' };</script>\n"
|
||||
+ "<div id=\"loginPopup\"></div>\n"
|
||||
+ "<form action=\"/?handler=VerifyPassword\"></form>\n";
|
||||
|
||||
private static final String OPEN_SPACE = ""
|
||||
+ "<script>window.htxx = {\"dlmc\":\"fufu1\",\"qqdz\":\"https://c6.ysepan.com/api/\","
|
||||
+ "\"yh\":{\"isgly\":false},\"ym\":\"ysepan.com\"};</script>";
|
||||
|
||||
@Test
|
||||
public void testNewPasswordPageTokenAndDlmc() {
|
||||
assertTrue(YsTool.isPasswordPage(NEW_GATE));
|
||||
assertEquals("new-token_value.1", YsTool.extractAntiforgery(NEW_GATE));
|
||||
assertEquals("qaiu", YsTool.extractDlmc(NEW_GATE));
|
||||
assertNull(YsTool.extractHtxx(NEW_GATE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLegacyPasswordPageStillParsed() {
|
||||
assertTrue(YsTool.isPasswordPage(OLD_GATE));
|
||||
assertEquals("legacy-token", YsTool.extractAntiforgery(OLD_GATE));
|
||||
assertNull(YsTool.extractDlmc(OLD_GATE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNewTokenWinsWhenBothFormatsExist() {
|
||||
String mixed = NEW_GATE + OLD_GATE;
|
||||
assertEquals("new-token_value.1", YsTool.extractAntiforgery(mixed));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSingleQuotedAttributes() {
|
||||
String html = "<div id='entryConfig' data-dlmc='sohehe4' "
|
||||
+ "data-verification-token='quoted-token'></div>";
|
||||
assertTrue(YsTool.isPasswordPage(html));
|
||||
assertEquals("quoted-token", YsTool.extractAntiforgery(html));
|
||||
assertEquals("sohehe4", YsTool.extractDlmc(html));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOpenSpaceIsNotPasswordPageAndKeepsNestedHtxx() {
|
||||
assertFalse(YsTool.isPasswordPage(OPEN_SPACE));
|
||||
JsonObject htxx = YsTool.extractHtxx(OPEN_SPACE);
|
||||
assertEquals("fufu1", htxx.getString("dlmc"));
|
||||
assertEquals("https://c6.ysepan.com/api/", htxx.getString("qqdz"));
|
||||
assertFalse(htxx.getJsonObject("yh").getBoolean("isgly"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testYs168RedirectTargetsYsepanPasswordEndpoint() {
|
||||
String next = YsTool.resolveRedirect("https://qaiu.ys168.com/", "https://qaiu.ysepan.com");
|
||||
assertEquals("https://qaiu.ysepan.com", next);
|
||||
assertEquals("https://qaiu.ysepan.com", YsTool.originOf(next));
|
||||
assertEquals("https://qaiu.ysepan.com/?handler=VerifyPassword",
|
||||
YsTool.verifyPasswordEndpoint(YsTool.originOf(next)));
|
||||
assertFalse(YsTool.verifyPasswordEndpoint(YsTool.originOf(next)).contains("ys168.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProtocolRelativeAndRelativeRedirects() {
|
||||
String protocolRelative = YsTool.resolveRedirect(
|
||||
"https://qaiu.ys168.com/", "//qaiu.ysepan.com/");
|
||||
assertEquals("https://qaiu.ysepan.com/", protocolRelative);
|
||||
assertEquals("https://qaiu.ysepan.com", YsTool.originOf(protocolRelative));
|
||||
|
||||
String relative = YsTool.resolveRedirect(
|
||||
"https://qaiu.ysupan.com/", "/login.aspx?d=qaiu");
|
||||
assertEquals("https://qaiu.ysupan.com/login.aspx?d=qaiu", relative);
|
||||
assertEquals("https://qaiu.ysupan.com", YsTool.originOf(relative));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonDefaultPortKeptInOrigin() {
|
||||
assertEquals("https://y.ys168.com:8100", YsTool.originOf("https://y.ys168.com:8100/"));
|
||||
assertEquals("https://qaiu.ysepan.com", YsTool.originOf("https://qaiu.ysepan.com:443/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrongPasswordUsesUpstreamMessageWithoutSecrets() {
|
||||
String body = "{\"success\":false,\"code\":\"invalid_password\",\"message\":\"密码错误\"}";
|
||||
assertEquals("密码错误", YsTool.passwordFailureMessage(400, body));
|
||||
|
||||
String leaked = "{\"success\":false,\"code\":\"invalid_password\",\"message\":\"eyJhbGciOiJIUzI1NiJ9.secret\"}";
|
||||
assertEquals("密码错误", YsTool.passwordFailureMessage(400, leaked));
|
||||
|
||||
String other = "{\"success\":false,\"message\":\"空间已关闭\"}";
|
||||
assertEquals("空间已关闭", YsTool.passwordFailureMessage(400, other));
|
||||
|
||||
assertEquals("密码验证失败 HTTP 500", YsTool.passwordFailureMessage(500, "<html>CfDJ8secret</html>"));
|
||||
assertEquals("密码验证失败 HTTP 400", YsTool.passwordFailureMessage(400, ""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBlankRedirectIsRejected() {
|
||||
assertNull(YsTool.resolveRedirect("https://qaiu.ys168.com/", " "));
|
||||
assertNull(YsTool.resolveRedirect("https://qaiu.ys168.com/", null));
|
||||
assertNull(YsTool.originOf("not a url"));
|
||||
assertFalse(YsTool.isPasswordPage(null));
|
||||
assertNull(YsTool.extractAntiforgery(null));
|
||||
}
|
||||
}
|
||||
@@ -97,23 +97,13 @@ public class YsToolTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOfficialSampleUrlRealDownload() throws Exception {
|
||||
String official = "https://ys-l.ysepan.com/wap/yssl/A95UIe495EkSKE/Bc8hF8Nsbl2I4Ec6vAm5EGe9HU36iC/lu20.jpg";
|
||||
String withForcePrefix = "https://ys-l.ysepan.com/wap/yssl/_A95UIe495EkSKE/Bc8hF8Nsbl2I4Ec6vAm5EGe9HU36iC/lu20.jpg";
|
||||
|
||||
Buffer ok = download(official, "https://yssl.ysepan.com/");
|
||||
assertTrue("官方直链应能下载到 JPEG", ok.length() > 1000);
|
||||
assertEquals((byte) 0xFF, ok.getByte(0));
|
||||
assertEquals((byte) 0xD8, ok.getByte(1));
|
||||
|
||||
int forceStatus = webClient.getAbs(withForcePrefix)
|
||||
.putHeader("User-Agent", "Mozilla/5.0")
|
||||
.putHeader("Referer", "https://yssl.ysepan.com/")
|
||||
.send()
|
||||
.toCompletionStage().toCompletableFuture()
|
||||
.get(30, TimeUnit.SECONDS)
|
||||
.statusCode();
|
||||
assertNotEquals("带 _ 前缀的直链应失败(文件不存在)", 200, forceStatus);
|
||||
public void testYsslOpenSpaceRealDownload() throws Exception {
|
||||
// 旧样例 lu20.jpg 已从示例空间删除(直链 404)。改为现场列出示例空间里的小文件再下载。
|
||||
FileInfo file = firstSmallFile("https://yssl.ysepan.com/", null, 2_000_000);
|
||||
assertNotNull("示例空间应至少有一个可下载的小文件", file);
|
||||
Buffer body = downloadParsedFile(file, "https://yssl.ysepan.com/");
|
||||
assertEquals(file.getSize().longValue(), body.length());
|
||||
System.out.println("yssl real download ok, file=" + file.getFileName() + ", size=" + body.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -249,46 +239,175 @@ public class YsToolTest {
|
||||
assertTrue("sohehe4 应有多个目录", dirs.size() >= 3);
|
||||
assertTrue(dirs.stream().allMatch(d -> "folder".equals(d.getFileType())));
|
||||
|
||||
String dirId = dirs.stream()
|
||||
.filter(d -> d.getFileName() != null && d.getFileName().contains("留言"))
|
||||
.map(FileInfo::getFileId)
|
||||
FileInfo file = null;
|
||||
for (FileInfo dir : dirs) {
|
||||
if (!"folder".equals(dir.getFileType())) {
|
||||
continue;
|
||||
}
|
||||
file = firstSmallFileInDir("https://sohehe4.ysepan.com/", "1234", dir.getFileId(), 5_000_000);
|
||||
if (file != null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertNotNull("sohehe4 应能找到可下载的小文件", file);
|
||||
Buffer body = downloadParsedFile(file, "https://sohehe4.ysepan.com/");
|
||||
assertEquals(file.getSize().longValue(), body.length());
|
||||
System.out.println("sohehe4 real download ok, file=" + file.getFileName()
|
||||
+ ", size=" + body.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQaiuRequiresPassword() throws Exception {
|
||||
ParserCreate create = ParserCreate.fromShareUrl("https://qaiu.ysepan.com/");
|
||||
create.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
|
||||
try {
|
||||
create.createTool().parseFileList()
|
||||
.toCompletionStage().toCompletableFuture()
|
||||
.get(60, TimeUnit.SECONDS);
|
||||
fail("未提供密码时应拒绝进入");
|
||||
} catch (java.util.concurrent.ExecutionException e) {
|
||||
assertTrue(e.getCause().getMessage(), e.getCause().getMessage().contains("空间需要访问密码"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFufu1Ys168RedirectOpenSpace() throws Exception {
|
||||
List<FileInfo> roots = fileList("https://fufu1.ys168.com/", null);
|
||||
assertNotNull(roots);
|
||||
assertTrue(roots.stream().anyMatch(f -> "游戏3".equals(f.getFileName())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testQaiuYs168PasswordRedirectAndRealDownload() throws Exception {
|
||||
List<FileInfo> dirs = fileList("https://qaiu.ys168.com/", "qaiuys168");
|
||||
assertNotNull(dirs);
|
||||
assertFalse(dirs.isEmpty());
|
||||
FileInfo app = dirs.stream()
|
||||
.filter(d -> d.getFileName() != null && d.getFileName().contains("app"))
|
||||
.findFirst()
|
||||
.orElse(dirs.get(0).getFileId());
|
||||
.orElse(dirs.get(0));
|
||||
|
||||
ParserCreate filesCreate = ParserCreate.fromShareUrl("https://sohehe4.ysepan.com/");
|
||||
filesCreate.getShareLinkInfo().setSharePassword("1234");
|
||||
filesCreate.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
|
||||
filesCreate.getShareLinkInfo().getOtherParam().put("dirId", dirId);
|
||||
|
||||
List<FileInfo> files = filesCreate.createTool().parseFileList()
|
||||
.toCompletionStage().toCompletableFuture()
|
||||
.get(60, TimeUnit.SECONDS);
|
||||
|
||||
assertNotNull(files);
|
||||
assertFalse(files.isEmpty());
|
||||
|
||||
FileInfo file = files.stream()
|
||||
List<FileInfo> files = fileList("https://qaiu.ys168.com/", "qaiuys168", app.getFileId());
|
||||
FileInfo zip = files.stream()
|
||||
.filter(f -> "file".equals(f.getFileType()))
|
||||
.filter(f -> f.getSize() != null && f.getSize() > 0 && f.getSize() < 5_000_000)
|
||||
.filter(f -> f.getFileName() != null && f.getFileName().contains("Pycharm"))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (file != null) {
|
||||
String param = file.getParserUrl().substring(file.getParserUrl().lastIndexOf('/') + 1);
|
||||
JsonObject paramJson = new JsonObject(CommonUtils.urlBase64Decode(param));
|
||||
String downloadUrl = paramJson.getString("downloadUrl");
|
||||
assertNotNull(downloadUrl);
|
||||
assertFalse(downloadUrl.contains("/_"));
|
||||
assertNotNull("ys168 重定向后应能列出 Pycharm 压缩包", zip);
|
||||
|
||||
Buffer body = download(downloadUrl, "https://sohehe4.ysepan.com/");
|
||||
assertEquals(file.getSize().longValue(), body.length());
|
||||
System.out.println("sohehe4 real download ok, file=" + file.getFileName()
|
||||
+ ", size=" + body.length());
|
||||
} else {
|
||||
System.out.println("sohehe4 dir=" + dirId + " entries=" + files.size()
|
||||
+ " (no small file for real download sample)");
|
||||
String param = zip.getParserUrl().substring(zip.getParserUrl().lastIndexOf('/') + 1);
|
||||
JsonObject paramJson = new JsonObject(CommonUtils.urlBase64Decode(param));
|
||||
String downloadUrl = paramJson.getString("downloadUrl");
|
||||
assertNotNull(downloadUrl);
|
||||
assertTrue(downloadUrl.contains("ysepan.com"));
|
||||
assertFalse(downloadUrl.contains("ys168.com"));
|
||||
assertFalse(downloadUrl.contains("/_"));
|
||||
|
||||
Buffer body = download(downloadUrl, "https://qaiu.ysepan.com/");
|
||||
assertEquals(zip.getSize().longValue(), body.length());
|
||||
assertEquals('P', (char) body.getByte(0));
|
||||
assertEquals('K', (char) body.getByte(1));
|
||||
System.out.println("qaiu ys168 redirect download ok, size=" + body.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBackupDomainsOpenAndPasswordSpaces() throws Exception {
|
||||
for (String host : new String[]{"cccpan.com", "uupan.net", "ysok.net"}) {
|
||||
List<FileInfo> openDirs = fileList("https://fufu1." + host + "/", null);
|
||||
assertNotNull(host, openDirs);
|
||||
assertFalse(host + " 无密码空间目录为空", openDirs.isEmpty());
|
||||
assertTrue(host, openDirs.stream().anyMatch(d -> "游戏3".equals(d.getFileName())));
|
||||
|
||||
List<FileInfo> lockedDirs = fileList("https://qaiu." + host + "/", "qaiuys168");
|
||||
assertNotNull(host, lockedDirs);
|
||||
assertFalse(host + " 密码空间目录为空", lockedDirs.isEmpty());
|
||||
assertTrue(host + " " + lockedDirs.stream().map(FileInfo::getFileName).toList(),
|
||||
lockedDirs.stream().anyMatch(d -> d.getFileName() != null && d.getFileName().contains("app")));
|
||||
}
|
||||
}
|
||||
|
||||
private static List<FileInfo> fileList(String url, String pwd) throws Exception {
|
||||
return fileList(url, pwd, null, null);
|
||||
}
|
||||
|
||||
private static List<FileInfo> fileList(String url, String pwd, String dirId) throws Exception {
|
||||
return fileList(url, pwd, dirId, null);
|
||||
}
|
||||
|
||||
private static List<FileInfo> fileList(String url, String pwd, String dirId, String zml) throws Exception {
|
||||
ParserCreate create = ParserCreate.fromShareUrl(url);
|
||||
if (pwd != null) {
|
||||
create.getShareLinkInfo().setSharePassword(pwd);
|
||||
}
|
||||
create.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
|
||||
if (dirId != null) {
|
||||
create.getShareLinkInfo().getOtherParam().put("dirId", dirId);
|
||||
}
|
||||
if (zml != null) {
|
||||
create.getShareLinkInfo().getOtherParam().put("zml", zml);
|
||||
}
|
||||
return create.createTool().parseFileList()
|
||||
.toCompletionStage().toCompletableFuture()
|
||||
.get(60, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/** 在目录及其 zml 子目录中找一个体积合适的真实文件。 */
|
||||
private static FileInfo firstSmallFile(String url, String pwd, long maxSize) throws Exception {
|
||||
List<FileInfo> dirs = fileList(url, pwd);
|
||||
assertNotNull(dirs);
|
||||
assertFalse(url + " 目录为空", dirs.isEmpty());
|
||||
for (FileInfo dir : dirs) {
|
||||
if (!"folder".equals(dir.getFileType())) {
|
||||
continue;
|
||||
}
|
||||
FileInfo file = firstSmallFileInDir(url, pwd, dir.getFileId(), maxSize);
|
||||
if (file != null) {
|
||||
return file;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static FileInfo firstSmallFileInDir(String url, String pwd, String dirId, long maxSize) throws Exception {
|
||||
List<FileInfo> entries = fileList(url, pwd, dirId);
|
||||
FileInfo direct = smallFile(entries, maxSize);
|
||||
if (direct != null) {
|
||||
return direct;
|
||||
}
|
||||
for (FileInfo entry : entries) {
|
||||
if (!"folder".equals(entry.getFileType()) || entry.getFileId() == null
|
||||
|| !entry.getFileId().contains(":")) {
|
||||
continue;
|
||||
}
|
||||
FileInfo nested = smallFile(fileList(url, pwd, dirId, entry.getFileName()), maxSize);
|
||||
if (nested != null) {
|
||||
return nested;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static FileInfo smallFile(List<FileInfo> entries, long maxSize) {
|
||||
if (entries == null) {
|
||||
return null;
|
||||
}
|
||||
return entries.stream()
|
||||
.filter(f -> "file".equals(f.getFileType()))
|
||||
.filter(f -> f.getSize() != null && f.getSize() > 0 && f.getSize() < maxSize)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private static Buffer downloadParsedFile(FileInfo file, String referer) throws Exception {
|
||||
assertNotNull(file.getParserUrl());
|
||||
String param = file.getParserUrl().substring(file.getParserUrl().lastIndexOf('/') + 1);
|
||||
JsonObject paramJson = new JsonObject(CommonUtils.urlBase64Decode(param));
|
||||
String downloadUrl = paramJson.getString("downloadUrl");
|
||||
assertNotNull(downloadUrl);
|
||||
assertFalse(downloadUrl.contains("/_"));
|
||||
return download(downloadUrl, referer);
|
||||
}
|
||||
|
||||
private static Buffer download(String url, String referer) throws Exception {
|
||||
return webClient.getAbs(url)
|
||||
.putHeader("User-Agent",
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<revision>0.4.9</revision>
|
||||
<revision>0.4.11</revision>
|
||||
<java.version>17</java.version>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nfd-web",
|
||||
"version": "0.4.9",
|
||||
"version": "0.4.11",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"serve": "vue-cli-service serve",
|
||||
|
||||
@@ -455,6 +455,7 @@ import fileTypeUtils from '@/utils/fileTypeUtils'
|
||||
import DownloadDialog from '@/components/DownloadDialog.vue'
|
||||
import { testConnection, autoDetect, addDownload, batchAddDownload, getConfig, saveConfig } from '@/utils/downloaderService'
|
||||
import batchTreeCollect from '@/utils/batchTreeCollect'
|
||||
import { openNoReferrer } from '@/utils/openNoReferrer'
|
||||
|
||||
const {
|
||||
DEFAULT_BATCH_MAX_DEPTH,
|
||||
@@ -758,13 +759,7 @@ export default {
|
||||
// 下载文件
|
||||
downloadFile(file) {
|
||||
if (file?.parserUrl) {
|
||||
const a = document.createElement('a')
|
||||
a.href = this.appendToken(file.parserUrl)
|
||||
a.target = '_blank'
|
||||
a.rel = 'noopener noreferrer'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
openNoReferrer(this.appendToken(file.parserUrl))
|
||||
this.$message.success('开始下载文件')
|
||||
} else {
|
||||
this.$message.warning('该文件暂无下载链接')
|
||||
@@ -805,14 +800,7 @@ export default {
|
||||
this.downloadInfo = info
|
||||
this.downloadDialogVisible = true
|
||||
} else if (info.downloadUrl) {
|
||||
// 服务端判断不需要下载器,直接跳转
|
||||
const a = document.createElement('a')
|
||||
a.href = info.downloadUrl
|
||||
a.target = '_blank'
|
||||
a.rel = 'noopener noreferrer'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
openNoReferrer(info.downloadUrl)
|
||||
this.$message.success('开始下载文件')
|
||||
} else {
|
||||
this.downloadFile(file)
|
||||
@@ -948,14 +936,7 @@ export default {
|
||||
},
|
||||
openPreviewInNewTab() {
|
||||
if (this.previewUrl) {
|
||||
// 使用动态 a 标签并设置 noopener noreferrer 以避免携带 Referer,绕过防盗链机制
|
||||
const a = document.createElement('a')
|
||||
a.href = this.previewUrl
|
||||
a.target = '_blank'
|
||||
a.rel = 'noopener noreferrer'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
openNoReferrer(this.previewUrl)
|
||||
}
|
||||
},
|
||||
hasValidTime(value) {
|
||||
@@ -1237,14 +1218,8 @@ export default {
|
||||
this.batchProgress = { current: 0, total: files.length, failed: 0 }
|
||||
for (const file of files) {
|
||||
try {
|
||||
const a = document.createElement('a')
|
||||
const rawUrl = file.parserUrl.startsWith('http') ? file.parserUrl : (window.location.origin + file.parserUrl)
|
||||
a.href = this.appendToken(rawUrl)
|
||||
a.target = '_blank'
|
||||
a.rel = 'noopener noreferrer'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
openNoReferrer(this.appendToken(rawUrl))
|
||||
await new Promise(r => setTimeout(r, 500))
|
||||
} catch {
|
||||
this.batchProgress.failed++
|
||||
|
||||
@@ -105,6 +105,7 @@
|
||||
|
||||
<script>
|
||||
import { testConnection, addDownload, getConfig, hasCookieHeader, hasCustomUaHeader } from '@/utils/downloaderService'
|
||||
import { openNoReferrer } from '@/utils/openNoReferrer'
|
||||
|
||||
export default {
|
||||
name: 'DownloadDialog',
|
||||
@@ -193,13 +194,7 @@ export default {
|
||||
/** 直接打开下载链接(可能因缺请求头而失败) */
|
||||
doDirectDownload() {
|
||||
if (this.info && this.info.downloadUrl) {
|
||||
const a = document.createElement('a')
|
||||
a.href = this.info.downloadUrl
|
||||
a.target = '_blank'
|
||||
a.rel = 'noopener noreferrer'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
openNoReferrer(this.info.downloadUrl)
|
||||
this.dialogVisible = false
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 在用户点击里打开地址,并且不带 Referer。
|
||||
* 夸克 / UC 的公开文件 CDN 遇到站点 Referer 会返回 403 HTML。
|
||||
* 使用 referrerpolicy="no-referrer" 的链接,而不是只依赖 window.open 的特征字符串。
|
||||
*/
|
||||
export function openNoReferrer(url) {
|
||||
if (!url) return
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.target = '_blank'
|
||||
a.rel = 'noreferrer noopener'
|
||||
a.referrerPolicy = 'no-referrer'
|
||||
a.style.display = 'none'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
const PAN_NAMES = {
|
||||
qk: '夸克网盘',
|
||||
uc: 'UC网盘',
|
||||
lz: '蓝奏云',
|
||||
iz: '蓝奏云优享',
|
||||
fj: '小飞机盘',
|
||||
ye: '123云盘',
|
||||
ec: '移动云空间',
|
||||
le: '联想乐云',
|
||||
qqsc: 'QQ闪传',
|
||||
pic: 'iCloud'
|
||||
}
|
||||
|
||||
/** 与专业版摘要一致:169.1 M,而不是 169.1MB。 */
|
||||
function formatByteSize(bytes) {
|
||||
const value = Number(bytes)
|
||||
if (!Number.isFinite(value) || value < 0) return ''
|
||||
const units = ['B', 'K', 'M', 'G', 'T']
|
||||
let size = value
|
||||
let index = 0
|
||||
while (size >= 1024 && index < units.length - 1) {
|
||||
size /= 1024
|
||||
index += 1
|
||||
}
|
||||
const text = index === 0 ? String(Math.round(size)) : size.toFixed(1)
|
||||
return `${text} ${units[index]}`
|
||||
}
|
||||
|
||||
function panDisplayName(panType, panList) {
|
||||
const type = String(panType || '').toLowerCase()
|
||||
if (!type) return ''
|
||||
const found = (panList || []).find(item => String(item.type || '').toLowerCase() === type)
|
||||
if (found && found.name) return found.name
|
||||
return PAN_NAMES[type] || type
|
||||
}
|
||||
|
||||
/** 单文件解析成功摘要:文件名、大小、网盘类型。 */
|
||||
function buildParseFileMeta({ fileName, size, sizeStr, panType, panList } = {}) {
|
||||
const meta = []
|
||||
if (fileName) meta.push(String(fileName))
|
||||
const sizeText = sizeStr || formatByteSize(size)
|
||||
if (sizeText) meta.push(sizeText)
|
||||
const pan = panDisplayName(panType, panList)
|
||||
if (pan) meta.push(pan)
|
||||
return meta
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
formatByteSize,
|
||||
panDisplayName,
|
||||
buildParseFileMeta
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const { buildParseFileMeta, formatByteSize, panDisplayName } = require('./parseResultMeta.js')
|
||||
|
||||
test('formats binary size like 169.1 M', () => {
|
||||
assert.equal(formatByteSize(0), '0 B')
|
||||
assert.equal(formatByteSize(169.1 * 1024 * 1024), '169.1 M')
|
||||
assert.equal(formatByteSize(10 * 1024 * 1024), '10.0 M')
|
||||
})
|
||||
|
||||
test('builds filename, size and pan tag', () => {
|
||||
assert.deepEqual(buildParseFileMeta({
|
||||
fileName: '末世冰潮.apk',
|
||||
sizeStr: '169.1 M',
|
||||
panType: 'lz',
|
||||
panList: [{ type: 'lz', name: '蓝奏云' }]
|
||||
}), ['末世冰潮.apk', '169.1 M', '蓝奏云'])
|
||||
})
|
||||
|
||||
test('falls back to quark and uc names', () => {
|
||||
assert.equal(panDisplayName('qk', []), '夸克网盘')
|
||||
assert.equal(panDisplayName('UC', []), 'UC网盘')
|
||||
assert.deepEqual(buildParseFileMeta({
|
||||
fileName: 'bilitools_1.4.7_amd64.AppImage',
|
||||
size: 92899832,
|
||||
panType: 'qk'
|
||||
})[2], '夸克网盘')
|
||||
})
|
||||
|
||||
test('omits missing fields', () => {
|
||||
assert.deepEqual(buildParseFileMeta({}), [])
|
||||
assert.deepEqual(buildParseFileMeta({ fileName: 'a.txt' }), ['a.txt'])
|
||||
})
|
||||
@@ -75,8 +75,8 @@
|
||||
<div class="project-intro">
|
||||
<div class="intro-title">NFD网盘直链解析 {{ projectVersion }}</div>
|
||||
<div class="intro-desc">
|
||||
<div>支持网盘:蓝奏云、蓝奏云优享、小飞机盘、123云盘、iCloud、移动云空间、联想乐云、QQ闪传等 <el-link style="color:#606cf5" :href="githubRepoUrl + '?tab=readme-ov-file#%E7%BD%91%E7%9B%98%E6%94%AF%E6%8C%81%E6%83%85%E5%86%B5'" target="_blank"> >> </el-link></div>
|
||||
<div>文件夹解析支持:蓝奏云、蓝奏云优享、小飞机盘、123云盘</div>
|
||||
<div>支持网盘:蓝奏云、蓝奏云优享、小飞机盘、123云盘、夸克网盘、UC网盘、iCloud、移动云空间、联想乐云、QQ闪传等 <el-link style="color:#606cf5" :href="githubRepoUrl + '?tab=readme-ov-file#%E7%BD%91%E7%9B%98%E6%94%AF%E6%8C%81%E6%83%85%E5%86%B5'" target="_blank"> >> </el-link></div>
|
||||
<div>文件夹解析支持:蓝奏云、蓝奏云优享、小飞机盘、123云盘、夸克网盘、UC网盘</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="typo">
|
||||
@@ -122,7 +122,12 @@
|
||||
|
||||
<!-- 解析结果 -->
|
||||
<div v-if="parseResult.code" style="margin-top: 10px">
|
||||
<strong>解析结果: </strong>
|
||||
<strong :style="parseResult.code === 200 ? 'color:var(--el-color-success)' : 'color:var(--el-color-danger)'">
|
||||
{{ parseResult.code === 200 ? '解析成功' : '解析失败' }}
|
||||
</strong>
|
||||
<span v-if="parseResult.code === 200 && parsedFileMeta.length" class="parse-file-meta">
|
||||
<el-tag v-for="item in parsedFileMeta" :key="item" size="small" type="info" effect="plain">{{ item }}</el-tag>
|
||||
</span>
|
||||
<json-viewer :value="parseResult" :expand-depth="5" copyable boxed sort />
|
||||
<!-- 下载链接卡片 -->
|
||||
<div v-if="downloadUrl" style="margin-top: 15px;">
|
||||
@@ -416,6 +421,12 @@
|
||||
|
||||
<!-- 目录树组件 -->
|
||||
<div v-if="showDirectoryTree" class="directory-tree-container">
|
||||
<div v-if="folderParseMeta.length" style="margin-bottom: 10px;">
|
||||
<strong style="color:var(--el-color-success)">解析成功</strong>
|
||||
<span class="parse-file-meta">
|
||||
<el-tag v-for="item in folderParseMeta" :key="item" size="small" type="info" effect="plain">{{ item }}</el-tag>
|
||||
</span>
|
||||
</div>
|
||||
<div style="margin-bottom: 10px; text-align: right;">
|
||||
<ViewModeSwitch v-model="directoryViewMode" pane-label="窗格" tree-label="文件树" />
|
||||
</div>
|
||||
@@ -619,6 +630,8 @@ import DirectoryTree from '@/components/DirectoryTree'
|
||||
import ViewModeSwitch from '@/components/ViewModeSwitch'
|
||||
import DownloadDialog from '@/components/DownloadDialog'
|
||||
import parserUrl from '../parserUrl1'
|
||||
import { openNoReferrer } from '../utils/openNoReferrer'
|
||||
import parseResultMeta from '../utils/parseResultMeta'
|
||||
import fileTypeUtils from '@/utils/fileTypeUtils'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { playgroundApi } from '@/utils/playgroundApi'
|
||||
@@ -750,6 +763,27 @@ export default {
|
||||
projectVersion() {
|
||||
return process.env.VUE_APP_VERSION || '0.0.0'
|
||||
},
|
||||
parsedFileMeta() {
|
||||
const data = this.parseResult?.data || {}
|
||||
const info = data.fileInfo || data.otherParam?.fileInfo || {}
|
||||
const panType = info.panType || data.panType || ''
|
||||
return parseResultMeta.buildParseFileMeta({
|
||||
fileName: info.fileName,
|
||||
size: info.size,
|
||||
sizeStr: info.sizeStr,
|
||||
panType,
|
||||
panList: this.panList
|
||||
})
|
||||
},
|
||||
folderParseMeta() {
|
||||
if (!this.showDirectoryTree) return []
|
||||
const meta = [`${this.directoryData.length} 个文件/文件夹`]
|
||||
const recognized = parserUrl.parseLink(this.link || '')
|
||||
const panType = this.getCurrentPanType()
|
||||
const name = recognized?.name || (panType ? parseResultMeta.panDisplayName(panType.toLowerCase(), this.panList) : '')
|
||||
if (name) meta.push(name)
|
||||
return meta
|
||||
},
|
||||
// 检查是否配置了认证信息(针对当前链接的网盘类型)
|
||||
hasAuthConfig() {
|
||||
const panType = this.getCurrentPanType()
|
||||
@@ -770,15 +804,22 @@ export default {
|
||||
}
|
||||
return map[this.aria2ConfigForm.downloaderType] || 'Aria2'
|
||||
},
|
||||
// 需要下载器(带 cookie 等特殊头)时禁用浏览器下载/复制直链;UC/夸克始终需要
|
||||
// 带 Cookie 的直链浏览器带不上,仍走下载器。
|
||||
// 夸克 / UC 的公开 H5 文件地址没有 Cookie,允许浏览器打开;文件名在 URL 的 filename 上
|
||||
// (跨域时 a[download] 无效,不能靠它改名)。
|
||||
needsDownloader() {
|
||||
const pan = (this.getCurrentPanType() || '').toLowerCase()
|
||||
if (pan === 'uc' || pan === 'qk') return true
|
||||
const data = this.parseResult?.data
|
||||
const pan = (this.getCurrentPanType() || '').toLowerCase()
|
||||
const headers = data && (data.downloadHeaders || data.otherParam?.downloadHeaders)
|
||||
const hasCookie = !!(headers && (headers.cookie || headers.Cookie))
|
||||
if (pan === 'uc' || pan === 'qk') {
|
||||
if (!data) return true
|
||||
if (hasCookie) return true
|
||||
return !!(data.needDownloader || data.otherParam?.needDownloader)
|
||||
}
|
||||
if (!data) return false
|
||||
if (data.needDownloader || data.otherParam?.needDownloader) return true
|
||||
const headers = data.downloadHeaders || data.otherParam?.downloadHeaders
|
||||
return !!(headers && (headers.cookie || headers.Cookie))
|
||||
return hasCookie
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
@@ -1423,7 +1464,7 @@ export default {
|
||||
// 文件点击处理
|
||||
handleFileClick(file) {
|
||||
if (file.parserUrl) {
|
||||
window.open(file.parserUrl, '_blank', 'noopener,noreferrer')
|
||||
openNoReferrer(file.parserUrl)
|
||||
} else {
|
||||
this.$message.warning('该文件暂无下载链接')
|
||||
}
|
||||
@@ -1860,7 +1901,7 @@ export default {
|
||||
}
|
||||
},
|
||||
openUrl(url) {
|
||||
if (url) window.open(url, '_blank', 'noopener,noreferrer')
|
||||
openNoReferrer(url)
|
||||
},
|
||||
async loadDirectoryParseSupportedPans() {
|
||||
try {
|
||||
@@ -2134,6 +2175,13 @@ hr {
|
||||
font-size: 0.98rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.parse-file-meta {
|
||||
margin-left: 10px;
|
||||
display: inline-flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.dark-theme .project-intro, .dark-theme .intro-title, .dark-theme .intro-desc {
|
||||
color: #bbb;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<div class="file-meta-info-card">
|
||||
<div class="file-meta-row">
|
||||
<span class="file-meta-label">下载链接:</span>
|
||||
<a :href="downloadUrl" target="_blank" class="file-meta-link">点击下载</a>
|
||||
<a :href="downloadUrl" target="_blank" rel="noreferrer noopener" referrerpolicy="no-referrer" class="file-meta-link">点击下载</a>
|
||||
</div>
|
||||
<div class="file-meta-row">
|
||||
<span class="file-meta-label">文件名:</span>{{ fileTypeUtils.extractFileNameAndExt(downloadUrl).name }}
|
||||
|
||||
@@ -598,6 +598,8 @@ GET /v2/redirectUrl/pan/eyJmaWxlSWQiOiIxMjM0NTYifQ==
|
||||
- 小飞机盘 (fj)
|
||||
- 360亿方云 (fc)
|
||||
- 联想乐云 (le)
|
||||
- 夸克网盘 (qk)
|
||||
- UC网盘 (uc)
|
||||
- 文叔叔 (ws)
|
||||
- Cloudreve (ce)
|
||||
- 等等...
|
||||
|
||||
@@ -54,6 +54,7 @@ public class AppMain {
|
||||
deploy.addPostShutdownTask(cn.qaiu.parser.PanBase::shutdownSharedClients);
|
||||
deploy.addPostShutdownTask(cn.qaiu.parser.IPanTool::shutdownCloseAfterScheduler);
|
||||
deploy.addPostShutdownTask(cn.qaiu.parser.impl.PodTool::shutdownWorkerExecutor);
|
||||
deploy.addPostShutdownTask(cn.qaiu.parser.impl.CtTool::shutdownWorkerExecutor);
|
||||
// start
|
||||
deploy.start(args, AppMain::exec);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import cn.qaiu.lz.web.service.DbService;
|
||||
import cn.qaiu.parser.PanDomainTemplate;
|
||||
import cn.qaiu.parser.IPanTool;
|
||||
import cn.qaiu.parser.ParserCreate;
|
||||
import cn.qaiu.parser.impl.QuarkFamilyDownloadPolicy;
|
||||
import cn.qaiu.parser.clientlink.ClientLinkGeneratorFactory;
|
||||
import cn.qaiu.parser.clientlink.ClientLinkType;
|
||||
import cn.qaiu.util.CommonUtils;
|
||||
@@ -318,8 +319,9 @@ public class ParserApi {
|
||||
}
|
||||
}
|
||||
|
||||
boolean needDownloader = Boolean.TRUE.equals(paramJson.getBoolean("needDownloader"))
|
||||
|| !downloadHeaders.isEmpty();
|
||||
boolean publicDirect = Boolean.TRUE.equals(shareLinkInfo.getOtherParam().get("publicDirectLink"));
|
||||
boolean needDownloader = QuarkFamilyDownloadPolicy.prepareDownloader(downloadHeaders,
|
||||
Boolean.TRUE.equals(paramJson.getBoolean("needDownloader")), publicDirect);
|
||||
|
||||
shareLinkInfo.getOtherParam().put("downloadUrl", downloadUrl);
|
||||
if (!downloadHeaders.isEmpty()) {
|
||||
|
||||
@@ -145,3 +145,12 @@ auths:
|
||||
username:
|
||||
password:
|
||||
# authorization:
|
||||
# 城通:免密和带访问密码的分享都先匿名解 ALTCHA,通常不用登录。
|
||||
# 只有匿名结果仍是 Turnstile 时,下面的令牌才会作为可选回退。
|
||||
# 浏览器打开 https://pan.ctfile.com 并登录,F12 → Application → Session Storage,
|
||||
# 复制 refresh_token。token 可空,填了就当作当前 access token,过期后用 refresh_token 刷新。
|
||||
# 刷新若轮换了 refresh_token,进程内会写回这份配置和 TokenCache;重启前请把新值保存回本文件。
|
||||
# 目录分享类型是 ctd,这里只配 ct 也会被目录解析回退使用。
|
||||
# ct:
|
||||
# refresh_token:
|
||||
# token:
|
||||
Reference in new issue
Block a user