mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-11-25 14:57:00 +00:00
Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7d41b0107 | ||
|
|
24c22fad7f | ||
|
|
a86b26d668 | ||
|
|
5781100905 | ||
|
|
04ba9a0e2c | ||
|
|
3825527519 | ||
|
|
531f431faa | ||
|
|
44b023d919 | ||
|
|
5681d3b805 | ||
|
|
8c07c6e657 | ||
|
|
25888661ad | ||
|
|
b6922b152f | ||
|
|
572c5a61fc | ||
|
|
dec6cf496f | ||
|
|
98a043daf9 | ||
|
|
12d0f6bfbb | ||
|
|
9d2fd09331 | ||
|
|
d692416a2e | ||
|
|
e9be9b3345 | ||
|
|
6acb774c87 | ||
|
|
511515cae4 | ||
|
|
1ab9df7826 | ||
|
|
ab8b687837 | ||
|
|
7616bf3144 | ||
|
|
01d7956de5 | ||
|
|
78e53c076e | ||
|
|
4d985cc96f | ||
|
|
13ccdb8adf | ||
|
|
ac1afcd35f | ||
|
|
0c678a4124 | ||
|
|
f77800602d | ||
|
|
79ab829952 | ||
|
|
2181ef38df | ||
|
|
e09c9f76a7 | ||
|
|
7adb938357 | ||
|
|
efb800d88e | ||
|
|
422d5b845b | ||
|
|
054e9cc1ec | ||
|
|
f3da45bb16 | ||
|
|
273dbae5e7 | ||
|
|
e103003b7a | ||
|
|
e853365fe4 | ||
|
|
b5f7d9694b | ||
|
|
f75d9f687b | ||
|
|
703bfa3061 | ||
|
|
6c709fde65 | ||
|
|
449fd741ac | ||
|
|
c18b8d80e1 | ||
|
|
06ba0aff52 | ||
|
|
74e401d99c | ||
|
|
4995bca901 |
No files matched your search
@@ -8,7 +8,7 @@ on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
- 'v*'
|
||||
branches-ignore:
|
||||
- '*'
|
||||
paths-ignore:
|
||||
@@ -52,6 +52,24 @@ jobs:
|
||||
- name: Maven 编译打包
|
||||
run: mvn -B package -DskipTests --file pom.xml
|
||||
|
||||
- name: Base64 兼容性回归测试
|
||||
if: github.event_name == 'pull_request'
|
||||
run: >-
|
||||
mvn -B test -DskipTests=false
|
||||
-Dtest=Base64DecoderTest,HttpProxyBase64Test,Base64CompatibilityTest
|
||||
-Dsurefire.failIfNoSpecifiedTests=false
|
||||
-DargLine=-XX:-UseBASE64Intrinsics
|
||||
--file pom.xml
|
||||
|
||||
- name: Base64 SIMD 兼容性回归测试
|
||||
if: github.event_name == 'pull_request'
|
||||
run: >-
|
||||
mvn -B test -DskipTests=false
|
||||
-Dtest=Base64DecoderTest,HttpProxyBase64Test,Base64CompatibilityTest
|
||||
-Dsurefire.failIfNoSpecifiedTests=false
|
||||
"-DargLine=--add-modules=jdk.incubator.vector -XX:-UseBASE64Intrinsics -Dnfd.test.requireVector=true"
|
||||
--file pom.xml
|
||||
|
||||
- name: 更新依赖图谱
|
||||
uses: advanced-security/maven-dependency-submission-action@v3
|
||||
if: github.event_name != 'pull_request'
|
||||
@@ -262,9 +280,27 @@ jobs:
|
||||
name: ${{ matrix.artifact-name }}
|
||||
path: ${{ matrix.artifact-name }}.zip
|
||||
|
||||
- name: 上传到 Release
|
||||
# ================================================================
|
||||
# 阶段三:创建 GitHub Release(只跑一次,避免矩阵任务重复拼接更新日志)
|
||||
# ================================================================
|
||||
publish-release:
|
||||
name: 发布 GitHub Release
|
||||
needs: native-package
|
||||
if: github.event_name != 'pull_request' && github.ref_type == 'tag'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 下载原生安装包
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: netdisk-fast-download-*
|
||||
merge-multiple: true
|
||||
|
||||
- name: 创建 Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: ${{ matrix.artifact-name }}.zip
|
||||
files: |
|
||||
netdisk-fast-download-linux-amd64.zip
|
||||
netdisk-fast-download-windows-amd64.zip
|
||||
tag_name: ${{ github.ref_name }}
|
||||
generate_release_notes: true
|
||||
fail_on_unmatched_files: true
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
FROM eclipse-temurin:17-jre
|
||||
ARG JAVA_RUNTIME_IMAGE=eclipse-temurin:17-jre
|
||||
FROM ${JAVA_RUNTIME_IMAGE}
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
@@ -18,9 +18,11 @@ QQ交流群:1017480890
|
||||

|
||||
|
||||
|
||||
> 本平台所有音乐解析工具不再维护,请移步[Sonder播放器](https://sodecode.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/)
|
||||
@@ -28,25 +30,31 @@ QQ交流群:1017480890
|
||||
[公益解析,lz0站](https://lz0.qaiu.top)
|
||||
[专业版](https://189.qaiu.top)
|
||||
|
||||
|
||||
## 快速开始
|
||||
命令行下载分享文件:
|
||||
```shell
|
||||
curl -LOJ "https://lz.qaiu.top/parser?url=https://share.feijipan.com/s/Tk1F2kGQ&pwd=1234"
|
||||
```
|
||||
或者使用wget:
|
||||
```shell
|
||||
wget -O bilibili.mp4 "https://lz.qaiu.top/parser?url=https://share.feijipan.com/s/Tk1F2kGQ&pwd=1234"
|
||||
```
|
||||
或者使用浏览器[直接访问](https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fparser%3Furl%3Dhttps%3A%2F%2Fwww.ilanzou.com%2Fs%2FCDx6xKbT&name=bilibili.mp4&ext=mp4):
|
||||
```
|
||||
### 调用演示站下载:
|
||||
https://lz.qaiu.top/parser?url=https://www.ilanzou.com/s/CDx6xKbT&pwd=1234
|
||||
### 调用演示站预览:
|
||||
https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fparser%3Furl%3Dhttps%3A%2F%2Fwww.ilanzou.com%2Fs%2FCDx6xKbT&name=bilibili.mp4&ext=mp4
|
||||
|
||||
以带提取码的分享链接为例(提取码 `1234`),链接中含 `#`、`&`,作为 `url` 参数传入前必须做 URL 编码:
|
||||
|
||||
`https://www.ecpan.cn/web/#/yunpanProxy?path=%2F%23%2Fdrive%2Foutside&data=70017ece572737b12b30709b7f029308eJD0&isShare=1`
|
||||
|
||||
**命令行下载**
|
||||
|
||||
```shell
|
||||
# curl
|
||||
curl -LOJ "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%23%2FyunpanProxy%3Fpath%3D%252F%2523%252Fdrive%252Foutside%26data%3D70017ece572737b12b30709b7f029308eJD0%26isShare%3D1&pwd=1234"
|
||||
|
||||
# wget
|
||||
wget -O v01 "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%23%2FyunpanProxy%3Fpath%3D%252F%2523%252Fdrive%252Foutside%26data%3D70017ece572737b12b30709b7f029308eJD0%26isShare%3D1&pwd=1234"
|
||||
```
|
||||
|
||||
**短链方式**(key 取分享链接的 `data` 参数,提取码用 `@` 拼接)
|
||||
|
||||
| 用途 | 地址 |
|
||||
| --- | --- |
|
||||
| 下载 | `https://lz.qaiu.top/ec/70017ece572737b12b30709b7f029308eJD0@1234` |
|
||||
| 在线预览 | [点击访问](https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fec%2F70017ece572737b12b30709b7f029308eJD0%401234&name=v01&ext=mp4) |
|
||||
|
||||
> 无提取码时去掉 `&pwd=1234` / `@1234` 即可;预览页 `src` 需编码(`@` → `%40`),用短链可避免二次编码。
|
||||
|
||||
**解析器模块文档:** [parser/README.md](parser/README.md)
|
||||
|
||||
**JavaScript解析器文档:** [JavaScript解析器开发指南](parser/doc/JAVASCRIPT_PARSER_GUIDE.md) | [自定义解析器扩展指南](parser/doc/CUSTOM_PARSER_GUIDE.md) | [快速开始](parser/doc/CUSTOM_PARSER_QUICKSTART.md)
|
||||
@@ -69,9 +77,11 @@ https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.
|
||||
- [移动云云空间-ec](https://www.ecpan.cn/web)
|
||||
- [小飞机网盘-fj](https://www.feijipan.com/)
|
||||
- [亿方云-fc](https://www.fangcloud.com/)
|
||||
- [123云盘-ye](https://www.123pan.com/) ⚠️仅建议本地部署使用,需登录认证,公共/云端服务器风控严格建议自行部署(Windows 可直接用 run.bat 一键运行)
|
||||
- [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)
|
||||
@@ -93,9 +103,9 @@ https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.
|
||||
- Dropbox-pdp
|
||||
- iCloud-pic
|
||||
### 专业版提供
|
||||
- 迅雷网盘-xl
|
||||
- [夸克云盘-qk](https://pan.quark.cn/)
|
||||
- [UC云盘-uc](https://fast.uc.cn/)
|
||||
- 百度网盘开放平台-bd
|
||||
- 迅雷云盘开放平台-xl
|
||||
- [光鸭云盘开放平台-gy](https://www.guangyapan.com)
|
||||
- [移动云盘-p139](https://yun.139.com/)
|
||||
- [联通云盘-pwo](https://pan.wo.cn/)
|
||||
- [天翼云盘-p189](https://cloud.189.cn/)
|
||||
@@ -133,6 +143,7 @@ GET /json/parser?url={分享链接}&pwd={密码}
|
||||
```
|
||||
GET /json/{网盘标识}/{分享key}@{密码}
|
||||
```
|
||||
注意: 移动云云空间的 `分享key` 取分享链接中的 `data` 参数值
|
||||
|
||||
#### 3. 文件夹解析(v0.1.8fixed3+)
|
||||
|
||||
@@ -149,7 +160,7 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
|
||||
|
||||
### 认证参数(v0.2.1+)
|
||||
[可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
|
||||
部分网盘(如夸克、UC)需要登录后的 Cookie 才能解析和下载。可通过 `auth` 参数传递认证信息:
|
||||
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。可通过 `auth` 参数传递认证信息:
|
||||
|
||||
**参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码
|
||||
|
||||
@@ -173,11 +184,11 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
|
||||
**网盘认证要求**:
|
||||
| 网盘 | 认证要求 | 说明 |
|
||||
|------|---------|------|
|
||||
| 夸克网盘(QK) | **必须** | 必须配置 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) | 可选 | 需要下载大文件/需要登录的分享时才需要认证,支持账号密码或 token/authorization |
|
||||
| 123网盘(YE) | 下载通常需要 | 分享列表经常可以不登录读取。下载接口常见 5112 / 请登录后下载 / 您需要注册登录或付费后下载,请在**本机**配置 `auths.ye.authorization`(与 `token` 等价)或账号密码。公共云解析没有共享 123 账号。约 10MB 小文件有时可以直链,大文件和风控必须用你自己的账号。短链:`ye:分享key@提取码`;`#` 片段会去掉;`yun.123pan.com`、`www.123pan.com`、`*.share.123pan.cn` 同一类 |
|
||||
|
||||
**使用示例**:
|
||||
```
|
||||
@@ -227,14 +238,13 @@ auths:
|
||||
```
|
||||
|
||||
> ⚠️ 注意:YAML 中 key 后面不写值(如 `authorization:` 空着)等同于没配置,不会生效,必须填入真实的账号密码或 token 内容。
|
||||
>
|
||||
> 若 123 云盘账号密码登录触发验证码或风控,解析会直接失败并提示改用 Authorization,不会尝试验证码。请改填上面的 `authorization` / `token`(浏览器 localStorage 的 `authorToken`,或请求头 `authorization` / Cookie `sso-token` 里的 JWT)。
|
||||
>
|
||||
> 公共解析站(例如别人搭的在线解析)不能替你登录 123。看到「请登录后下载」「5112」「您需要注册登录或付费后下载」时,把服务跑在自己的机器上并填入自己的 Authorization。这是 123 的登录和风控要求。链接写法:`/d/ye/分享key@提取码`;浏览器地址栏里 `#` 后面的片段不参与解析;`yun.123pan.com` 与 `www.123pan.com`、`数字.share.123pan.cn` 是同一种分享。
|
||||
|
||||
如果只是临时调用一次,不想改动服务端配置,也可以用上面提到的 `auth` 参数临时传递(`authType` 可选 `password`/`accesstoken`/`authorization`),无需重启服务,仅本次请求生效。
|
||||
|
||||
### 特殊说明
|
||||
|
||||
- 移动云云空间的 `分享key` 取分享链接中的 `data` 参数值
|
||||
- 移动云云空间、小飞机网盘的加密分享可忽略密码参数
|
||||
|
||||
### 示例
|
||||
|
||||
```bash
|
||||
@@ -369,14 +379,19 @@ json返回数据格式示例:
|
||||
| 移动云云空间(个人版) | √ | √(密码可忽略) | 5G(个人) | 不限大小 |
|
||||
| 小飞机网盘 | √ | √ | 10G | 不限大小 |
|
||||
| 360亿方云 | √ | √ | 100G(须实名) | 不限大小 |
|
||||
| 123云盘 | √ | √ | 2T | 100G(>100M需要登录) |
|
||||
| 123云盘 | 小文件有时可以 | √ | 2T | 大文件/风控需要本机登录 |
|
||||
| 文叔叔 | √ | √ | 10G | 5GB |
|
||||
| 永硕E盘 | √ | √(空间密码) | 视套餐 | 视套餐 |
|
||||
| WPS云文档 | √ | X | 5G(免费) | 10M(免费)/2G(会员) |
|
||||
| 夸克网盘 | x | √ | 10G | 不限大小 |
|
||||
| UC网盘 | x | √ | 10G | 不限大小 |
|
||||
| 夸克网盘 | ≤10MiB 原解析 | √ | 10G | 更大文件要有效 SVIP/VIP,或可用的 H5 文件地址 |
|
||||
| UC网盘 | x | √ | 10G | 不能免登录;大文件规则同夸克 |
|
||||
| 飞书云盘 | √ | X | 15G | 不限大小 |
|
||||
|
||||
免登录边界(阈值由网盘决定,不是本项目写死的):
|
||||
|
||||
- **夸克 / UC**:单文件体积阈值是 `10 * 1024 * 1024` 字节(10MiB)。小于或等于该值保持原来的解析。严格大于该值时,先请求会员接口,只把 `member_type` 为 `SUPER_VIP`、`EXP_SVIP`、`Z_VIP`、`VIP`、`EXP_VIP` 且 `exp_at` 仍在未来的账号当作有效 SVIP/VIP,并走原来的账号直链。缺少档位、普通账号、已过期或只有 Cookie 都不会当成会员。没有有效会员时,才使用 H5 预览返回的 `https://dl-c-*.drive.quark.cn` 或 `https://dl-c-*.drive.uc.cn` 文件地址,并加上真实 `filename`(含中文)。预览网页、HTML、JSON、m3u8 不会当作下载成功。UC 不能免登录。目录列表不变。百度大约 100MB 以内有直链,属于专业版,这次没有改解析器。
|
||||
- **123**:分享目录经常可以不登录看。下载则经常要登录。请本机配置 Authorization,不要依赖公共云解析的共享账号。约 10MB 的小文件有时能直链。
|
||||
|
||||
# 打包部署
|
||||
|
||||
## JDK下载(lz.qaiu.top提供直链云解析服务)
|
||||
@@ -455,8 +470,8 @@ 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/v3.0.2/netdisk-fast-download-bin.zip
|
||||
unzip netdisk-fast-download-bin.zip
|
||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.10/netdisk-fast-download-linux-amd64.zip
|
||||
unzip netdisk-fast-download.zip
|
||||
cd netdisk-fast-download
|
||||
bash service-install.sh
|
||||
```
|
||||
@@ -512,7 +527,7 @@ nfd-proxy搭建http代理服务器
|
||||
参考https://github.com/nfd-parser/nfd-proxy
|
||||
|
||||
### 认证信息配置说明
|
||||
部分网盘(如123)解析大文件时需要登录认证,可以在配置文件中添加认证信息。
|
||||
夸克不超过 10MiB 可以不登录;更大的文件要本机未过期的 SVIP/VIP Cookie,或上游确实返回了可下载的 H5 文件地址。UC 不能免登录。123 的下载在公共解析站上基本都要你自己的 Authorization,云端没有共用账号。
|
||||
|
||||
修改配置文件:
|
||||
app-dev.yml
|
||||
@@ -520,14 +535,19 @@ app-dev.yml
|
||||
```yaml
|
||||
### 解析认证相关
|
||||
auths:
|
||||
# 123:配置用户名密码
|
||||
# 夸克 / UC 大于 10MiB(10 * 1024 * 1024 字节)时才会查询会员接口。
|
||||
# 只有未过期的 SVIP/VIP 才使用该账号直链;不要把普通 Cookie 写成会员。
|
||||
# qk:
|
||||
# cookie: 浏览器里夸克网盘的 Cookie
|
||||
# uc:
|
||||
# cookie: 浏览器里 UC 网盘的 Cookie
|
||||
# 123:优先填 authorization。账号密码若触发验证码会失败,本项目不处理验证码。
|
||||
ye:
|
||||
username: 你的用户名
|
||||
password: 你的密码
|
||||
# authorization: 浏览器登录后的 authorToken / sso-token
|
||||
```
|
||||
|
||||
**注意:** 目前仅支持 123(ye)的认证配置。
|
||||
|
||||
|
||||
**技术栈:**
|
||||
Jdk17+Vert.x4
|
||||
@@ -544,19 +564,33 @@ Core模块集成Vert.x实现类似spring的注解式路由API
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
## **免责声明**
|
||||
- 用户在使用本项目时,应自行承担风险,并确保其行为符合当地法律法规。开发者不对用户因使用本项目而导致的任何后果负责。
|
||||
|
||||
## 支持该项目
|
||||
开源不易,用爱发电,本项目长期维护如果觉得有帮助, 可以请作者喝杯咖啡, 感谢支持
|
||||
## **声明**
|
||||
|
||||
- 本项目**仅供个人学习与技术交流使用**,请勿用于商业用途或大规模滥用。
|
||||
- 所用接口均来自各网盘**官方开放平台**、官方公开接口及**已知开源项目**,仅解析用户主动提供的分享链接,**不涉及破解或绕过版权保护**。
|
||||
- 本项目**相当于自动化程序代替用户发起请求**,**不会提升或绕过任何会员权限**,也**不会突破网盘的限速策略**;我们**鼓励用户开通官方 VIP/SVIP**以获得更好的下载与加速体验。
|
||||
- 使用者应遵守各网盘服务商的**用户协议与使用条款**,以及所在地区的**法律法规**,违反所产生的后果自行承担。
|
||||
- **高频调用可能触发网盘风控**,导致**账号限流、封禁**或**来源 IP 被屏蔽**,请合理控制请求频率,避免高并发与批量请求。
|
||||
- 网盘接口调整、风控策略变更等因素可能导致功能失效,本项目**不对可用性与稳定性作任何担保**。
|
||||
- 开发者**不对**使用本项目产生的**任何直接或间接损失**(账号封禁、数据丢失、法律纠纷等)**承担责任**。
|
||||
- 开发者保留**随时修改本免责声明**的权利,恕不另行通知。
|
||||
- **下载、部署或使用本项目,即视为您已阅读并接受上述全部条款。**
|
||||
|
||||
|
||||
## 赞助该项目
|
||||
开源不易,用爱发电。本项目长期维护,如果觉得有帮助,欢迎赞助开发者,感谢支持。
|
||||
|
||||
<p align="center">
|
||||
<a href="https://blog.qaiu.top/archives/da-shang-zhuan-yong"><img alt="微信" src="https://api.iconify.design/simple-icons/wechat.svg?color=%2307C160" width="44" height="44"></a>
|
||||
|
||||
<a href="https://blog.qaiu.top/archives/da-shang-zhuan-yong"><img alt="支付宝" src="https://api.iconify.design/simple-icons/alipay.svg?color=%231677FF" width="44" height="44"></a>
|
||||
|
||||
<a href="https://paypal.me/futianshun"><img alt="PayPal" src="https://api.iconify.design/simple-icons/paypal.svg?color=%2300457C" width="44" height="44"></a>
|
||||
</p>
|
||||
|
||||
本项目的服务器由林枫云提供赞助
|
||||
|
||||
本项目的服务器由林枫云提供赞助<br>
|
||||
</a>
|
||||
<a href="https://www.dkdun.cn/aff/WDBRYKGH" target="_blank">
|
||||
<img src="https://www.dkdun.cn/themes/web/www/upload/local68c2dbb2ab148.png" width="200">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
|
||||
|
||||
Regular → Executable
+5
-1
@@ -1,5 +1,9 @@
|
||||
#!/bin/bash
|
||||
# set -x
|
||||
LAUNCH_JAR="netdisk-fast-download.jar"
|
||||
exec java -Xmx${JVM_XMX:-512M} ${JVM_OPTS} -jar "$LAUNCH_JAR" "$@"
|
||||
VECTOR_MODULE_OPT=
|
||||
if java --list-modules 2>/dev/null | grep -q '^jdk.incubator.vector@'; then
|
||||
VECTOR_MODULE_OPT=--add-modules=jdk.incubator.vector
|
||||
fi
|
||||
exec java ${VECTOR_MODULE_OPT} -Xmx${JVM_XMX:-512M} ${JVM_OPTS} -jar "$LAUNCH_JAR" "$@"
|
||||
|
||||
@@ -162,13 +162,18 @@ public class CommonUtil {
|
||||
try (var is = CommonUtil.class.getClassLoader().getResourceAsStream("app.properties")) {
|
||||
if (is != null) {
|
||||
properties.load(is);
|
||||
if (!properties.isEmpty()) {
|
||||
appVersion = properties.getProperty("app.version") + "build" + properties.getProperty("build");
|
||||
String version = properties.getProperty("app.version");
|
||||
String build = properties.getProperty("build");
|
||||
if (version != null && !version.contains("${")) {
|
||||
appVersion = version + "build" + (build == null || build.contains("${") ? "" : build);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("读取app.properties失败", e);
|
||||
}
|
||||
if (appVersion == null) {
|
||||
appVersion = "unknown";
|
||||
}
|
||||
}
|
||||
return appVersion;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,10 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import static cn.qaiu.vx.core.util.ConfigConstant.GLOBAL_CONFIG;
|
||||
@@ -25,6 +28,20 @@ import static cn.qaiu.vx.core.util.ConfigConstant.LOCAL;
|
||||
public class HttpProxyVerticle extends AbstractVerticle {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(HttpProxyVerticle.class);
|
||||
|
||||
static byte[] decodeProxyAuthorization(String encoded) {
|
||||
var source = new ByteArrayInputStream(encoded.getBytes(StandardCharsets.ISO_8859_1));
|
||||
// The streaming decoder uses scalar Java code and does not call the bulk intrinsic.
|
||||
try (var decoder = Base64.getDecoder().wrap(source)) {
|
||||
byte[] decoded = decoder.readAllBytes();
|
||||
if (source.available() != 0) {
|
||||
throw new IllegalArgumentException("Unexpected data after Base64 padding");
|
||||
}
|
||||
return decoded;
|
||||
} catch (IOException e) {
|
||||
throw new IllegalArgumentException("Invalid Base64 proxy credentials", e);
|
||||
}
|
||||
}
|
||||
|
||||
private HttpClient httpClient;
|
||||
private NetClient netClient;
|
||||
private HttpServer httpServer;
|
||||
@@ -164,7 +181,7 @@ public class HttpProxyVerticle extends AbstractVerticle {
|
||||
}
|
||||
String[] split;
|
||||
try {
|
||||
split = new String(Base64.getDecoder().decode(s.replace("Basic ", ""))).split(":");
|
||||
split = new String(decodeProxyAuthorization(s.replace("Basic ", ""))).split(":");
|
||||
} catch (IllegalArgumentException e) {
|
||||
LOGGER.warn("Proxy-Authorization header is not valid Base64");
|
||||
failClientResponse(clientRequest.response(), 403, null);
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package cn.qaiu.vx.core.verticle;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class HttpProxyBase64Test {
|
||||
@Test
|
||||
public void matchesJdkBasicDecoder() {
|
||||
for (String value : new String[]{"", "Zg", "Zg==", "Zm8=", "dXNlcjpwYXNz", "+/8=", "ABCD",
|
||||
"AB==", "Z", "Zg=", "Zm8==", "Zg==suffix", "Zg==\n", "-_8=", "AA\u2603", "===="}) {
|
||||
byte[] expected;
|
||||
try {
|
||||
expected = Base64.getDecoder().decode(value);
|
||||
} catch (IllegalArgumentException expectedFailure) {
|
||||
try {
|
||||
HttpProxyVerticle.decodeProxyAuthorization(value);
|
||||
} catch (IllegalArgumentException actualFailure) {
|
||||
continue;
|
||||
}
|
||||
fail("Accepted invalid proxy credentials: " + value);
|
||||
return;
|
||||
}
|
||||
assertArrayEquals(expected, HttpProxyVerticle.decodeProxyAuthorization(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,4 +10,9 @@ DEFAULT_JVM_OPTS="-Xmx${JVM_XMX:-512M} -Xss${JVM_XSS:-512k} -XX:MaxDirectMemoryS
|
||||
if [ -n "${JVM_MAX_METASPACE:-}" ]; then
|
||||
DEFAULT_JVM_OPTS="$DEFAULT_JVM_OPTS -XX:MaxMetaspaceSize=$JVM_MAX_METASPACE"
|
||||
fi
|
||||
exec java ${DEFAULT_JVM_OPTS} ${JVM_OPTS} -Duser.timezone=${TZ:-Asia/Shanghai} -jar /app/netdisk-fast-download.jar
|
||||
# Keep this after JVM_OPTS to disable the intrinsic even with an older base image.
|
||||
VECTOR_MODULE_OPT=
|
||||
if java --list-modules 2>/dev/null | grep -q '^jdk.incubator.vector@'; then
|
||||
VECTOR_MODULE_OPT=--add-modules=jdk.incubator.vector
|
||||
fi
|
||||
exec java ${VECTOR_MODULE_OPT} ${DEFAULT_JVM_OPTS} ${JVM_OPTS} -XX:-UseBASE64Intrinsics -Duser.timezone=${TZ:-Asia/Shanghai} -jar /app/netdisk-fast-download.jar
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
### 认证参数说明(v0.2.1+)
|
||||
|
||||
部分网盘(如夸克QK、UC网盘)需要登录后的 Cookie 才能解析。`auth` 参数用于传递认证信息:
|
||||
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。夸克小文件可以不登录;UC 必须有 Cookie。`auth` 参数用于传递认证信息:
|
||||
|
||||
**加密方式**:
|
||||
- 算法:AES/ECB/PKCS5Padding
|
||||
@@ -42,8 +42,9 @@
|
||||
**网盘认证要求**:
|
||||
| 网盘 | 认证要求 |
|
||||
|------|---------|
|
||||
| 夸克网盘(QK) | **必须** |
|
||||
| 夸克网盘(QK) | 小文件可免登录;超过访客大小限制(23018)需要 Cookie |
|
||||
| UC网盘(UC) | **必须** |
|
||||
| 123网盘(YE) | 下载通常需要本机 `auths.ye.authorization`;公共云解析没有共享账号 |
|
||||
| 小飞机网盘(FJ) | 大文件需要 |
|
||||
| 蓝奏优享(IZ) | 大文件需要 |
|
||||
|
||||
|
||||
@@ -261,39 +261,11 @@ var methods = systemClass.getDeclaredMethods();
|
||||
|
||||
Nashorn引擎默认允许JavaScript访问所有Java类,这是一个严重的安全隐患。以下是建议的安全措施:
|
||||
|
||||
### 1. 使用ClassFilter限制类访问 🔒 必须
|
||||
### 1. 演练场与已注册解析器的类访问限制
|
||||
|
||||
```java
|
||||
import jdk.nashorn.api.scripting.ClassFilter;
|
||||
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
两个入口都通过 `ParserScriptEngine.create()` 创建 Nashorn 引擎。引擎使用 `--no-java`,类过滤器拒绝按名称解析 Java 类。引擎在执行解析器代码前禁用包入口、脚本加载函数和脚本上下文全局变量。解析器仍可使用项目显式注入的分享信息、HTTP、Fetch 和日志接口。
|
||||
|
||||
public class SecurityClassFilter implements ClassFilter {
|
||||
@Override
|
||||
public boolean exposeToScripts(String className) {
|
||||
// 黑名单:禁止访问危险类
|
||||
if (className.startsWith("java.lang.Runtime") ||
|
||||
className.startsWith("java.lang.ProcessBuilder") ||
|
||||
className.startsWith("java.io.File") ||
|
||||
className.startsWith("java.nio.file") ||
|
||||
className.startsWith("java.lang.System") ||
|
||||
className.startsWith("java.lang.Class") ||
|
||||
className.startsWith("java.lang.reflect") ||
|
||||
className.startsWith("java.net.Socket") ||
|
||||
className.startsWith("java.net.URL")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 白名单:只允许特定的类
|
||||
// return className.startsWith("允许的包名");
|
||||
|
||||
return false; // 默认拒绝所有
|
||||
}
|
||||
}
|
||||
|
||||
// 使用ClassFilter创建引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
ScriptEngine engine = factory.getScriptEngine(new SecurityClassFilter());
|
||||
```
|
||||
`ParserScriptEngineTest` 检查受限全局变量的属性,并通过两个执行入口验证普通解析器的行为。
|
||||
|
||||
### 2. 设置执行超时 ⏱️ 强烈推荐
|
||||
|
||||
|
||||
@@ -109,6 +109,8 @@ URL解码 → Base64解码 → AES解密 → JSON对象
|
||||
}
|
||||
```
|
||||
|
||||
> 123云盘(`ye`)账号密码登录如果返回验证码或风控,解析会直接失败,并提示改用 Authorization,不会尝试验证码。请在浏览器登录后复制 `authorToken` / 请求头 `authorization` / Cookie `sso-token`,用 `authType=authorization` 或 `accesstoken` 传入,或写入 `app-dev.yml` 的 `auths.ye.authorization`。
|
||||
|
||||
#### 4. 自定义认证
|
||||
```json
|
||||
{
|
||||
@@ -339,3 +341,4 @@ server:
|
||||
## 更新日志
|
||||
|
||||
- **2026-02-05**: 初始版本,支持 accesstoken、cookie、password、custom 认证类型
|
||||
- **2026-09-27**: 补充 123云盘账号密码登录触发验证码/风控时改用 Authorization 的说明
|
||||
@@ -57,6 +57,8 @@
|
||||
}
|
||||
```
|
||||
|
||||
> 123云盘(`ye`)账号密码登录触发验证码/风控时,请改用 `authType=authorization` 或 `accesstoken`(`token` 填浏览器中的 Bearer token / JWT),或在 `app-dev.yml` 配置 `auths.ye.authorization`。解析不会尝试验证码。
|
||||
|
||||
### 自定义认证
|
||||
```json
|
||||
{
|
||||
|
||||
+10
-2
@@ -63,7 +63,7 @@
|
||||
<lombok.version>1.18.38</lombok.version>
|
||||
<slf4j.version>2.0.16</slf4j.version>
|
||||
<commons-lang3.version>3.18.0</commons-lang3.version>
|
||||
<jackson.version>2.18.6</jackson.version>
|
||||
<jackson.version>2.18.9</jackson.version>
|
||||
<logback.version>1.5.32</logback.version>
|
||||
<junit.version>4.13.2</junit.version>
|
||||
</properties>
|
||||
@@ -165,6 +165,10 @@
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<release>${maven.compiler.source}</release>
|
||||
<compilerArgs>
|
||||
<arg>--add-modules</arg>
|
||||
<arg>jdk.incubator.vector</arg>
|
||||
</compilerArgs>
|
||||
<encoding>${project.build.sourceEncoding}</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
@@ -200,7 +204,11 @@
|
||||
<!-- 忽略 Javadoc 错误 -->
|
||||
<failOnError>false</failOnError>
|
||||
<!-- 禁用 doclint(新版参数名改为 additionalOptions) -->
|
||||
<additionalOptions>-Xdoclint:none</additionalOptions>
|
||||
<additionalOptions>
|
||||
<additionalOption>-Xdoclint:none</additionalOption>
|
||||
<additionalOption>--add-modules</additionalOption>
|
||||
<additionalOption>jdk.incubator.vector</additionalOption>
|
||||
</additionalOptions>
|
||||
<!-- 如果项目源码中几乎没有 Javadoc,可设 true -->
|
||||
<quiet>true</quiet>
|
||||
</configuration>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -368,48 +368,32 @@ public abstract class PanBase implements IPanTool, Closeable {
|
||||
// 检查响应头中的Content-Encoding是否为gzip
|
||||
String contentEncoding = res.getHeader("Content-Encoding");
|
||||
try {
|
||||
if ("gzip".equalsIgnoreCase(contentEncoding)) {
|
||||
if ("gzip".equalsIgnoreCase(contentEncoding) && res.body() instanceof Buffer gzipBody
|
||||
&& gzipBody.length() >= 2
|
||||
&& (gzipBody.getByte(0) & 0xff) == 0x1f
|
||||
&& (gzipBody.getByte(1) & 0xff) == 0x8b) {
|
||||
// 如果是gzip压缩的响应体,解压(只解压一次,缓存结果)
|
||||
String decompressed = decompressGzip((Buffer) res.body());
|
||||
String decompressed = decompressGzip(gzipBody);
|
||||
return new JsonObject(decompressed);
|
||||
} else {
|
||||
return res.bodyAsJsonObject();
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
// 上游响应体可能来自内网探测目标或非JSON内容,仅写日志,避免经 HTTP 500 回传给调用方
|
||||
if ("gzip".equalsIgnoreCase(contentEncoding)) {
|
||||
log.error("上游响应gzip解压或JSON解析失败: {}", e.getMessage());
|
||||
// gzip解压失败,记录错误
|
||||
log.error("响应gzip解压或JSON解析失败: {}", e.getMessage());
|
||||
fail("响应gzip解压或JSON解析失败: {}", e.getMessage());
|
||||
} else {
|
||||
log.error("上游响应格式异常(非JSON): {}", responseBodyPreview(res));
|
||||
// 上游响应体可能来自内网探测目标,仅写日志,避免经 HTTP 500 回传给调用方
|
||||
String bodyPreview = responseBodyPreview(res);
|
||||
log.error("解析失败: json格式异常: {}", bodyPreview);
|
||||
fail("解析失败: json格式异常");
|
||||
}
|
||||
fail("上游响应格式异常");
|
||||
return JsonObject.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试将响应体解析为 JsonObject,失败时静默返回 null(不调用 fail())。
|
||||
* 适用于版本探测等场景:响应可能是 HTML,此时不应立即终止解析流程。
|
||||
*
|
||||
* @param res HttpResponse
|
||||
* @return JsonObject,若响应体不是合法 JSON 则返回 null
|
||||
*/
|
||||
protected JsonObject tryParseJson(HttpResponse<?> res) {
|
||||
String contentEncoding = res.getHeader("Content-Encoding");
|
||||
try {
|
||||
if ("gzip".equalsIgnoreCase(contentEncoding)) {
|
||||
String decompressed = decompressGzip((Buffer) res.body());
|
||||
return new JsonObject(decompressed);
|
||||
} else {
|
||||
return res.bodyAsJsonObject();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("响应体不是合法JSON,跳过: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* body To text的封装, 会自动处理异常, 会自动解压gzip
|
||||
* @param res HttpResponse
|
||||
|
||||
@@ -121,9 +121,9 @@ public enum PanDomainTemplate {
|
||||
"https://lecloud.lenovo.com/share/{shareKey}",
|
||||
LeTool.class),
|
||||
|
||||
// https://v2.fangcloud.com/s/
|
||||
// https://v2.fangcloud.com/s/ https://v2.fangcloud.cn/h5/share/ (移动端H5落地页)
|
||||
FC("亿方云",
|
||||
compile("https://v2\\.fangcloud\\.(com|cn)/(s|share|sharing)/(?<KEY>.+)"),
|
||||
compile("https://v2\\.fangcloud\\.(com|cn)/(?:h5/)?(s|share|sharing)/(?<KEY>.+)"),
|
||||
"https://v2.fangcloud.com/s/{shareKey}",
|
||||
"https://www.fangcloud.com/",
|
||||
FcTool.class),
|
||||
@@ -232,7 +232,7 @@ public enum PanDomainTemplate {
|
||||
"123635\\.com|" +
|
||||
"123242\\.com|" +
|
||||
"123795\\.com" +
|
||||
")/(?:(?:s|123pan)/|(?:[^/?#]+/)+)?(?<KEY>[a-zA-Z0-9]+-[a-zA-Z0-9]+|[a-zA-Z0-9_-]+)(?:\\.html)?(?:\\?.*)?"),
|
||||
")/(?:(?:s|123pan)/|(?:[^/?#]+/)+)?(?<KEY>[a-zA-Z0-9]+-[a-zA-Z0-9]+|[a-zA-Z0-9_-]+)(?:\\.html)?(?:[?#].*)?"),
|
||||
"https://www.123pan.com/s/{shareKey}",
|
||||
Ye2Tool.class),
|
||||
// https://www.ecpan.cn/web/#/yunpanProxy?path=%2F%23%2Fdrive%2Foutside&data={code}&isShare=1
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
package cn.qaiu.parser;
|
||||
|
||||
import io.vertx.core.json.JsonArray;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 账号密码登录撞上验证码/风控时的用户提示。
|
||||
* 只识别失败形态并引导改用 Authorization,不实现验证码求解、扫码或重试。
|
||||
*/
|
||||
public final class PasswordLoginRisk {
|
||||
|
||||
/**
|
||||
* 123 云盘(ye)账号密码登录被验证码/风控拦住时返回给调用方的固定说明。
|
||||
* 上游 code/message 会另附在这句话后面,便于和“密码错误”区分。
|
||||
*/
|
||||
public static final String AUTHORIZATION_HINT =
|
||||
"账号密码登录触发了验证码/风控,已停止用户名密码登录(不会尝试验证码)。"
|
||||
+ "请改为配置 Authorization(浏览器登录后的 Bearer token / JWT,"
|
||||
+ "例如 localStorage 的 authorToken、请求头 authorization 或 Cookie 的 sso-token)。"
|
||||
+ "静态配置写在 app-dev.yml 的 auths.ye.authorization(与 auths.ye.token 等价);"
|
||||
+ "临时请求使用 authType=authorization 或 authType=accesstoken,token 填该令牌(不要重复带 Bearer 前缀)。"
|
||||
+ "说明见 parser/doc/auth-param/。";
|
||||
|
||||
/**
|
||||
* 上游文案命中这些片段时视为验证码/风控,而不是单纯的密码错误。
|
||||
* 依据公开客户端(AList/OpenList)实际展示过的 123 登录失败文案,以及登录页上的滑块/人机验证提示。
|
||||
*/
|
||||
private static final String[] RISK_KEYWORDS = {
|
||||
"验证码",
|
||||
"风控",
|
||||
"安全风险",
|
||||
"安全验证",
|
||||
"安全校验",
|
||||
"滑块",
|
||||
"滑动验证",
|
||||
"拼图验证",
|
||||
"短信验证",
|
||||
"微信登录",
|
||||
"微信进行登录",
|
||||
"境外登录",
|
||||
"需要验证",
|
||||
"请验证",
|
||||
"请你验证",
|
||||
"进行验证",
|
||||
"完成验证",
|
||||
"二次验证",
|
||||
"人机验证",
|
||||
"操作频繁",
|
||||
"请求过于频繁",
|
||||
"请求频繁",
|
||||
"captcha",
|
||||
"recaptcha",
|
||||
"risk control"
|
||||
};
|
||||
|
||||
private PasswordLoginRisk() {
|
||||
}
|
||||
|
||||
public static boolean isLoginSuccess(JsonObject json) {
|
||||
if (json == null) {
|
||||
return false;
|
||||
}
|
||||
Integer code = readCode(json);
|
||||
return code != null && code == 200 && StringUtils.isNotBlank(readToken(json));
|
||||
}
|
||||
|
||||
public static boolean indicatesCaptchaOrRisk(JsonObject json) {
|
||||
if (json == null) {
|
||||
return false;
|
||||
}
|
||||
if (hasTruthyRiskField(json) || hasTruthyRiskField(dataObject(json))) {
|
||||
return true;
|
||||
}
|
||||
return textIndicatesCaptchaOrRisk(collectMessageText(json));
|
||||
}
|
||||
|
||||
public static boolean textIndicatesCaptchaOrRisk(String text) {
|
||||
if (StringUtils.isBlank(text)) {
|
||||
return false;
|
||||
}
|
||||
String lower = text.toLowerCase(Locale.ROOT);
|
||||
for (String keyword : RISK_KEYWORDS) {
|
||||
if (lower.contains(keyword.toLowerCase(Locale.ROOT))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 非成功登录响应的用户可见说明。验证码/风控走 Authorization 引导,其余保持“登录失败: 上游文案”。
|
||||
*/
|
||||
public static String describeLoginFailure(JsonObject json) {
|
||||
if (json == null) {
|
||||
return "登录响应格式异常";
|
||||
}
|
||||
if (indicatesCaptchaOrRisk(json)) {
|
||||
return AUTHORIZATION_HINT + " 上游返回:" + upstreamSummary(json);
|
||||
}
|
||||
Integer code = readCode(json);
|
||||
if (code != null && code == 200) {
|
||||
return "未获取到token";
|
||||
}
|
||||
String message = firstMessage(json);
|
||||
if (StringUtils.isBlank(message)) {
|
||||
return "登录失败";
|
||||
}
|
||||
return "登录失败: " + message;
|
||||
}
|
||||
|
||||
public static String nonJsonLoginFailure(String body) {
|
||||
if (textIndicatesCaptchaOrRisk(body)) {
|
||||
return AUTHORIZATION_HINT + " 上游返回:" + truncate(body, 300);
|
||||
}
|
||||
return "登录响应格式异常: " + body;
|
||||
}
|
||||
|
||||
private static String collectMessageText(JsonObject json) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
appendMessage(text, json);
|
||||
JsonObject data = dataObject(json);
|
||||
if (data != null) {
|
||||
appendMessage(text, data);
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
|
||||
private static void appendMessage(StringBuilder text, JsonObject json) {
|
||||
append(text, json.getString("message"));
|
||||
append(text, json.getString("msg"));
|
||||
}
|
||||
|
||||
private static void append(StringBuilder text, String value) {
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
if (text.length() > 0) {
|
||||
text.append(' ');
|
||||
}
|
||||
text.append(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasTruthyRiskField(JsonObject obj) {
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
for (String key : obj.fieldNames()) {
|
||||
if (!isRiskFieldName(key)) {
|
||||
continue;
|
||||
}
|
||||
if (isTruthyRiskValue(obj.getValue(key))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isRiskFieldName(String key) {
|
||||
String lower = key.toLowerCase(Locale.ROOT);
|
||||
return lower.contains("captcha")
|
||||
|| lower.contains("vcode")
|
||||
|| lower.contains("risk")
|
||||
|| "needverify".equals(lower)
|
||||
|| "need_verify".equals(lower)
|
||||
|| "slideverify".equals(lower)
|
||||
|| "verifycode".equals(lower)
|
||||
|| "verify_code".equals(lower);
|
||||
}
|
||||
|
||||
private static boolean isTruthyRiskValue(Object value) {
|
||||
if (value == null) {
|
||||
return false;
|
||||
}
|
||||
if (value instanceof Boolean) {
|
||||
return (Boolean) value;
|
||||
}
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).doubleValue() != 0d;
|
||||
}
|
||||
if (value instanceof CharSequence) {
|
||||
String text = value.toString().trim();
|
||||
if (text.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String lower = text.toLowerCase(Locale.ROOT);
|
||||
return !"false".equals(lower) && !"0".equals(lower) && !"null".equals(lower) && !"none".equals(lower);
|
||||
}
|
||||
if (value instanceof JsonObject) {
|
||||
return !((JsonObject) value).isEmpty();
|
||||
}
|
||||
if (value instanceof JsonArray) {
|
||||
return !((JsonArray) value).isEmpty();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static String upstreamSummary(JsonObject json) {
|
||||
StringBuilder summary = new StringBuilder();
|
||||
Integer code = readCode(json);
|
||||
if (code != null) {
|
||||
summary.append("code=").append(code);
|
||||
}
|
||||
String message = firstMessage(json);
|
||||
if (StringUtils.isNotBlank(message)) {
|
||||
if (summary.length() > 0) {
|
||||
summary.append(", ");
|
||||
}
|
||||
summary.append("message=").append(message);
|
||||
}
|
||||
if (summary.length() == 0) {
|
||||
summary.append(json.encode());
|
||||
}
|
||||
return truncate(summary.toString(), 300);
|
||||
}
|
||||
|
||||
private static String firstMessage(JsonObject json) {
|
||||
String message = json.getString("message");
|
||||
if (StringUtils.isBlank(message)) {
|
||||
message = json.getString("msg");
|
||||
}
|
||||
if (StringUtils.isBlank(message)) {
|
||||
JsonObject data = dataObject(json);
|
||||
if (data != null) {
|
||||
message = data.getString("message");
|
||||
if (StringUtils.isBlank(message)) {
|
||||
message = data.getString("msg");
|
||||
}
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
static String readToken(JsonObject json) {
|
||||
JsonObject data = dataObject(json);
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
Object token = data.getValue("token");
|
||||
return token == null ? null : token.toString();
|
||||
}
|
||||
|
||||
private static JsonObject dataObject(JsonObject json) {
|
||||
Object data = json.getValue("data");
|
||||
return data instanceof JsonObject ? (JsonObject) data : null;
|
||||
}
|
||||
|
||||
static Integer readCode(JsonObject json) {
|
||||
Object code = json.getValue("code");
|
||||
if (code instanceof Number) {
|
||||
return ((Number) code).intValue();
|
||||
}
|
||||
if (code instanceof String && StringUtils.isNumeric(((String) code).trim())) {
|
||||
return Integer.parseInt(((String) code).trim());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String truncate(String value, int max) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
if (trimmed.length() <= max) {
|
||||
return trimmed;
|
||||
}
|
||||
return trimmed.substring(0, max) + "...";
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
package cn.qaiu.parser.clientlink.impl;
|
||||
|
||||
import cn.qaiu.util.Base64Encoder;
|
||||
import cn.qaiu.parser.clientlink.ClientLinkGenerator;
|
||||
import cn.qaiu.parser.clientlink.ClientLinkType;
|
||||
import cn.qaiu.parser.clientlink.DownloadLinkMeta;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* 迅雷协议链接生成器
|
||||
@@ -27,7 +27,7 @@ public class ThunderLinkGenerator implements ClientLinkGenerator {
|
||||
String thunderUrl = "AA" + originalUrl + "ZZ";
|
||||
|
||||
// Base64编码
|
||||
String encodedUrl = Base64.getEncoder().encodeToString(
|
||||
String encodedUrl = Base64Encoder.encode(
|
||||
thunderUrl.getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import io.vertx.core.Future;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.WorkerExecutor;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -134,15 +133,7 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
|
||||
*/
|
||||
private ScriptEngine initEngine() {
|
||||
try {
|
||||
// 使用安全的ClassFilter创建Nashorn引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
|
||||
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
|
||||
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
|
||||
|
||||
if (engine == null) {
|
||||
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
|
||||
}
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
this.engine = engine;
|
||||
|
||||
// 注入Java对象到JavaScript环境
|
||||
@@ -151,14 +142,6 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
|
||||
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
||||
engine.put("JavaFetch", fetchBridge);
|
||||
|
||||
// 禁用Java对象访问
|
||||
engine.eval("var Java = undefined;");
|
||||
engine.eval("var JavaImporter = undefined;");
|
||||
engine.eval("var Packages = undefined;");
|
||||
engine.eval("var javax = undefined;");
|
||||
engine.eval("var org = undefined;");
|
||||
engine.eval("var com = undefined;");
|
||||
|
||||
// 加载fetch运行时(Promise和fetch API polyfill)
|
||||
String fetchRuntime = loadFetchRuntime();
|
||||
if (!fetchRuntime.isEmpty()) {
|
||||
|
||||
@@ -5,7 +5,6 @@ import cn.qaiu.entity.ShareLinkInfo;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -111,15 +110,7 @@ public class JsPlaygroundExecutor implements AutoCloseable {
|
||||
*/
|
||||
private ScriptEngine initEngine() {
|
||||
try {
|
||||
// 使用安全的ClassFilter创建Nashorn引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
|
||||
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
|
||||
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
|
||||
|
||||
if (engine == null) {
|
||||
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
|
||||
}
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
this.engine = engine;
|
||||
|
||||
// 注入Java对象到JavaScript环境
|
||||
@@ -128,14 +119,6 @@ public class JsPlaygroundExecutor implements AutoCloseable {
|
||||
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
||||
engine.put("JavaFetch", fetchBridge);
|
||||
|
||||
// 禁用Java对象访问
|
||||
engine.eval("var Java = undefined;");
|
||||
engine.eval("var JavaImporter = undefined;");
|
||||
engine.eval("var Packages = undefined;");
|
||||
engine.eval("var javax = undefined;");
|
||||
engine.eval("var org = undefined;");
|
||||
engine.eval("var com = undefined;");
|
||||
|
||||
// 加载fetch运行时(Promise和fetch API polyfill)
|
||||
String fetchRuntime = JsParserExecutor.loadFetchRuntime();
|
||||
if (!fetchRuntime.isEmpty()) {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptException;
|
||||
|
||||
final class ParserScriptEngine {
|
||||
private ParserScriptEngine() {}
|
||||
|
||||
static ScriptEngine create() throws ScriptException {
|
||||
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
|
||||
new String[]{"--no-java"}, null, new SecurityClassFilter());
|
||||
// Remove host loaders and scripting-context globals before binding the parser APIs.
|
||||
engine.eval("""
|
||||
(function (global) {
|
||||
["load", "loadWithNewGlobal", "exit", "quit", "engine", "context",
|
||||
"Java", "JavaImporter", "Packages", "java", "javax", "javafx", "org",
|
||||
"com", "edu"].forEach(function (name) {
|
||||
Object.defineProperty(global, name, {
|
||||
value: void 0, writable: false, configurable: false
|
||||
});
|
||||
});
|
||||
})(this);
|
||||
""");
|
||||
return engine;
|
||||
}
|
||||
}
|
||||
@@ -1,118 +1,11 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import org.openjdk.nashorn.api.scripting.ClassFilter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* JavaScript执行器安全类过滤器
|
||||
* 用于限制JavaScript代码可以访问的Java类,防止恶意代码执行危险操作
|
||||
*
|
||||
* @author <a href="https://qaiu.top">QAIU</a>
|
||||
*/
|
||||
/** Scripts work through the supplied parser APIs and may not resolve Java classes by name. */
|
||||
public class SecurityClassFilter implements ClassFilter {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SecurityClassFilter.class);
|
||||
|
||||
// 危险类黑名单
|
||||
private static final String[] DANGEROUS_CLASSES = {
|
||||
// 系统命令执行
|
||||
"java.lang.Runtime",
|
||||
"java.lang.ProcessBuilder",
|
||||
"java.lang.Process",
|
||||
|
||||
// 文件系统访问
|
||||
"java.io.File",
|
||||
"java.io.FileInputStream",
|
||||
"java.io.FileOutputStream",
|
||||
"java.io.FileReader",
|
||||
"java.io.FileWriter",
|
||||
"java.io.RandomAccessFile",
|
||||
"java.nio.file.Files",
|
||||
"java.nio.file.Paths",
|
||||
"java.nio.file.Path",
|
||||
"java.nio.channels.FileChannel",
|
||||
|
||||
// 系统访问
|
||||
"java.lang.System",
|
||||
"java.lang.SecurityManager",
|
||||
|
||||
// 反射相关
|
||||
"java.lang.Class",
|
||||
"java.lang.reflect.Method",
|
||||
"java.lang.reflect.Field",
|
||||
"java.lang.reflect.Constructor",
|
||||
"java.lang.reflect.AccessibleObject",
|
||||
"java.lang.ClassLoader",
|
||||
|
||||
// 网络访问
|
||||
"java.net.Socket",
|
||||
"java.net.ServerSocket",
|
||||
"java.net.DatagramSocket",
|
||||
"java.net.URL",
|
||||
"java.net.URLConnection",
|
||||
"java.net.HttpURLConnection",
|
||||
"java.net.InetAddress",
|
||||
|
||||
// 线程和并发
|
||||
"java.lang.Thread",
|
||||
"java.lang.ThreadGroup",
|
||||
"java.util.concurrent.Executor",
|
||||
"java.util.concurrent.ExecutorService",
|
||||
|
||||
// 数据库访问
|
||||
"java.sql.Connection",
|
||||
"java.sql.Statement",
|
||||
"java.sql.PreparedStatement",
|
||||
"java.sql.DriverManager",
|
||||
|
||||
// 脚本引擎(防止嵌套执行)
|
||||
"javax.script.ScriptEngine",
|
||||
"javax.script.ScriptEngineManager",
|
||||
|
||||
// JVM控制
|
||||
"java.lang.invoke.MethodHandle",
|
||||
"sun.misc.Unsafe",
|
||||
|
||||
// Nashorn内部类
|
||||
"jdk.nashorn.internal",
|
||||
"jdk.internal",
|
||||
};
|
||||
|
||||
@Override
|
||||
public boolean exposeToScripts(String className) {
|
||||
// 检查是否在黑名单中
|
||||
for (String dangerous : DANGEROUS_CLASSES) {
|
||||
if (className.equals(dangerous) || className.startsWith(dangerous + ".")) {
|
||||
log.warn("🔒 安全拦截: JavaScript尝试访问危险类 - {}", className);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 额外的包级别限制
|
||||
String[] dangerousPackages = {
|
||||
"java.lang.reflect.",
|
||||
"java.io.",
|
||||
"java.nio.",
|
||||
"java.net.",
|
||||
"java.sql.",
|
||||
"javax.script.",
|
||||
"sun.",
|
||||
"jdk.internal.",
|
||||
"jdk.nashorn.internal."
|
||||
};
|
||||
|
||||
for (String pkg : dangerousPackages) {
|
||||
if (className.startsWith(pkg)) {
|
||||
log.warn("🔒 安全拦截: JavaScript尝试访问危险包 - {}", className);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 默认也拒绝(白名单策略更安全,但这里为了兼容性使用黑名单)
|
||||
// 如果要更严格,可以改为 return false
|
||||
log.debug("允许访问类: {}", className);
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,15 +81,18 @@ public class CeTool extends PanBase {
|
||||
// 禁止跟随重定向:assertPublicHost 只校验初始 host,自动 30x 会绕过 SSRF 防护
|
||||
clientNoRedirects.getAbs(pingUrlV4).send().onSuccess(res -> {
|
||||
if (res.statusCode() == 200) {
|
||||
// 使用 tryParseJson 而非 asJson,避免非JSON响应(如HTML)提前终止整个解析流程
|
||||
JsonObject json = tryParseJson(res);
|
||||
// v4 ping 成功且返回有效JSON,使用 Ce4Tool
|
||||
if (json != null && !json.isEmpty()) {
|
||||
log.debug("检测到Cloudreve 4.x (通过v4 ping)");
|
||||
delegateToCe4Tool();
|
||||
return;
|
||||
try {
|
||||
JsonObject json = asJson(res);
|
||||
// v4 ping 成功且返回有效JSON,使用 Ce4Tool
|
||||
if (json != null && !json.isEmpty()) {
|
||||
log.debug("检测到Cloudreve 4.x (通过v4 ping)");
|
||||
delegateToCe4Tool();
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// JSON解析失败,继续尝试 v3
|
||||
log.debug("v4 ping返回非JSON响应,尝试v3");
|
||||
}
|
||||
log.debug("v4 ping返回非JSON响应,尝试v3");
|
||||
}
|
||||
// v4 ping失败或返回非JSON,尝试 v3
|
||||
tryV3Ping(baseUrl, key, pwd);
|
||||
@@ -108,15 +111,18 @@ public class CeTool extends PanBase {
|
||||
|
||||
clientNoRedirects.getAbs(pingUrlV3).send().onSuccess(res -> {
|
||||
if (res.statusCode() == 200) {
|
||||
// 使用 tryParseJson 而非 asJson,避免非JSON响应(如HTML)提前终止整个解析流程
|
||||
JsonObject json = tryParseJson(res);
|
||||
// v3 ping 成功且返回有效JSON,进一步验证是否为 v3
|
||||
if (json != null && !json.isEmpty()) {
|
||||
// 尝试调用 v3 share API 来确认
|
||||
verifyV3AndParse(baseUrl, key, pwd);
|
||||
return;
|
||||
try {
|
||||
JsonObject json = asJson(res);
|
||||
// v3 ping 成功且返回有效JSON,进一步验证是否为 v3
|
||||
if (json != null && !json.isEmpty()) {
|
||||
// 尝试调用 v3 share API 来确认
|
||||
verifyV3AndParse(baseUrl, key, pwd);
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// JSON解析失败,不是Cloudreve盘
|
||||
log.debug("v3 ping返回非JSON响应,不是Cloudreve盘");
|
||||
}
|
||||
log.debug("v3 ping返回非JSON响应,不是Cloudreve盘");
|
||||
}
|
||||
// v3 ping失败,不是Cloudreve盘
|
||||
log.debug("v3 ping失败,尝试下一个解析器");
|
||||
|
||||
@@ -22,6 +22,7 @@ public class FcTool extends PanBase {
|
||||
|
||||
public static final String SHARE_URL_PREFIX = "https://v2.fangcloud.com/sharing/";
|
||||
public static final String SHARE_URL_PREFIX2 = "https://v2.fangcloud.cn/sharing/";
|
||||
private static final String SHARE_INFO_URL = "https://v2.fangcloud.cn/apps/share_links/info/";
|
||||
private static final String DOWN_REQUEST_URL = "https://v2.fangcloud.cn/apps/files/download?file_id={fid}" +
|
||||
"&scenario=share&unique_name={uname}";
|
||||
|
||||
@@ -38,6 +39,25 @@ public class FcTool extends PanBase {
|
||||
final String dataKey = shareLinkInfo.getShareKey();
|
||||
final String pwd = shareLinkInfo.getSharePassword();
|
||||
WebClientSession sClient = WebClientSession.create(client);
|
||||
// 先查询分享有效性, 避免分享已失效/已过期时仍去解析HTML, 报出令人困惑的技术错误
|
||||
sClient.getAbs(SHARE_INFO_URL + dataKey).send().onSuccess(infoRes -> {
|
||||
JsonObject infoJson = asJson(infoRes);
|
||||
if (promise.future().isComplete()) {
|
||||
return;
|
||||
}
|
||||
JsonObject process = infoJson.getJsonObject("process");
|
||||
boolean isClosed = process != null && Boolean.TRUE.equals(process.getBoolean("is_closed"));
|
||||
boolean isExpired = process != null && Boolean.TRUE.equals(process.getBoolean("is_expired"));
|
||||
if (process == null || isClosed || isExpired) {
|
||||
fail("分享已失效或不存在");
|
||||
return;
|
||||
}
|
||||
doParse(dataKey, pwd, sClient);
|
||||
}).onFailure(handleFail(SHARE_INFO_URL + dataKey));
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
private void doParse(String dataKey, String pwd, WebClientSession sClient) {
|
||||
// 第一次请求 自动重定向
|
||||
sClient.getAbs(SHARE_URL_PREFIX + dataKey).send().onSuccess(res -> {
|
||||
|
||||
@@ -67,7 +87,6 @@ public class FcTool extends PanBase {
|
||||
}
|
||||
getDownURL(dataKey, promise, res, sClient);
|
||||
}).onFailure(handleFail(SHARE_URL_PREFIX + dataKey));
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
private void getDownURL(String dataKey, Promise<String> promise, HttpResponse<Buffer> res,
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
final class FjDownloadParams {
|
||||
private FjDownloadParams() {
|
||||
}
|
||||
|
||||
static JsonObject create(String fileId, String userId, String uuid, String shareId, long timestamp) {
|
||||
if (StringUtils.isBlank(fileId) || StringUtils.isBlank(shareId)) {
|
||||
throw new IllegalArgumentException("缺少 fileId 或 shareId");
|
||||
}
|
||||
return JsonObject.of("fileId", fileId,
|
||||
"fidEncode", AESUtils.encrypt2Hex(fileId + "|" + StringUtils.defaultString(userId)),
|
||||
"uuid", uuid, "shareId", shareId,
|
||||
"ts", AESUtils.encrypt2Hex(Long.toString(timestamp)),
|
||||
"auth", AESUtils.encrypt2Hex(fileId + "|" + timestamp));
|
||||
}
|
||||
|
||||
static String fileId(JsonObject params) throws Exception {
|
||||
String fileId = params.getString("fileId");
|
||||
if (StringUtils.isNotBlank(fileId)) {
|
||||
return fileId;
|
||||
}
|
||||
// 兼容已生成的目录链接,但不再复用其中的身份和过期签名。
|
||||
String decoded = AESUtils.decryptByHexAES(params.getString("fidEncode"), AESUtils.CIPHER_AES0);
|
||||
int separator = decoded.indexOf('|');
|
||||
if (separator <= 0) {
|
||||
throw new IllegalArgumentException("无效的 fidEncode");
|
||||
}
|
||||
return decoded.substring(0, separator);
|
||||
}
|
||||
|
||||
static String ownerId(JsonObject params) throws Exception {
|
||||
Object id = params.getValue("userId");
|
||||
if (id != null && StringUtils.isNotBlank(id.toString())) {
|
||||
return id.toString();
|
||||
}
|
||||
String encoded = params.getString("fidEncode");
|
||||
if (StringUtils.isBlank(encoded)) {
|
||||
return null;
|
||||
}
|
||||
String decoded = AESUtils.decryptByHexAES(encoded, AESUtils.CIPHER_AES0);
|
||||
int separator = decoded.indexOf('|');
|
||||
String owner = separator < 0 ? null : decoded.substring(separator + 1);
|
||||
return StringUtils.isBlank(owner) || "null".equals(owner) ? null : owner;
|
||||
}
|
||||
|
||||
static String missingLocation(int status, String body) {
|
||||
String message = "未获取到下载重定向地址, HTTP " + status;
|
||||
if (StringUtils.isBlank(body)) {
|
||||
return message + ", 响应体为空";
|
||||
}
|
||||
try {
|
||||
JsonObject json = new JsonObject(body);
|
||||
if (StringUtils.isNotBlank(json.getString("msg"))) {
|
||||
return message + ", 上游返回: " + preview(json.getString("msg"))
|
||||
+ " (code=" + json.getValue("code") + ")";
|
||||
}
|
||||
} catch (RuntimeException ignored) {
|
||||
// 非 JSON 错误页同样保留有限长度的诊断内容。
|
||||
}
|
||||
return message + ", 响应体: " + preview(body);
|
||||
}
|
||||
|
||||
private static String preview(String value) {
|
||||
return value.length() > 500 ? value.substring(0, 500) + "..." : value;
|
||||
}
|
||||
}
|
||||
@@ -129,8 +129,6 @@ public class FjTool extends PanBase {
|
||||
if (auths.contains("userId")) {
|
||||
FjTool.userId = auths.get("userId");
|
||||
log.info("已配置用户ID: {}", FjTool.userId);
|
||||
} else {
|
||||
log.warn("未配置用户ID, 可能会导致解析失败");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +197,7 @@ public class FjTool extends PanBase {
|
||||
// 其他参数
|
||||
long nowTs2 = System.currentTimeMillis();
|
||||
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId);
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
||||
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
||||
|
||||
// 检查是否有认证信息
|
||||
@@ -223,7 +221,7 @@ public class FjTool extends PanBase {
|
||||
log.warn("登录失败: {}", failRes.getMessage());
|
||||
fail(failRes.getMessage());
|
||||
}).onSuccess(r-> {
|
||||
httpRequest.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId))
|
||||
httpRequest.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + userId))
|
||||
.putHeaders(header);
|
||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
});
|
||||
@@ -245,7 +243,7 @@ public class FjTool extends PanBase {
|
||||
});
|
||||
} else {
|
||||
httpRequest
|
||||
.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId))
|
||||
.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + userId))
|
||||
.putHeaders(header);
|
||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
}
|
||||
@@ -444,8 +442,15 @@ public class FjTool extends PanBase {
|
||||
|
||||
private void down(HttpResponse<Buffer> res2) {
|
||||
MultiMap headers = res2.headers();
|
||||
if (!headers.contains("Location") || headers.get("Location") == null) {
|
||||
fail("找不到下载链接可能服务器已被禁止或者配置的认证信息有误: " + res2.bodyAsString());
|
||||
if (StringUtils.isBlank(headers.get("Location"))) {
|
||||
String body;
|
||||
try {
|
||||
body = asText(res2);
|
||||
} catch (IllegalArgumentException | UnsupportedOperationException e) {
|
||||
fail(e, "读取下载错误响应失败, HTTP {}", res2.statusCode());
|
||||
return;
|
||||
}
|
||||
fail("{}", FjDownloadParams.missingLocation(res2.statusCode(), body));
|
||||
return;
|
||||
}
|
||||
promise.complete(headers.get("Location"));
|
||||
@@ -523,7 +528,7 @@ public class FjTool extends PanBase {
|
||||
// 其他参数
|
||||
long nowTs2 = System.currentTimeMillis();
|
||||
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId);
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
||||
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
||||
|
||||
// 回传用到的参数
|
||||
@@ -533,6 +538,8 @@ public class FjTool extends PanBase {
|
||||
//"auth", paramJson.getString("auth"))
|
||||
//"shareId", paramJson.getString("shareId"))
|
||||
JsonObject entries = JsonObject.of(
|
||||
"fileId", fileId,
|
||||
"userId", userId,
|
||||
"fidEncode", fidEncode,
|
||||
"uuid", uuid,
|
||||
"ts", tsEncode2,
|
||||
@@ -590,20 +597,24 @@ public class FjTool extends PanBase {
|
||||
promise.fail("缺少 paramJson 参数");
|
||||
return promise.future();
|
||||
}
|
||||
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
||||
.setTemplateParam("fidEncode", paramJson.getString("fidEncode"))
|
||||
.setTemplateParam("uuid", paramJson.getString("uuid"))
|
||||
.setTemplateParam("ts", paramJson.getString("ts"))
|
||||
.setTemplateParam("auth", paramJson.getString("auth"))
|
||||
.setTemplateParam("dataKey", paramJson.getString("shareId"))
|
||||
.putHeaders(header).send().onSuccess(res2 -> {
|
||||
MultiMap headers = res2.headers();
|
||||
if (!headers.contains("Location")) {
|
||||
fail(SECOND_REQUEST_URL_VIP + " 未找到重定向URL: \n" + res2.headers());
|
||||
return;
|
||||
}
|
||||
promise.complete(headers.get("Location"));
|
||||
}).onFailure(handleFail(SECOND_REQUEST_URL_VIP));
|
||||
try {
|
||||
String ownerId = FjDownloadParams.ownerId(paramJson);
|
||||
if (StringUtils.isBlank(ownerId) || "null".equals(ownerId)) {
|
||||
fail("目录下载参数缺少分享者 userId,请刷新文件列表后重试");
|
||||
return promise.future();
|
||||
}
|
||||
JsonObject params = FjDownloadParams.create(FjDownloadParams.fileId(paramJson), ownerId,
|
||||
paramJson.getString("uuid"), paramJson.getString("shareId"), System.currentTimeMillis());
|
||||
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
||||
.setTemplateParam("fidEncode", params.getString("fidEncode"))
|
||||
.setTemplateParam("uuid", params.getString("uuid"))
|
||||
.setTemplateParam("ts", params.getString("ts"))
|
||||
.setTemplateParam("auth", params.getString("auth"))
|
||||
.setTemplateParam("dataKey", params.getString("shareId"))
|
||||
.putHeaders(header).send().onSuccess(this::down).onFailure(handleFail("下载请求"));
|
||||
} catch (Exception e) {
|
||||
fail(e, "下载参数无效");
|
||||
}
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.util.Base64Encoder;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.PanBase;
|
||||
import io.netty.handler.codec.http.cookie.Cookie;
|
||||
@@ -14,7 +15,6 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -48,7 +48,7 @@ public class GenShortUrl extends PanBase {
|
||||
public Future<String> parse() {
|
||||
String longUrl = shareLinkInfo.getShareUrl();
|
||||
|
||||
String url = WRAPPER_URL + Base64.getEncoder().encodeToString(longUrl.getBytes());
|
||||
String url = WRAPPER_URL + Base64Encoder.encode(longUrl.getBytes());
|
||||
|
||||
String payload = "mid=" + MID + "&content=" + URLEncoder.encode(url, StandardCharsets.UTF_8);
|
||||
clientSession.cookieStore().put(cookie);
|
||||
|
||||
@@ -3,6 +3,7 @@ package cn.qaiu.parser.impl;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.PanBase;
|
||||
import cn.qaiu.parser.TokenCache;
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import cn.qaiu.util.AcwScV2Generator;
|
||||
import cn.qaiu.util.CommonUtils;
|
||||
@@ -85,12 +86,31 @@ public class IzTool extends PanBase {
|
||||
}
|
||||
public IzTool(ShareLinkInfo shareLinkInfo) {
|
||||
super(shareLinkInfo);
|
||||
IzXffHeader.apply(header);
|
||||
String accountId = "_default";
|
||||
if (shareLinkInfo.getOtherParam().containsKey("auths")) {
|
||||
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
||||
if (auths.contains("_configId")) {
|
||||
accountId = auths.get("_configId");
|
||||
} else if (auths.contains("username")) {
|
||||
accountId = auths.get("username");
|
||||
}
|
||||
}
|
||||
this.cacheKey = TokenCache.key("iz", accountId);
|
||||
}
|
||||
|
||||
String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
|
||||
|
||||
public static volatile String token = null;
|
||||
public static volatile boolean authFlag = true;
|
||||
// 多账号隔离:用 TokenCache 代替 static 变量
|
||||
private final String cacheKey;
|
||||
|
||||
private String token() {
|
||||
return TokenCache.getToken(cacheKey);
|
||||
}
|
||||
|
||||
private boolean authFlag() {
|
||||
return TokenCache.getFlag(cacheKey, true);
|
||||
}
|
||||
|
||||
public Future<String> parse() {
|
||||
|
||||
@@ -101,22 +121,21 @@ public class IzTool extends PanBase {
|
||||
// 检查并输出认证状态
|
||||
if (shareLinkInfo.getOtherParam().containsKey("auths")) {
|
||||
boolean isTempAuth = shareLinkInfo.getOtherParam().containsKey("__TEMP_AUTH_ADDED");
|
||||
String token = token();
|
||||
log.info("文件解析检测到认证信息: isTempAuth={}, authFlag={}, token={}",
|
||||
isTempAuth, authFlag, token != null ? "已登录(" + token.substring(0, Math.min(8, token.length())) + "...)" : "未登录");
|
||||
isTempAuth, authFlag(), token != null ? "已登录(" + token.substring(0, Math.min(8, token.length())) + "...)" : "未登录");
|
||||
|
||||
// 如果需要认证但还没有token,先执行登录
|
||||
if ((isTempAuth || authFlag) && token == null) {
|
||||
if ((isTempAuth || authFlag()) && token == null) {
|
||||
log.info("文件解析需要登录,开始执行登录流程...");
|
||||
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
||||
return login(tsEncode, auths)
|
||||
.compose(v -> {
|
||||
log.info("文件解析预登录成功,继续解析流程");
|
||||
return parseWithAuth(shareId, tsEncode);
|
||||
.recover(err -> {
|
||||
// 预登录失败不终止解析,继续走免登录
|
||||
log.warn("文件解析预登录失败: {},使用免登录模式", err.getMessage());
|
||||
return Future.succeededFuture();
|
||||
})
|
||||
.onFailure(err -> {
|
||||
log.warn("文件解析预登录失败: {},尝试使用免登录模式", err.getMessage());
|
||||
// 登录失败,继续使用免登录模式
|
||||
});
|
||||
.compose(v -> parseWithAuth(shareId, tsEncode));
|
||||
} else if (token != null) {
|
||||
log.info("文件解析使用已有token: {}...", token.substring(0, Math.min(8, token.length())));
|
||||
}
|
||||
@@ -231,8 +250,8 @@ public class IzTool extends PanBase {
|
||||
// 检查是否为临时认证(临时认证每次都尝试登录)
|
||||
boolean isTempAuth = shareLinkInfo.getOtherParam().containsKey("__TEMP_AUTH_ADDED");
|
||||
// 如果是临时认证,或者是后台配置且authFlag为true,则尝试使用认证
|
||||
if (isTempAuth || authFlag) {
|
||||
log.debug("尝试使用认证信息解析, isTempAuth={}, authFlag={}", isTempAuth, authFlag);
|
||||
if (isTempAuth || authFlag()) {
|
||||
log.debug("尝试使用认证信息解析, isTempAuth={}, authFlag={}", isTempAuth, authFlag());
|
||||
HttpRequest<Buffer> httpRequest =
|
||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
||||
.setTemplateParam("fidEncode", fidEncode)
|
||||
@@ -241,18 +260,19 @@ public class IzTool extends PanBase {
|
||||
.setTemplateParam("auth", auth)
|
||||
.setTemplateParam("dataKey", dataKey);
|
||||
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
||||
if (token == null) {
|
||||
// 执行登录
|
||||
if (token() == null) {
|
||||
// 执行登录,失败则回退免登录
|
||||
login(tsEncode2, auths).onFailure(failRes-> {
|
||||
log.warn("登录失败: {}", failRes.getMessage());
|
||||
fail(failRes.getMessage());
|
||||
log.warn("登录失败,回退免登录: {}", failRes.getMessage());
|
||||
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||
}).onSuccess(r-> {
|
||||
httpRequest.setTemplateParam("appToken", token)
|
||||
httpRequest.setTemplateParam("appToken", token())
|
||||
.putHeaders(header);
|
||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
});
|
||||
} else {
|
||||
// 验证token
|
||||
// 验证token — 先从缓存恢复到 header
|
||||
header.set("appToken", token());
|
||||
webClientSession.postAbs(UriTemplate.of(TOKEN_VERIFY_URL))
|
||||
.setTemplateParam("uuid", uuid)
|
||||
.setTemplateParam("ts", tsEncode2)
|
||||
@@ -260,15 +280,15 @@ public class IzTool extends PanBase {
|
||||
// log.info("res: {}",asJson(res));
|
||||
if (asJson(res).getInteger("code") != 200) {
|
||||
login(tsEncode2, auths).onFailure(failRes -> {
|
||||
log.warn("重新登录失败: {}", failRes.getMessage());
|
||||
fail(failRes.getMessage());
|
||||
log.warn("重新登录失败,回退免登录: {}", failRes.getMessage());
|
||||
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||
}).onSuccess(r-> {
|
||||
httpRequest.setTemplateParam("appToken", token)
|
||||
httpRequest.setTemplateParam("appToken", token())
|
||||
.putHeaders(header);
|
||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
});
|
||||
} else {
|
||||
httpRequest.setTemplateParam("appToken", token)
|
||||
httpRequest.setTemplateParam("appToken", token())
|
||||
.putHeaders(header);
|
||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
}
|
||||
@@ -277,29 +297,27 @@ public class IzTool extends PanBase {
|
||||
} else {
|
||||
// authFlag 为 false,使用免登录解析
|
||||
log.debug("authFlag=false,使用免登录解析");
|
||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
||||
.putHeaders(header)
|
||||
.setTemplateParam("fidEncode", fidEncode)
|
||||
.setTemplateParam("uuid", uuid)
|
||||
.setTemplateParam("ts", tsEncode2)
|
||||
.setTemplateParam("auth", auth)
|
||||
.setTemplateParam("dataKey", dataKey).send()
|
||||
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||
}
|
||||
} else {
|
||||
// 没有认证信息,使用免登录解析
|
||||
log.debug("无认证信息,使用免登录解析");
|
||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
||||
.putHeaders(header)
|
||||
.setTemplateParam("fidEncode", fidEncode)
|
||||
.setTemplateParam("uuid", uuid)
|
||||
.setTemplateParam("ts", tsEncode2)
|
||||
.setTemplateParam("auth", auth)
|
||||
.setTemplateParam("dataKey", dataKey).send()
|
||||
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||
}
|
||||
}
|
||||
|
||||
private void downloadAnonymous(String fidEncode, String tsEncode2, String auth, String dataKey) {
|
||||
log.debug("使用免登录解析");
|
||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
||||
.putHeaders(header)
|
||||
.setTemplateParam("fidEncode", fidEncode)
|
||||
.setTemplateParam("uuid", uuid)
|
||||
.setTemplateParam("ts", tsEncode2)
|
||||
.setTemplateParam("auth", auth)
|
||||
.setTemplateParam("dataKey", dataKey).send()
|
||||
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
}
|
||||
|
||||
private Future<Void> login(String tsEncode2, MultiMap auths) {
|
||||
Promise<Void> promise1 = Promise.promise();
|
||||
webClientSession.postAbs(UriTemplate.of(LOGIN_URL))
|
||||
@@ -310,8 +328,13 @@ public class IzTool extends PanBase {
|
||||
.onSuccess(res2->{
|
||||
JsonObject json = asJson(res2);
|
||||
if (json.getInteger("code") == 200) {
|
||||
token = json.getJsonObject("data").getString("appToken");
|
||||
log.info("登录成功 token: {}...", token != null ? token.substring(0, Math.min(8, token.length())) : "null");
|
||||
String loginToken = json.getJsonObject("data").getString("appToken");
|
||||
TokenCache.putToken(cacheKey, loginToken);
|
||||
TokenCache.queueCachedTokenPersist(cacheKey, loginToken, System.currentTimeMillis() + 24 * 60 * 60 * 1000L);
|
||||
if (loginToken != null) {
|
||||
header.set("appToken", loginToken);
|
||||
}
|
||||
log.info("登录成功 token: {}...", loginToken != null ? loginToken.substring(0, Math.min(8, loginToken.length())) : "null");
|
||||
promise1.complete();
|
||||
} else {
|
||||
// 检查是否为临时认证
|
||||
@@ -323,7 +346,7 @@ public class IzTool extends PanBase {
|
||||
} else {
|
||||
// 后台配置的认证失败,设置authFlag并返回失败,让下次请求使用免登陆解析
|
||||
log.warn("后台配置认证失败: {}, authFlag将设为false,请重新解析", json.getString("msg"));
|
||||
authFlag = false;
|
||||
TokenCache.putFlag(cacheKey, false);
|
||||
promise1.fail("认证失败: " + json.getString("msg") + ", 请重新解析将使用免登陆模式");
|
||||
}
|
||||
}
|
||||
@@ -443,75 +466,75 @@ public class IzTool extends PanBase {
|
||||
}
|
||||
}
|
||||
|
||||
private void down(HttpResponse<Buffer> res2) {
|
||||
MultiMap headers = res2.headers();
|
||||
String location = headers.get("Location");
|
||||
if (StringUtils.isBlank(location)) {
|
||||
fail("{}", buildMissingLocationMessage(res2));
|
||||
return;
|
||||
}
|
||||
promise.complete(location);
|
||||
}
|
||||
|
||||
private String buildMissingLocationMessage(HttpResponse<Buffer> response) {
|
||||
StringBuilder message = new StringBuilder("未获取到下载重定向地址");
|
||||
message.append(", HTTP ").append(response.statusCode());
|
||||
|
||||
String body = null;
|
||||
try {
|
||||
body = asText(response);
|
||||
} catch (Exception e) {
|
||||
body = "<响应体读取失败: " + e.getMessage() + ">";
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(body)) {
|
||||
try {
|
||||
JsonObject json = new JsonObject(body);
|
||||
String upstreamMsg = json.getString("msg");
|
||||
Object code = json.getValue("code");
|
||||
if (StringUtils.isNotBlank(upstreamMsg)) {
|
||||
message.append(", 上游返回: ").append(upstreamMsg);
|
||||
if (code != null) {
|
||||
message.append(" (code=").append(code).append(")");
|
||||
}
|
||||
} else {
|
||||
message.append(", 响应体: ").append(previewBody(body));
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
message.append(", 响应体: ").append(previewBody(body));
|
||||
}
|
||||
} else {
|
||||
message.append(", 响应体为空");
|
||||
}
|
||||
|
||||
Object fileName = shareLinkInfo.getOtherParam().get("fileName");
|
||||
Object fileSize = shareLinkInfo.getOtherParam().get("fileSizeFormat");
|
||||
if (fileName != null) {
|
||||
message.append(", 文件: ").append(fileName);
|
||||
}
|
||||
if (fileSize != null) {
|
||||
message.append(", 大小: ").append(fileSize);
|
||||
}
|
||||
if (!hasConfiguredAuth()) {
|
||||
message.append(", 当前为免登录解析,上游可能要求登录、会员或人工处理");
|
||||
}
|
||||
return message.toString();
|
||||
}
|
||||
|
||||
private boolean hasConfiguredAuth() {
|
||||
Object authObj = shareLinkInfo.getOtherParam().get("auths");
|
||||
if (!(authObj instanceof MultiMap auths)) {
|
||||
return false;
|
||||
}
|
||||
return StringUtils.isNotBlank(auths.get("username")) && StringUtils.isNotBlank(auths.get("password"));
|
||||
}
|
||||
|
||||
private String previewBody(String body) {
|
||||
int maxLength = 500;
|
||||
return body.length() <= maxLength ? body : body.substring(0, maxLength) + "...";
|
||||
}
|
||||
|
||||
// 目录解析
|
||||
private void down(HttpResponse<Buffer> res2) {
|
||||
MultiMap headers = res2.headers();
|
||||
String location = headers.get("Location");
|
||||
if (StringUtils.isBlank(location)) {
|
||||
fail("{}", buildMissingLocationMessage(res2));
|
||||
return;
|
||||
}
|
||||
promise.complete(location);
|
||||
}
|
||||
|
||||
private String buildMissingLocationMessage(HttpResponse<Buffer> response) {
|
||||
StringBuilder message = new StringBuilder("未获取到下载重定向地址");
|
||||
message.append(", HTTP ").append(response.statusCode());
|
||||
|
||||
String body = null;
|
||||
try {
|
||||
body = asText(response);
|
||||
} catch (Exception e) {
|
||||
body = "<响应体读取失败: " + e.getMessage() + ">";
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(body)) {
|
||||
try {
|
||||
JsonObject json = new JsonObject(body);
|
||||
String upstreamMsg = json.getString("msg");
|
||||
Object code = json.getValue("code");
|
||||
if (StringUtils.isNotBlank(upstreamMsg)) {
|
||||
message.append(", 上游返回: ").append(upstreamMsg);
|
||||
if (code != null) {
|
||||
message.append(" (code=").append(code).append(")");
|
||||
}
|
||||
} else {
|
||||
message.append(", 响应体: ").append(previewBody(body));
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
message.append(", 响应体: ").append(previewBody(body));
|
||||
}
|
||||
} else {
|
||||
message.append(", 响应体为空");
|
||||
}
|
||||
|
||||
Object fileName = shareLinkInfo.getOtherParam().get("fileName");
|
||||
Object fileSize = shareLinkInfo.getOtherParam().get("fileSizeFormat");
|
||||
if (fileName != null) {
|
||||
message.append(", 文件: ").append(fileName);
|
||||
}
|
||||
if (fileSize != null) {
|
||||
message.append(", 大小: ").append(fileSize);
|
||||
}
|
||||
if (!hasConfiguredAuth()) {
|
||||
message.append(", 当前为免登录解析,上游可能要求登录、会员或人工处理");
|
||||
}
|
||||
return message.toString();
|
||||
}
|
||||
|
||||
private boolean hasConfiguredAuth() {
|
||||
Object authObj = shareLinkInfo.getOtherParam().get("auths");
|
||||
if (!(authObj instanceof MultiMap auths)) {
|
||||
return false;
|
||||
}
|
||||
return StringUtils.isNotBlank(auths.get("username")) && StringUtils.isNotBlank(auths.get("password"));
|
||||
}
|
||||
|
||||
private String previewBody(String body) {
|
||||
int maxLength = 500;
|
||||
return body.length() <= maxLength ? body : body.substring(0, maxLength) + "...";
|
||||
}
|
||||
|
||||
// 目录解析
|
||||
@Override
|
||||
public Future<List<FileInfo>> parseFileList() {
|
||||
Promise<List<FileInfo>> promise = Promise.promise();
|
||||
@@ -691,7 +714,6 @@ public class IzTool extends PanBase {
|
||||
}
|
||||
|
||||
public static void resetToken() {
|
||||
token = null;
|
||||
authFlag = true;
|
||||
TokenCache.removeByDiskType("iz");
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,7 @@ public class IzToolWithAuth extends PanBase {
|
||||
}
|
||||
public IzToolWithAuth(ShareLinkInfo shareLinkInfo) {
|
||||
super(shareLinkInfo);
|
||||
IzXffHeader.apply(header);
|
||||
}
|
||||
|
||||
String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
|
||||
@@ -213,8 +214,8 @@ public class IzToolWithAuth extends PanBase {
|
||||
if (token == null) {
|
||||
// 执行登录
|
||||
login(tsEncode2, auths).onFailure(failRes-> {
|
||||
log.warn("登录失败: {}", failRes.getMessage());
|
||||
fail(failRes.getMessage());
|
||||
log.warn("登录失败,回退免登录: {}", failRes.getMessage());
|
||||
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||
}).onSuccess(r-> {
|
||||
httpRequest.setTemplateParam("appToken", token)
|
||||
.putHeaders(header);
|
||||
@@ -229,8 +230,8 @@ public class IzToolWithAuth extends PanBase {
|
||||
// log.info("res: {}",asJson(res));
|
||||
if (asJson(res).getInteger("code") != 200) {
|
||||
login(tsEncode2, auths).onFailure(failRes -> {
|
||||
log.warn("重新登录失败: {}", failRes.getMessage());
|
||||
fail(failRes.getMessage());
|
||||
log.warn("重新登录失败,回退免登录: {}", failRes.getMessage());
|
||||
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||
}).onSuccess(r-> {
|
||||
httpRequest.setTemplateParam("appToken", token)
|
||||
.putHeaders(header);
|
||||
@@ -246,29 +247,27 @@ public class IzToolWithAuth extends PanBase {
|
||||
} else {
|
||||
// authFlag 为 false,使用免登录解析
|
||||
log.debug("authFlag=false,使用免登录解析");
|
||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
||||
.putHeaders(header)
|
||||
.setTemplateParam("fidEncode", fidEncode)
|
||||
.setTemplateParam("uuid", uuid)
|
||||
.setTemplateParam("ts", tsEncode2)
|
||||
.setTemplateParam("auth", auth)
|
||||
.setTemplateParam("dataKey", dataKey).send()
|
||||
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||
}
|
||||
} else {
|
||||
// 没有认证信息,使用免登录解析
|
||||
log.debug("无认证信息,使用免登录解析");
|
||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
||||
.putHeaders(header)
|
||||
.setTemplateParam("fidEncode", fidEncode)
|
||||
.setTemplateParam("uuid", uuid)
|
||||
.setTemplateParam("ts", tsEncode2)
|
||||
.setTemplateParam("auth", auth)
|
||||
.setTemplateParam("dataKey", dataKey).send()
|
||||
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
downloadAnonymous(fidEncode, tsEncode2, auth, dataKey);
|
||||
}
|
||||
}
|
||||
|
||||
private void downloadAnonymous(String fidEncode, String tsEncode2, String auth, String dataKey) {
|
||||
log.debug("使用免登录解析");
|
||||
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL))
|
||||
.putHeaders(header)
|
||||
.setTemplateParam("fidEncode", fidEncode)
|
||||
.setTemplateParam("uuid", uuid)
|
||||
.setTemplateParam("ts", tsEncode2)
|
||||
.setTemplateParam("auth", auth)
|
||||
.setTemplateParam("dataKey", dataKey).send()
|
||||
.onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
}
|
||||
|
||||
private Future<Void> login(String tsEncode2, MultiMap auths) {
|
||||
Promise<Void> promise1 = Promise.promise();
|
||||
webClientSession.postAbs(UriTemplate.of(LOGIN_URL))
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import io.vertx.core.MultiMap;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* 蓝奏云优享 X-Forwarded-For 配置。
|
||||
* <p>
|
||||
* 读取系统属性 {@code nfd.iz.xff},其次环境变量 {@code NFD_IZ_XFF}:
|
||||
* <ul>
|
||||
* <li>未设置 / 空 / {@code off}:不发送该头(默认)</li>
|
||||
* <li>{@code random}:每次创建解析器时随机一个国内常见网段 IP</li>
|
||||
* <li>其它值:原样作为头的值,例如 {@code 113.96.181.18}</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class IzXffHeader {
|
||||
|
||||
public static final String PROP = "nfd.iz.xff";
|
||||
public static final String ENV = "NFD_IZ_XFF";
|
||||
private static final String HEADER = "X-Forwarded-For";
|
||||
|
||||
/** 国内运营商常见 /8 段首字节 */
|
||||
private static final int[] CN_PREFIX = {36, 39, 42, 58, 59, 60, 61, 101, 106, 110, 111, 112, 113, 114,
|
||||
115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 175, 180, 182, 183, 202, 210, 211, 218, 219, 220, 221, 222, 223};
|
||||
|
||||
private IzXffHeader() {
|
||||
}
|
||||
|
||||
static String configured() {
|
||||
String v = System.getProperty(PROP);
|
||||
if (StringUtils.isBlank(v)) {
|
||||
v = System.getenv(ENV);
|
||||
}
|
||||
return v == null ? "" : v.trim();
|
||||
}
|
||||
|
||||
/** 根据配置得到头的值,返回 null 表示不发送 */
|
||||
static String resolve(String mode) {
|
||||
if (StringUtils.isBlank(mode) || "off".equalsIgnoreCase(mode)) {
|
||||
return null;
|
||||
}
|
||||
if ("random".equalsIgnoreCase(mode)) {
|
||||
ThreadLocalRandom r = ThreadLocalRandom.current();
|
||||
return CN_PREFIX[r.nextInt(CN_PREFIX.length)] + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + (1 + r.nextInt(254));
|
||||
}
|
||||
return mode;
|
||||
}
|
||||
|
||||
/** 按当前配置写入或移除请求头 */
|
||||
public static void apply(MultiMap headers) {
|
||||
String value = resolve(configured());
|
||||
if (value == null) {
|
||||
headers.remove(HEADER);
|
||||
} else {
|
||||
headers.set(HEADER, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.util.Base64Encoder;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.PanBase;
|
||||
@@ -13,7 +14,6 @@ import io.vertx.core.json.JsonObject;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
@@ -232,7 +232,7 @@ public class LeTool extends PanBase {
|
||||
"shareId", shareId,
|
||||
"fileId", fileId
|
||||
);
|
||||
String paramBase64 = Base64.getEncoder().encodeToString(paramJson.encode().getBytes());
|
||||
String paramBase64 = Base64Encoder.encode(paramJson.encode().getBytes());
|
||||
|
||||
// 设置解析URL和预览URL
|
||||
fileInfo.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
@@ -22,6 +24,7 @@ import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -48,9 +51,27 @@ public class QkTool extends PanBase {
|
||||
// 多账号隔离:用 TokenCache 代替 static cookie 缓存
|
||||
// __puus 有效期,默认 55 分钟(服务器实际 1 小时过期,提前 5 分钟刷新)
|
||||
private static final long PUUS_TTL_MS = 55 * 60 * 1000L;
|
||||
|
||||
/** 根目录经常只有一层文件夹,继续向下找文件。#275 这类分享要再进一层。 */
|
||||
static final int MAX_FOLDER_DEPTH = 4;
|
||||
/** 同一层最多进入的文件夹数,避免把整棵目录树都请求一遍。 */
|
||||
static final int MAX_FOLDERS_PER_LEVEL = 12;
|
||||
/** 访客直链失败(23018)后,按体积从小到大再试几个文件。 */
|
||||
static final int MAX_GUEST_DOWNLOAD_ATTEMPTS = 6;
|
||||
|
||||
static final String EMPTY_SHARE_MSG = "分享目录为空,或只包含空文件夹。解析已经进入子目录查找。";
|
||||
static final String GUEST_OVERSIZE_MSG =
|
||||
"夸克访客只能免登录下载小文件,当前文件超过访客大小限制(上游 23018 download file size limit)。"
|
||||
+ "请在本机配置夸克 Cookie:auths.qk.cookie,或在解析请求中携带 auth。"
|
||||
+ "未配置 Cookie 时不会转存。大文件需要绑定账号后交给下载器,浏览器里直接打开也经常失败。";
|
||||
static final String GUEST_LOGIN_MSG =
|
||||
"夸克要求登录后才能下载。请配置 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
|
||||
@@ -216,8 +237,8 @@ public class QkTool extends PanBase {
|
||||
log.debug("第一阶段响应: {}", res.bodyAsString());
|
||||
JsonObject resJson = asJson(res);
|
||||
|
||||
if (resJson.getInteger("code") != 0) {
|
||||
fail(TOKEN_URL + " 返回异常: " + resJson);
|
||||
if (resJson.getInteger("code") == null || resJson.getInteger("code") != 0) {
|
||||
fail(quarkApiFailure(TOKEN_URL, resJson));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -228,106 +249,373 @@ public class QkTool extends PanBase {
|
||||
}
|
||||
|
||||
log.debug("成功获取 stoken: {}", stoken);
|
||||
|
||||
// 第二步:获取文件列表
|
||||
client.getAbs(DETAIL_URL)
|
||||
.addQueryParam("pr", "ucpro")
|
||||
.addQueryParam("fr", "pc")
|
||||
.addQueryParam("pwd_id", pwdId)
|
||||
.addQueryParam("stoken", stoken)
|
||||
.addQueryParam("pdir_fid", "0")
|
||||
.addQueryParam("force", "0")
|
||||
.addQueryParam("_page", "1")
|
||||
.addQueryParam("_size", "50")
|
||||
.addQueryParam("_fetch_banner", "1")
|
||||
.addQueryParam("_fetch_share", "1")
|
||||
.addQueryParam("_fetch_total", "1")
|
||||
.addQueryParam("_sort", "file_type:asc,updated_at:desc")
|
||||
.putHeaders(header)
|
||||
.send()
|
||||
.onSuccess(res2 -> {
|
||||
log.debug("第二阶段响应: {}", res2.bodyAsString());
|
||||
JsonObject resJson2 = asJson(res2);
|
||||
|
||||
if (resJson2.getInteger("code") != 0) {
|
||||
fail(DETAIL_URL + " 返回异常: " + resJson2);
|
||||
return;
|
||||
}
|
||||
|
||||
JsonArray fileList = resJson2.getJsonObject("data").getJsonArray("list");
|
||||
if (fileList == null || fileList.isEmpty()) {
|
||||
fail("未找到文件");
|
||||
return;
|
||||
}
|
||||
|
||||
// 过滤出文件(排除文件夹)
|
||||
List<JsonObject> files = new ArrayList<>();
|
||||
for (int i = 0; i < fileList.size(); i++) {
|
||||
JsonObject item = fileList.getJsonObject(i);
|
||||
// 判断是否为文件:file=true 或 obj_category 不为空
|
||||
if (item.getBoolean("file", false) ||
|
||||
(item.getString("obj_category") != null && !item.getString("obj_category").isEmpty())) {
|
||||
files.add(item);
|
||||
}
|
||||
}
|
||||
|
||||
if (files.isEmpty()) {
|
||||
fail("没有可下载的文件(可能都是文件夹)");
|
||||
return;
|
||||
}
|
||||
|
||||
log.debug("找到 {} 个文件", files.size());
|
||||
|
||||
// 提取第一个文件的信息并保存到 otherParam
|
||||
try {
|
||||
JsonObject firstFile = files.get(0);
|
||||
FileInfo fileInfo = new FileInfo();
|
||||
fileInfo.setFileId(firstFile.getString("fid"))
|
||||
.setFileName(firstFile.getString("file_name"))
|
||||
.setSize(firstFile.getLong("size", 0L))
|
||||
.setSizeStr(FileSizeConverter.convertToReadableSize(firstFile.getLong("size", 0L)))
|
||||
.setFileType(firstFile.getBoolean("file", true) ? "file" : "folder")
|
||||
.setCreateTime(formatEpochMs(firstFile.getLong("updated_at", 0L)))
|
||||
.setUpdateTime(formatEpochMs(firstFile.getLong("updated_at", 0L)))
|
||||
.setPanType(shareLinkInfo.getType());
|
||||
|
||||
// 保存到 otherParam,供 CacheServiceImpl 使用
|
||||
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
|
||||
log.debug("夸克提取文件信息: {}", fileInfo.getFileName());
|
||||
} catch (Exception e) {
|
||||
log.warn("夸克提取文件信息失败,继续解析: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// 提取文件ID列表
|
||||
List<String> fileIds = new ArrayList<>();
|
||||
for (JsonObject file : files) {
|
||||
String fid = file.getString("fid");
|
||||
if (fid != null && !fid.isEmpty()) {
|
||||
fileIds.add(fid);
|
||||
}
|
||||
}
|
||||
|
||||
if (fileIds.isEmpty()) {
|
||||
fail("无法提取文件ID");
|
||||
return;
|
||||
}
|
||||
|
||||
// 第三步:解析下载链接(先直链,必要时才转存)
|
||||
JsonObject firstFileForDownload = files.get(0);
|
||||
String firstFid = firstFileForDownload.getString("fid");
|
||||
String firstShareFidToken = firstFileForDownload.getString("share_fid_token");
|
||||
|
||||
resolveDownloadUrl(firstFid, pwdId, stoken, firstShareFidToken)
|
||||
.onSuccess(downloadUrl -> completeWithMeta(downloadUrl, buildDownloadHeaders(null)))
|
||||
.onFailure(handleFail("获取下载链接"));
|
||||
|
||||
}).onFailure(handleFail(DETAIL_URL));
|
||||
// 根目录可能只是文件夹(#282)。先列出再进入,找到文件后再取直链。
|
||||
findDownloadableFiles(pwdId, stoken, "0", 0)
|
||||
.compose(files -> resolveListedFiles(files, pwdId, stoken))
|
||||
.onSuccess(this::finishParse)
|
||||
.onFailure(t -> fail(t.getMessage() == null ? "解析失败" : t.getMessage()));
|
||||
})
|
||||
.onFailure(handleFail(TOKEN_URL));
|
||||
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
private Future<String> resolveListedFiles(List<JsonObject> files, String pwdId, String stoken) {
|
||||
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()) {
|
||||
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,再按体积从小到大试同目录里的其他文件。
|
||||
*/
|
||||
private Future<String> resolveGuestDownloads(List<JsonObject> files, String pwdId, String stoken,
|
||||
int index, int attempts) {
|
||||
if (index >= files.size() || attempts >= MAX_GUEST_DOWNLOAD_ATTEMPTS) {
|
||||
return Future.failedFuture(GUEST_OVERSIZE_MSG);
|
||||
}
|
||||
JsonObject file = files.get(index);
|
||||
String fid = file.getString("fid");
|
||||
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"))
|
||||
.compose(url -> {
|
||||
rememberFile(file);
|
||||
return Future.succeededFuture(url);
|
||||
})
|
||||
.recover(err -> {
|
||||
if (needsTransferFallback(err)) {
|
||||
log.info("夸克访客跳过超过大小限制的文件 {} ({} bytes)",
|
||||
file.getString("file_name"), fileSize(file));
|
||||
return resolveGuestDownloads(files, pwdId, stoken, index + 1, attempts + 1);
|
||||
}
|
||||
if (isGuestAuthError(err)) {
|
||||
return Future.failedFuture(GUEST_LOGIN_MSG);
|
||||
}
|
||||
return Future.failedFuture(err);
|
||||
});
|
||||
}
|
||||
|
||||
private Future<List<JsonObject>> findDownloadableFiles(String pwdId, String stoken, String pdirFid, int depth) {
|
||||
return fetchShareList(pwdId, stoken, pdirFid).compose(list -> {
|
||||
List<JsonObject> files = new ArrayList<>();
|
||||
List<JsonObject> folders = new ArrayList<>();
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
JsonObject item = list.getJsonObject(i);
|
||||
if (isQuarkFile(item)) {
|
||||
files.add(item);
|
||||
} else if (isQuarkFolder(item)) {
|
||||
folders.add(item);
|
||||
}
|
||||
}
|
||||
if (hasPositiveSize(files) || folders.isEmpty() || depth >= MAX_FOLDER_DEPTH) {
|
||||
return Future.succeededFuture(preferSizedFiles(files));
|
||||
}
|
||||
int limit = Math.min(folders.size(), MAX_FOLDERS_PER_LEVEL);
|
||||
List<JsonObject> placeholders = files;
|
||||
return firstFolderWithFiles(pwdId, stoken, folders.subList(0, limit), 0, depth + 1)
|
||||
.compose(nested -> {
|
||||
if (nested != null && !nested.isEmpty()) {
|
||||
return Future.succeededFuture(nested);
|
||||
}
|
||||
return Future.succeededFuture(placeholders);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private Future<List<JsonObject>> firstFolderWithFiles(String pwdId, String stoken, List<JsonObject> folders,
|
||||
int index, int depth) {
|
||||
if (index >= folders.size()) {
|
||||
return Future.succeededFuture(new ArrayList<>());
|
||||
}
|
||||
JsonObject folder = folders.get(index);
|
||||
String fid = folder.getString("fid");
|
||||
if (fid == null || fid.isEmpty()) {
|
||||
return firstFolderWithFiles(pwdId, stoken, folders, index + 1, depth);
|
||||
}
|
||||
log.debug("夸克进入子目录 depth={} name={}", depth, folder.getString("file_name"));
|
||||
return findDownloadableFiles(pwdId, stoken, fid, depth).compose(files -> {
|
||||
if (hasPositiveSize(files)) {
|
||||
return Future.succeededFuture(files);
|
||||
}
|
||||
return firstFolderWithFiles(pwdId, stoken, folders, index + 1, depth).compose(later -> {
|
||||
if (later != null && !later.isEmpty()) {
|
||||
return Future.succeededFuture(later);
|
||||
}
|
||||
return Future.succeededFuture(files == null ? new ArrayList<>() : files);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private Future<JsonArray> fetchShareList(String pwdId, String stoken, String pdirFid) {
|
||||
Promise<JsonArray> listPromise = Promise.promise();
|
||||
client.getAbs(DETAIL_URL)
|
||||
.addQueryParam("pr", "ucpro")
|
||||
.addQueryParam("fr", "pc")
|
||||
.addQueryParam("pwd_id", pwdId)
|
||||
.addQueryParam("stoken", stoken)
|
||||
.addQueryParam("pdir_fid", pdirFid == null || pdirFid.isEmpty() ? "0" : pdirFid)
|
||||
.addQueryParam("force", "0")
|
||||
.addQueryParam("_page", "1")
|
||||
.addQueryParam("_size", "50")
|
||||
.addQueryParam("_fetch_banner", "0")
|
||||
.addQueryParam("_fetch_share", "1")
|
||||
.addQueryParam("_fetch_total", "1")
|
||||
.addQueryParam("_sort", "file_type:asc,updated_at:desc")
|
||||
.putHeaders(header)
|
||||
.send()
|
||||
.onSuccess(res -> {
|
||||
JsonObject json = asJson(res);
|
||||
if (json.getInteger("code") == null || json.getInteger("code") != 0) {
|
||||
listPromise.fail(quarkApiFailure(DETAIL_URL, json));
|
||||
return;
|
||||
}
|
||||
JsonObject data = json.getJsonObject("data");
|
||||
JsonArray list = data == null ? null : data.getJsonArray("list");
|
||||
listPromise.complete(list == null ? new JsonArray() : list);
|
||||
})
|
||||
.onFailure(t -> listPromise.fail("获取分享目录失败: " + t.getMessage()));
|
||||
return listPromise.future();
|
||||
}
|
||||
|
||||
private void rememberFile(JsonObject file) {
|
||||
try {
|
||||
long size = fileSize(file);
|
||||
if (size == Long.MAX_VALUE) {
|
||||
size = 0L;
|
||||
}
|
||||
FileInfo fileInfo = new FileInfo()
|
||||
.setFileId(file.getString("fid"))
|
||||
.setFileName(file.getString("file_name"))
|
||||
.setSize(size)
|
||||
.setSizeStr(FileSizeConverter.convertToReadableSize(size))
|
||||
.setFileType("file")
|
||||
.setCreateTime(formatEpochMs(epochMs(file, "updated_at")))
|
||||
.setUpdateTime(formatEpochMs(epochMs(file, "updated_at")))
|
||||
.setPanType(shareLinkInfo.getType());
|
||||
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
|
||||
log.debug("夸克提取文件信息: {}", fileInfo.getFileName());
|
||||
} catch (Exception e) {
|
||||
log.warn("夸克提取文件信息失败,继续解析: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasQuarkCookie() {
|
||||
String cookie = header.get(HttpHeaders.COOKIE);
|
||||
return cookie != null && !cookie.isBlank();
|
||||
}
|
||||
|
||||
/**
|
||||
* 访客候选:保留接口返回的第一个文件,其余按体积从小到大。
|
||||
* 这样小文件分享仍先下最新文件;文件夹里最新文件超限时,再改下同目录的小文件。
|
||||
*/
|
||||
static List<JsonObject> orderGuestCandidates(List<JsonObject> files) {
|
||||
List<JsonObject> ordered = new ArrayList<>();
|
||||
if (files == null || files.isEmpty()) {
|
||||
return ordered;
|
||||
}
|
||||
ordered.add(files.get(0));
|
||||
if (files.size() == 1) {
|
||||
return ordered;
|
||||
}
|
||||
List<JsonObject> rest = new ArrayList<>(files.subList(1, files.size()));
|
||||
rest.sort(Comparator.comparingLong(QkTool::fileSize));
|
||||
ordered.addAll(rest);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
static boolean isQuarkFolder(JsonObject item) {
|
||||
if (item == null) {
|
||||
return false;
|
||||
}
|
||||
if (quarkFlag(item, "dir")) {
|
||||
return true;
|
||||
}
|
||||
Integer fileType = intValue(item, "file_type");
|
||||
return fileType != null && fileType == 0 && !quarkFlag(item, "file");
|
||||
}
|
||||
|
||||
static boolean isQuarkFile(JsonObject item) {
|
||||
if (item == null || isQuarkFolder(item)) {
|
||||
return false;
|
||||
}
|
||||
if (quarkFlag(item, "file")) {
|
||||
return true;
|
||||
}
|
||||
Integer fileType = intValue(item, "file_type");
|
||||
if (fileType != null && fileType > 0) {
|
||||
return true;
|
||||
}
|
||||
String category = item.getString("obj_category");
|
||||
return category != null && !category.isEmpty();
|
||||
}
|
||||
|
||||
static boolean isGuestAuthError(Throwable t) {
|
||||
String msg = t == null || t.getMessage() == null ? "" : t.getMessage();
|
||||
return msg.contains("31001")
|
||||
|| msg.contains("未登录")
|
||||
|| msg.contains("require login")
|
||||
|| msg.contains("Cookie 已失效");
|
||||
}
|
||||
|
||||
static String quarkApiFailure(String url, JsonObject json) {
|
||||
Integer code = json == null ? null : intValue(json, "code");
|
||||
String message = json == null ? null : json.getString("message");
|
||||
if ((code != null && code == 41010) || (message != null && message.contains("违规"))) {
|
||||
return "夸克判定该分享涉及违规内容,无法解析(上游 code=" + code
|
||||
+ (message == null ? "" : "," + message)
|
||||
+ ")。请让分享者更换资源,本项目不能绕过网盘审核。";
|
||||
}
|
||||
return url + " 返回异常: " + json;
|
||||
}
|
||||
|
||||
private static boolean quarkFlag(JsonObject item, String key) {
|
||||
Object value = item.getValue(key);
|
||||
if (value instanceof Boolean) {
|
||||
return (Boolean) value;
|
||||
}
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).intValue() != 0;
|
||||
}
|
||||
if (value instanceof String) {
|
||||
return "true".equalsIgnoreCase((String) value) || "1".equals(value);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Integer intValue(JsonObject item, String key) {
|
||||
Object value = item.getValue(key);
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).intValue();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static boolean hasPositiveSize(List<JsonObject> files) {
|
||||
if (files == null) {
|
||||
return false;
|
||||
}
|
||||
for (JsonObject file : files) {
|
||||
long size = fileSize(file);
|
||||
if (size > 0 && size != Long.MAX_VALUE) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 同一目录里有正常文件时,忽略 0 字节占位文件。 */
|
||||
static List<JsonObject> preferSizedFiles(List<JsonObject> files) {
|
||||
List<JsonObject> sized = new ArrayList<>();
|
||||
if (files == null) {
|
||||
return sized;
|
||||
}
|
||||
for (JsonObject file : files) {
|
||||
long size = fileSize(file);
|
||||
if (size > 0 && size != Long.MAX_VALUE) {
|
||||
sized.add(file);
|
||||
}
|
||||
}
|
||||
return sized.isEmpty() ? new ArrayList<>(files) : sized;
|
||||
}
|
||||
|
||||
static long fileSize(JsonObject item) {
|
||||
if (item == null) {
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
Object value = item.getValue("size");
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).longValue();
|
||||
}
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
|
||||
private static long epochMs(JsonObject item, String key) {
|
||||
Object value = item.getValue(key);
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).longValue();
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一下载入口(parse / parseById 共用):
|
||||
* <ol>
|
||||
@@ -353,7 +641,7 @@ public class QkTool extends PanBase {
|
||||
* 是否属于「必须转存」类错误。
|
||||
* 典型:code 23018 download file size limit(分享直链有大小限制)。
|
||||
*/
|
||||
private static boolean needsTransferFallback(Throwable t) {
|
||||
static boolean needsTransferFallback(Throwable t) {
|
||||
String msg = t == null || t.getMessage() == null ? "" : t.getMessage();
|
||||
return msg.contains("23018")
|
||||
|| msg.contains("size limit")
|
||||
@@ -538,8 +826,7 @@ public class QkTool extends PanBase {
|
||||
.setUpdateTime(updatedAt)
|
||||
.setPanType(shareLinkInfo.getType());
|
||||
|
||||
// 判断是否为文件:file=true 或 obj_category 不为空
|
||||
if (isFile || (objCategory != null && !objCategory.isEmpty())) {
|
||||
if (isQuarkFile(item)) {
|
||||
// 文件
|
||||
fileInfo.setFileType("file");
|
||||
// 保存必要的参数用于后续下载
|
||||
@@ -550,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);
|
||||
@@ -620,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);
|
||||
|
||||
@@ -690,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);
|
||||
@@ -788,8 +1093,13 @@ public class QkTool extends PanBase {
|
||||
.send()
|
||||
.onSuccess(res -> {
|
||||
JsonObject resJson = asJson(res);
|
||||
if (resJson.getInteger("code") != 0) {
|
||||
promise.fail("获取转存目录失败: " + resJson.getString("message"));
|
||||
if (resJson.getInteger("code") == null || resJson.getInteger("code") != 0) {
|
||||
String message = resJson.getString("message");
|
||||
if (message != null && (message.contains("require login") || message.contains("guest"))) {
|
||||
promise.fail(GUEST_LOGIN_MSG);
|
||||
return;
|
||||
}
|
||||
promise.fail("获取转存目录失败: " + message);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@ package cn.qaiu.parser.impl;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.PanBase;
|
||||
import cn.qaiu.parser.PasswordLoginRisk;
|
||||
import cn.qaiu.parser.TokenCache;
|
||||
import cn.qaiu.util.CommonUtils;
|
||||
import cn.qaiu.util.Base64Decoder;
|
||||
import cn.qaiu.util.FileSizeConverter;
|
||||
import cn.qaiu.util.YeShareHostUtil;
|
||||
import io.vertx.core.Future;
|
||||
@@ -22,7 +24,6 @@ import java.net.MalformedURLException;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
@@ -188,7 +189,12 @@ public class Ye2Tool extends PanBase {
|
||||
.onSuccess(res -> {
|
||||
JsonObject shareInfoJson = asJson(res);
|
||||
if (shareInfoJson.getInteger("code") != 0) {
|
||||
fail("获取分享信息失败: " + shareInfoJson.getString("message"));
|
||||
String message = shareInfoJson.getString("message");
|
||||
if (isYeLoginRequired(shareInfoJson.getInteger("code"), message)) {
|
||||
fail(loginRequiredDownloadMessage(!"nologin".equals(token), message));
|
||||
return;
|
||||
}
|
||||
fail("获取分享信息失败: " + message);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -205,7 +211,7 @@ public class Ye2Tool extends PanBase {
|
||||
|
||||
JsonObject fileInfo = data.getJsonArray("InfoList").getJsonObject(0);
|
||||
if (token.equals("nologin")) {
|
||||
fail("该分享需要登录才能下载,请配置认证信息");
|
||||
fail(loginRequiredDownloadMessage(false, null));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -272,24 +278,27 @@ public class Ye2Tool extends PanBase {
|
||||
.putHeader("platform", "web")
|
||||
.sendJsonObject(loginBody)
|
||||
.onSuccess(res -> {
|
||||
JsonObject json = res.bodyAsJsonObject();
|
||||
JsonObject json;
|
||||
try {
|
||||
json = res.bodyAsJsonObject();
|
||||
} catch (Exception e) {
|
||||
promise.fail(PasswordLoginRisk.nonJsonLoginFailure(res.bodyAsString()));
|
||||
return;
|
||||
}
|
||||
if (json == null) {
|
||||
promise.fail("登录响应格式异常: " + res.bodyAsString());
|
||||
promise.fail(PasswordLoginRisk.nonJsonLoginFailure(res.bodyAsString()));
|
||||
return;
|
||||
}
|
||||
if (!json.containsKey("code")) {
|
||||
promise.fail("登录响应格式异常: " + res.bodyAsString());
|
||||
return;
|
||||
}
|
||||
if (json.getInteger("code") != 200) {
|
||||
promise.fail("登录失败: " + json.getString("message"));
|
||||
// 验证码/风控只提示改用 Authorization,不求解、不重试。
|
||||
if (!PasswordLoginRisk.isLoginSuccess(json)) {
|
||||
promise.fail(PasswordLoginRisk.describeLoginFailure(json));
|
||||
return;
|
||||
}
|
||||
JsonObject data = json.getJsonObject("data");
|
||||
if (data == null || !data.containsKey("token")) {
|
||||
promise.fail("未获取到token");
|
||||
return;
|
||||
}
|
||||
String ssoToken = data.getString("token");
|
||||
String expireStr = data.getString("expire");
|
||||
long expireMs;
|
||||
@@ -438,9 +447,47 @@ public class Ye2Tool extends PanBase {
|
||||
.onFailure(err -> fail("文件夹打包下载接口失败: " + err.getMessage()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 123 下载接口要求登录时的说明。分享列表本身经常可以匿名读取,
|
||||
* 真正拦下载的是 5112 / 请登录后下载,需要调用方自己的 Authorization。
|
||||
*/
|
||||
static String loginRequiredDownloadMessage(boolean authConfigured, String upstream) {
|
||||
String msg = authConfigured
|
||||
? "123网盘仍要求登录或触发了风控。请在本机检查 auths.ye.authorization(与 auths.ye.token 等价)"
|
||||
+ "或账号密码是否仍然有效。公共云解析没有共享 123 账号。"
|
||||
+ "上游常见返回:5112、请登录后下载、您需要注册登录或付费后下载。"
|
||||
: "123网盘这个分享需要登录后才能下载。请在本机部署,并配置 auths.ye.authorization"
|
||||
+ "(与 auths.ye.token 等价;浏览器登录后的 authorToken、请求头 authorization 或 Cookie sso-token,不要重复带 Bearer),"
|
||||
+ "或配置 auths.ye.username 与 password。公共云解析没有共享 123 账号,不能代登。"
|
||||
+ "约 10MB 的小文件有时可以直链,大文件、文件夹打包以及 5112/请登录后下载必须使用你自己的 Authorization。"
|
||||
+ "短链格式是 ye:分享key@提取码;链接里的 # 片段会去掉。"
|
||||
+ "yun.123pan.com、www.123pan.com 和 *.share.123pan.cn 都是同一类分享。";
|
||||
if (StringUtils.isNotBlank(upstream)) {
|
||||
String brief = upstream.length() > 180 ? upstream.substring(0, 180) : upstream;
|
||||
msg = msg + " 上游信息: " + brief;
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
static boolean isYeLoginRequired(Integer code, String message) {
|
||||
if (code != null && (code == 5112 || code == 401)) {
|
||||
return true;
|
||||
}
|
||||
if (message == null) {
|
||||
return false;
|
||||
}
|
||||
return message.contains("请登录") || message.contains("需要登录") || message.contains("注册登录");
|
||||
}
|
||||
|
||||
private void handleDownloadUrlResponse(WebClient client, JsonObject downURLJson, String failPrefix) {
|
||||
try {
|
||||
if (downURLJson.getInteger("code") != 0) {
|
||||
Integer code = downURLJson.getInteger("code");
|
||||
if (code != 0) {
|
||||
String message = downURLJson.getString("message");
|
||||
if (isYeLoginRequired(code, message)) {
|
||||
fail(loginRequiredDownloadMessage(true, message));
|
||||
return;
|
||||
}
|
||||
fail(failPrefix + "返回值异常->" + downURLJson);
|
||||
return;
|
||||
}
|
||||
@@ -467,7 +514,7 @@ public class Ye2Tool extends PanBase {
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] decodeByte = Base64.getDecoder().decode(params);
|
||||
byte[] decodeByte = Base64Decoder.decode(params);
|
||||
String downUrl2 = new String(decodeByte);
|
||||
|
||||
clientNoRedirects.getAbs(downUrl2).putHeaders(header).send().onSuccess(res3 -> {
|
||||
@@ -542,27 +589,35 @@ public class Ye2Tool extends PanBase {
|
||||
Future<String> tokenFuture = resolveTokenFuture();
|
||||
String finalParentFileId = parentFileId;
|
||||
tokenFuture.onSuccess(token -> {
|
||||
if (token.equals("nologin")) {
|
||||
promise.fail("该分享需要登录才能访问,请配置认证信息");
|
||||
return;
|
||||
// 分享列表接口可以不登录。下载才经常返回 5112。
|
||||
boolean loggedIn = StringUtils.isNotEmpty(token) && !"nologin".equals(token);
|
||||
if (loggedIn) {
|
||||
header.set("Authorization", "Bearer " + token);
|
||||
}
|
||||
|
||||
String normalizedShareKey = YeShareHostUtil.normalizeShareKey(shareKey);
|
||||
String shareOrigin = resolveYeShareOrigin(normalizedShareKey);
|
||||
String shareReferer = buildShareReferer(shareOrigin, normalizedShareKey, pwd);
|
||||
|
||||
client.getAbs(UriTemplate.of(GET_SHARE_INFO_URL))
|
||||
HttpRequest<Buffer> request = client.getAbs(UriTemplate.of(GET_SHARE_INFO_URL))
|
||||
.setTemplateParam("shareKey", shareKey)
|
||||
.setTemplateParam("pwd", StringUtils.isEmpty(pwd) ? "" : pwd)
|
||||
.setTemplateParam("ParentFileId", finalParentFileId)
|
||||
.putHeader("Authorization", "Bearer " + token)
|
||||
.putHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
|
||||
.putHeader("Referer", shareReferer)
|
||||
.putHeader("Origin", shareOrigin)
|
||||
.send().onSuccess(res -> {
|
||||
.putHeader("Origin", shareOrigin);
|
||||
if (loggedIn) {
|
||||
request.putHeader("Authorization", "Bearer " + token);
|
||||
}
|
||||
request.send().onSuccess(res -> {
|
||||
JsonObject response = asJson(res);
|
||||
if (response.getInteger("code") != 0) {
|
||||
promise.fail("API错误: " + response.getString("message"));
|
||||
String message = response.getString("message");
|
||||
if (isYeLoginRequired(response.getInteger("code"), message)) {
|
||||
promise.fail(loginRequiredDownloadMessage(loggedIn, message));
|
||||
return;
|
||||
}
|
||||
promise.fail("API错误: " + message);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -637,7 +692,7 @@ public class Ye2Tool extends PanBase {
|
||||
|
||||
tokenFuture.onSuccess(token -> {
|
||||
if (token.equals("nologin")) {
|
||||
fail("该分享需要登录才能下载,请配置认证信息");
|
||||
fail(loginRequiredDownloadMessage(false, null));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.util.Base64Encoder;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.PanBase;
|
||||
import cn.qaiu.util.CommonUtils;
|
||||
import cn.qaiu.util.Base64Decoder;
|
||||
import cn.qaiu.util.FileSizeConverter;
|
||||
import cn.qaiu.util.JsExecUtils;
|
||||
import io.vertx.core.Future;
|
||||
@@ -21,7 +23,6 @@ import java.net.MalformedURLException;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -166,7 +167,7 @@ public class YeTool extends PanBase {
|
||||
try {
|
||||
Map<String, String> urlParams = CommonUtils.getURLParams(downURL);
|
||||
String params = urlParams.get("params");
|
||||
byte[] decodeByte = Base64.getDecoder().decode(params);
|
||||
byte[] decodeByte = Base64Decoder.decode(params);
|
||||
String downUrl2 = new String(decodeByte);
|
||||
|
||||
// 获取直链
|
||||
@@ -261,7 +262,7 @@ public class YeTool extends PanBase {
|
||||
.put("Size", item.getLong("Size"))
|
||||
.put("Etag", item.getString("Etag"));
|
||||
|
||||
byte[] encode = Base64.getEncoder().encode(postData.encode().getBytes());
|
||||
byte[] encode = Base64Encoder.encodeBytes(postData.encode().getBytes());
|
||||
String param = new String(encode);
|
||||
|
||||
if (item.getInteger("Type") == 0) { // 文件
|
||||
|
||||
@@ -11,7 +11,6 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.*;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.HexFormat;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -131,13 +130,13 @@ public class AESUtils {
|
||||
public static String encryptBase64ByAES(String source, String keyString) throws NoSuchPaddingException,
|
||||
NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
|
||||
byte[] encrypted = encryptByAES(source, keyString);
|
||||
return Base64.getEncoder().encodeToString(encrypted);
|
||||
return Base64Encoder.encode(encrypted);
|
||||
}
|
||||
|
||||
public static String encryptBase64ByAES(String source, Key key) throws NoSuchPaddingException,
|
||||
NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
|
||||
byte[] encrypted = encryptByAES(source, key);
|
||||
return Base64.getEncoder().encodeToString(encrypted);
|
||||
return Base64Encoder.encode(encrypted);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -219,12 +218,12 @@ public class AESUtils {
|
||||
*/
|
||||
public static String decryptByBase64AES(String encrypted, String keyString) throws IllegalBlockSizeException,
|
||||
BadPaddingException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException {
|
||||
return decryptByAES(Base64.getDecoder().decode(encrypted), keyString);
|
||||
return decryptByAES(Base64Decoder.decode(encrypted), keyString);
|
||||
}
|
||||
|
||||
public static String decryptByBase64AES(String encrypted, Key key) throws IllegalBlockSizeException,
|
||||
BadPaddingException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException {
|
||||
return decryptByAES(Base64.getDecoder().decode(encrypted), key);
|
||||
return decryptByAES(Base64Decoder.decode(encrypted), key);
|
||||
}
|
||||
|
||||
// ================================飞机盘Id解密========================================== //
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package cn.qaiu.util;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Strict Base64 decoding without the HotSpot Base64 intrinsic (CVE-2026-114938).
|
||||
* Like the JDK's String decoder, this reads ISO-8859-1 bytes.
|
||||
* Unmappable characters become '?', which is rejected by both alphabets.
|
||||
*/
|
||||
public final class Base64Decoder {
|
||||
private static final byte[] BASIC = alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
|
||||
private static final byte[] URL_SAFE = alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
|
||||
|
||||
private Base64Decoder() {
|
||||
}
|
||||
|
||||
public static byte[] decode(String input) {
|
||||
return decode(input.getBytes(StandardCharsets.ISO_8859_1), BASIC);
|
||||
}
|
||||
|
||||
public static byte[] decodeUrl(String input) {
|
||||
return decode(input.getBytes(StandardCharsets.ISO_8859_1), URL_SAFE);
|
||||
}
|
||||
|
||||
private static byte[] decode(byte[] input, byte[] alphabet) {
|
||||
int length = input.length;
|
||||
int dataLength = length;
|
||||
if (dataLength > 0 && input[dataLength - 1] == '=') {
|
||||
dataLength--;
|
||||
if (dataLength > 0 && input[dataLength - 1] == '=') {
|
||||
dataLength--;
|
||||
}
|
||||
}
|
||||
|
||||
int remainder = dataLength % 4;
|
||||
int padding = length - dataLength;
|
||||
if (remainder == 1 || (padding != 0 && remainder + padding != 4)) {
|
||||
throw new IllegalArgumentException("Invalid Base64 padding or length");
|
||||
}
|
||||
|
||||
int groupEnd = dataLength - remainder;
|
||||
byte[] decoded = new byte[(groupEnd / 4) * 3 + (remainder == 0 ? 0 : remainder - 1)];
|
||||
int start = Base64Encoder.useVectors(groupEnd)
|
||||
? VectorBase64.decode(input, groupEnd, decoded, alphabet == URL_SAFE) : 0;
|
||||
int outputIndex = start / 4 * 3;
|
||||
// Each complete group consumes exactly four characters and writes exactly three bytes.
|
||||
for (int i = start; i < groupEnd; i += 4) {
|
||||
int a = alphabet[input[i] & 0xff];
|
||||
int b = alphabet[input[i + 1] & 0xff];
|
||||
int c = alphabet[input[i + 2] & 0xff];
|
||||
int d = alphabet[input[i + 3] & 0xff];
|
||||
if ((a | b | c | d) < 0) {
|
||||
throw new IllegalArgumentException("Invalid Base64 character");
|
||||
}
|
||||
int bits = (a << 18) | (b << 12) | (c << 6) | d;
|
||||
decoded[outputIndex++] = (byte) (bits >>> 16);
|
||||
decoded[outputIndex++] = (byte) (bits >>> 8);
|
||||
decoded[outputIndex++] = (byte) bits;
|
||||
}
|
||||
|
||||
// The two possible tails consume two or three characters and write one or two bytes.
|
||||
if (remainder != 0) {
|
||||
int a = alphabet[input[groupEnd] & 0xff];
|
||||
int b = alphabet[input[groupEnd + 1] & 0xff];
|
||||
int c = remainder == 3 ? alphabet[input[groupEnd + 2] & 0xff] : 0;
|
||||
if ((a | b | c) < 0) {
|
||||
throw new IllegalArgumentException("Invalid Base64 character");
|
||||
}
|
||||
decoded[outputIndex] = (byte) ((a << 2) | (b >>> 4));
|
||||
if (remainder == 3) {
|
||||
decoded[outputIndex + 1] = (byte) ((b << 4) | (c >>> 2));
|
||||
}
|
||||
}
|
||||
return decoded;
|
||||
}
|
||||
|
||||
private static byte[] alphabet(String characters) {
|
||||
// Index with an unsigned byte. Every non-alphabet value, including padding, maps to -1.
|
||||
byte[] table = new byte[256];
|
||||
Arrays.fill(table, (byte) -1);
|
||||
for (int i = 0; i < characters.length(); i++) {
|
||||
table[characters.charAt(i)] = (byte) i;
|
||||
}
|
||||
return table;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package cn.qaiu.util;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
public final class Base64Encoder {
|
||||
private static final boolean VECTORS = vectorsAvailable();
|
||||
static final String BASIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
static final String URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
|
||||
private Base64Encoder() {}
|
||||
|
||||
private static boolean vectorsAvailable() {
|
||||
if (java.nio.ByteOrder.nativeOrder() != java.nio.ByteOrder.LITTLE_ENDIAN
|
||||
|| ModuleLayer.boot().findModule("jdk.incubator.vector").isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return VectorBase64.available();
|
||||
} catch (LinkageError unavailableOnThisJdk) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean useVectors(int length) {
|
||||
return VECTORS && length >= 1024;
|
||||
}
|
||||
|
||||
public static String encode(byte[] data) {
|
||||
return useVectors(data.length) ? new String(vectorEncode(data, false), StandardCharsets.ISO_8859_1)
|
||||
: Base64.getEncoder().encodeToString(data);
|
||||
}
|
||||
|
||||
public static byte[] encodeBytes(byte[] data) {
|
||||
return useVectors(data.length) ? vectorEncode(data, false) : Base64.getEncoder().encode(data);
|
||||
}
|
||||
|
||||
public static String encodeUrlWithoutPadding(byte[] data) {
|
||||
return useVectors(data.length) ? new String(vectorEncode(data, true), StandardCharsets.ISO_8859_1)
|
||||
: Base64.getUrlEncoder().withoutPadding().encodeToString(data);
|
||||
}
|
||||
|
||||
private static byte[] vectorEncode(byte[] input, boolean url) {
|
||||
int remainder = input.length % 3;
|
||||
int tailLength = remainder + 1;
|
||||
if (remainder == 0) {
|
||||
tailLength = 0;
|
||||
} else if (!url) {
|
||||
tailLength = 4;
|
||||
}
|
||||
long length = (long) (input.length / 3) * 4 + tailLength;
|
||||
if (length > Integer.MAX_VALUE) {
|
||||
throw new OutOfMemoryError("Base64 output exceeds maximum array length");
|
||||
}
|
||||
byte[] output = new byte[(int) length];
|
||||
int src = VectorBase64.encode(input, output, url);
|
||||
int dst = src / 3 * 4;
|
||||
String alphabet = url ? URL : BASIC;
|
||||
while (src < input.length) {
|
||||
int bytes = Math.min(3, input.length - src);
|
||||
int bits = (input[src++] & 255) << 16;
|
||||
if (bytes >= 2) {
|
||||
bits |= (input[src++] & 255) << 8;
|
||||
}
|
||||
if (bytes == 3) {
|
||||
bits |= input[src++] & 255;
|
||||
}
|
||||
for (int shift = 18; shift >= 18 - bytes * 6; shift -= 6) {
|
||||
output[dst++] = (byte) alphabet.charAt((bits >>> shift) & 63);
|
||||
}
|
||||
}
|
||||
java.util.Arrays.fill(output, dst, output.length, (byte) '=');
|
||||
return output;
|
||||
}
|
||||
}
|
||||
@@ -100,12 +100,12 @@ public class CommonUtils {
|
||||
Exception last = null;
|
||||
for (String candidate : new String[]{s, padBase64(s)}) {
|
||||
try {
|
||||
return new String(java.util.Base64.getUrlDecoder().decode(candidate), StandardCharsets.UTF_8);
|
||||
return new String(Base64Decoder.decodeUrl(candidate), StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
last = e;
|
||||
}
|
||||
try {
|
||||
return new String(java.util.Base64.getDecoder().decode(candidate), StandardCharsets.UTF_8);
|
||||
return new String(Base64Decoder.decode(candidate), StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
last = e;
|
||||
}
|
||||
@@ -118,9 +118,7 @@ public class CommonUtils {
|
||||
* <p>不再做 URLEncoder,避免前端/代理再 encode 时变成 %253D。</p>
|
||||
*/
|
||||
public static String urlBase64Encode(String str) {
|
||||
return java.util.Base64.getUrlEncoder()
|
||||
.withoutPadding()
|
||||
.encodeToString(str.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64Encoder.encodeUrlWithoutPadding(str.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static String padBase64(String s) {
|
||||
|
||||
@@ -119,8 +119,18 @@ public class HttpResponseHelper {
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean looksLikeGzip(Buffer compressed) {
|
||||
return compressed != null && compressed.length() >= 2
|
||||
&& (compressed.getByte(0) & 0xff) == 0x1f
|
||||
&& (compressed.getByte(1) & 0xff) == 0x8b;
|
||||
}
|
||||
|
||||
// -------------------- gzip --------------------
|
||||
private static String decompressGzip(Buffer compressed) throws IOException {
|
||||
// Vert.x 可能已解压但仍带 Content-Encoding: gzip,再走 GZIPInputStream 会变成 ZipException
|
||||
if (!looksLikeGzip(compressed)) {
|
||||
return compressed.toString(StandardCharsets.UTF_8);
|
||||
}
|
||||
try (ByteArrayInputStream bais = new ByteArrayInputStream(compressed.getBytes());
|
||||
GZIPInputStream gzis = new GZIPInputStream(bais);
|
||||
InputStreamReader isr = new InputStreamReader(gzis, StandardCharsets.UTF_8);
|
||||
|
||||
@@ -101,59 +101,384 @@ public interface JsContent {
|
||||
""";
|
||||
String lz = """
|
||||
/**
|
||||
* 蓝奏云解析器js签名获取工具
|
||||
* 蓝奏云解析器 JS 沙箱:伪装 jQuery / document / window。
|
||||
* 新版页面会用 document.cookie、location.reload、querySelector、
|
||||
* $('#pwd').val()、.html()、.css() 等,这里做成可链式的最小实现。
|
||||
* kdns.js 在浏览器里是 `var killdns = true`,需一并注入,否则 kd 会被改成 0。
|
||||
*/
|
||||
|
||||
var signObj;
|
||||
var __lzPwd = '';
|
||||
var killdns = true;
|
||||
|
||||
function __lzSetPwd(p) {
|
||||
__lzPwd = p == null ? '' : String(p);
|
||||
}
|
||||
|
||||
function __lzEl(id) {
|
||||
var nid = String(id == null ? '' : id).replace(/^[#.]/, '');
|
||||
var el = {
|
||||
id: nid,
|
||||
_value: nid === 'pwd' ? __lzPwd : '',
|
||||
checked: false,
|
||||
disabled: false,
|
||||
innerHTML: '',
|
||||
innerText: '',
|
||||
textContent: '',
|
||||
className: '',
|
||||
style: { display: '', visibility: '', width: '', height: '' },
|
||||
classList: {
|
||||
add: function () {},
|
||||
remove: function () {},
|
||||
contains: function () { return false; },
|
||||
toggle: function () {}
|
||||
},
|
||||
setAttribute: function () {},
|
||||
getAttribute: function () { return null; },
|
||||
removeAttribute: function () {},
|
||||
addEventListener: function (t, fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
},
|
||||
removeEventListener: function () {},
|
||||
appendChild: function (n) { return n; },
|
||||
removeChild: function (n) { return n; },
|
||||
insertBefore: function (n) { return n; },
|
||||
click: function () {},
|
||||
focus: function () {},
|
||||
blur: function () {},
|
||||
submit: function () {},
|
||||
select: function () {},
|
||||
reset: function () {}
|
||||
};
|
||||
el.parentNode = el;
|
||||
el.parentElement = el;
|
||||
el.children = [];
|
||||
el.childNodes = [];
|
||||
el.firstChild = null;
|
||||
el.lastChild = null;
|
||||
try {
|
||||
Object.defineProperty(el, 'value', {
|
||||
get: function () { return nid === 'pwd' ? __lzPwd : el._value; },
|
||||
set: function (v) {
|
||||
el._value = v;
|
||||
if (nid === 'pwd') {
|
||||
__lzPwd = v == null ? '' : String(v);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
el.value = el._value;
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
function __lzJq(sel) {
|
||||
var id = '';
|
||||
if (typeof sel === 'string') {
|
||||
id = sel.replace(/^[#.]/, '');
|
||||
} else if (sel && sel.id) {
|
||||
id = String(sel.id);
|
||||
}
|
||||
var el = (sel && sel.style && sel.addEventListener) ? sel : __lzEl(id);
|
||||
var api = {
|
||||
0: el,
|
||||
length: 1,
|
||||
selector: sel,
|
||||
ready: function (fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(jQuery); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
on: function (t, fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
off: function () { return api; },
|
||||
bind: function (t, fn) { return api.on(t, fn); },
|
||||
unbind: function () { return api; },
|
||||
click: function (fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
focus: function (fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
blur: function () { return api; },
|
||||
keyup: function (fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
keydown: function (fn) { return api.keyup(fn); },
|
||||
keypress: function (fn) { return api.keyup(fn); },
|
||||
submit: function (fn) { return api.click(fn); },
|
||||
change: function (fn) { return api.click(fn); },
|
||||
hover: function () { return api; },
|
||||
val: function (v) {
|
||||
if (arguments.length === 0) {
|
||||
if (typeof el.value !== 'undefined') {
|
||||
return el.value;
|
||||
}
|
||||
return (id === 'pwd') ? __lzPwd : '';
|
||||
}
|
||||
el.value = v;
|
||||
return api;
|
||||
},
|
||||
html: function (v) {
|
||||
if (arguments.length === 0) {
|
||||
return el.innerHTML;
|
||||
}
|
||||
el.innerHTML = v;
|
||||
return api;
|
||||
},
|
||||
text: function (v) {
|
||||
if (arguments.length === 0) {
|
||||
return el.innerText;
|
||||
}
|
||||
el.innerText = v;
|
||||
el.textContent = v;
|
||||
return api;
|
||||
},
|
||||
attr: function (k, v) {
|
||||
if (arguments.length < 2) {
|
||||
return null;
|
||||
}
|
||||
return api;
|
||||
},
|
||||
prop: function (k, v) {
|
||||
if (arguments.length < 2) {
|
||||
return false;
|
||||
}
|
||||
return api;
|
||||
},
|
||||
css: function () { return api; },
|
||||
addClass: function () { return api; },
|
||||
removeClass: function () { return api; },
|
||||
toggleClass: function () { return api; },
|
||||
hasClass: function () { return false; },
|
||||
show: function () {
|
||||
el.style.display = '';
|
||||
return api;
|
||||
},
|
||||
hide: function () {
|
||||
el.style.display = 'none';
|
||||
return api;
|
||||
},
|
||||
fadeIn: function () { return api; },
|
||||
fadeOut: function () { return api; },
|
||||
animate: function () { return api; },
|
||||
find: function () { return api; },
|
||||
parent: function () { return api; },
|
||||
children: function () { return api; },
|
||||
eq: function () { return api; },
|
||||
first: function () { return api; },
|
||||
last: function () { return api; },
|
||||
each: function (fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn.call(el, 0, el); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
append: function () { return api; },
|
||||
prepend: function () { return api; },
|
||||
remove: function () { return api; },
|
||||
empty: function () { return api; },
|
||||
ajax: function (obj) {
|
||||
signObj = obj;
|
||||
return api;
|
||||
},
|
||||
get: function () { return el; }
|
||||
};
|
||||
return api;
|
||||
}
|
||||
|
||||
var $, jQuery;
|
||||
|
||||
$ = jQuery = function () {
|
||||
return new jQuery.fn.init();
|
||||
}
|
||||
$ = jQuery = function (sel) {
|
||||
if (typeof sel === 'function') {
|
||||
try { sel(jQuery); } catch (e) {}
|
||||
return __lzJq(document);
|
||||
}
|
||||
return __lzJq(sel);
|
||||
};
|
||||
|
||||
jQuery.fn = jQuery.prototype = {
|
||||
init: function () {
|
||||
return {
|
||||
focus: function (a) {
|
||||
|
||||
},
|
||||
keyup: function(a) {
|
||||
|
||||
},
|
||||
ajax: function (obj) {
|
||||
signObj = obj
|
||||
},
|
||||
val: function(a) {
|
||||
|
||||
},
|
||||
|
||||
}
|
||||
},
|
||||
|
||||
}
|
||||
|
||||
init: function (sel) {
|
||||
return __lzJq(sel);
|
||||
}
|
||||
};
|
||||
jQuery.fn.init.prototype = jQuery.fn;
|
||||
|
||||
$.fn = jQuery.fn;
|
||||
|
||||
$.ajax = function (obj) {
|
||||
signObj = obj
|
||||
}
|
||||
signObj = obj;
|
||||
return {
|
||||
done: function () { return this; },
|
||||
fail: function () { return this; },
|
||||
always: function () { return this; }
|
||||
};
|
||||
};
|
||||
$.get = function () {};
|
||||
$.post = function () {};
|
||||
$.extend = function () {
|
||||
var t = arguments[0] || {};
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
var s = arguments[i];
|
||||
if (s) {
|
||||
for (var k in s) {
|
||||
if (s.hasOwnProperty(k)) {
|
||||
t[k] = s[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return t;
|
||||
};
|
||||
$.each = function (obj, fn) {
|
||||
if (!obj || typeof fn !== 'function') {
|
||||
return obj;
|
||||
}
|
||||
if (typeof obj.length === 'number') {
|
||||
for (var i = 0; i < obj.length; i++) {
|
||||
fn.call(obj[i], i, obj[i]);
|
||||
}
|
||||
} else {
|
||||
for (var k in obj) {
|
||||
if (obj.hasOwnProperty(k)) {
|
||||
fn.call(obj[k], k, obj[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
$.isFunction = function (f) { return typeof f === 'function'; };
|
||||
$.isArray = function (a) {
|
||||
return Object.prototype.toString.call(a) === '[object Array]';
|
||||
};
|
||||
$.trim = function (s) {
|
||||
return s == null ? '' : String(s).replace(/^\\s+|\\s+$/g, '');
|
||||
};
|
||||
|
||||
var __lzLocation = {
|
||||
href: '',
|
||||
search: '',
|
||||
pathname: '/',
|
||||
hash: '',
|
||||
host: '',
|
||||
hostname: '',
|
||||
protocol: 'https:',
|
||||
port: '',
|
||||
origin: '',
|
||||
assign: function () {},
|
||||
replace: function () {},
|
||||
reload: function () {}
|
||||
};
|
||||
|
||||
var document = {
|
||||
getElementById: function (v) {
|
||||
return {
|
||||
value: 'v',
|
||||
style: {
|
||||
display: ''
|
||||
},
|
||||
addEventListener: function() {}
|
||||
cookie: '',
|
||||
title: '',
|
||||
domain: '',
|
||||
referrer: '',
|
||||
readyState: 'complete',
|
||||
hidden: false,
|
||||
visibilityState: 'visible',
|
||||
documentElement: null,
|
||||
body: null,
|
||||
head: null,
|
||||
location: __lzLocation,
|
||||
getElementById: function (id) { return __lzEl(id); },
|
||||
getElementsByClassName: function () { return []; },
|
||||
getElementsByTagName: function (t) {
|
||||
return t === 'script' ? [] : [__lzEl(t)];
|
||||
},
|
||||
getElementsByName: function () { return []; },
|
||||
querySelector: function (s) { return __lzEl(s); },
|
||||
querySelectorAll: function (s) { return [__lzEl(s)]; },
|
||||
createElement: function (t) { return __lzEl(t); },
|
||||
createTextNode: function (t) { return { nodeValue: t, data: t }; },
|
||||
createDocumentFragment: function () { return __lzEl('fragment'); },
|
||||
addEventListener: function (t, fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
},
|
||||
removeEventListener: function () {},
|
||||
write: function () {},
|
||||
writeln: function () {},
|
||||
open: function () {},
|
||||
close: function () {}
|
||||
};
|
||||
document.documentElement = __lzEl('html');
|
||||
document.body = __lzEl('body');
|
||||
document.head = __lzEl('head');
|
||||
|
||||
var navigator = {
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
|
||||
platform: 'Win32',
|
||||
language: 'zh-CN',
|
||||
cookieEnabled: true,
|
||||
onLine: true
|
||||
};
|
||||
|
||||
var location = __lzLocation;
|
||||
var console = {
|
||||
log: function () {},
|
||||
warn: function () {},
|
||||
error: function () {},
|
||||
info: function () {},
|
||||
debug: function () {}
|
||||
};
|
||||
|
||||
function setTimeout(fn, delay) {
|
||||
if (typeof fn === 'function' && (!delay || delay <= 0)) {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
var window = {location: {}}
|
||||
function setInterval() { return 0; }
|
||||
function clearTimeout() {}
|
||||
function clearInterval() {}
|
||||
|
||||
var window = {
|
||||
location: __lzLocation,
|
||||
document: document,
|
||||
navigator: navigator,
|
||||
console: console,
|
||||
innerWidth: 1920,
|
||||
innerHeight: 1080,
|
||||
setTimeout: setTimeout,
|
||||
setInterval: setInterval,
|
||||
clearTimeout: clearTimeout,
|
||||
clearInterval: clearInterval,
|
||||
addEventListener: function (t, fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
},
|
||||
removeEventListener: function () {},
|
||||
atob: function (s) { return s; },
|
||||
btoa: function (s) { return s; }
|
||||
};
|
||||
window.window = window;
|
||||
window.top = window;
|
||||
window.self = window;
|
||||
window.parent = window;
|
||||
window.jQuery = jQuery;
|
||||
window.$ = $;
|
||||
|
||||
var top = window;
|
||||
var self = window;
|
||||
var parent = window;
|
||||
""";
|
||||
|
||||
String kwSignString = """
|
||||
|
||||
@@ -50,21 +50,47 @@ public class JsExecUtils {
|
||||
*/
|
||||
public static ScriptObjectMirror executeDynamicJs(String jsText, String funName) throws ScriptException,
|
||||
NoSuchMethodException {
|
||||
ScriptEngine engine = ENGINE_MANAGER.getEngineByName("JavaScript"); // 得到脚本引擎
|
||||
return executeDynamicJs(jsText, funName, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param pwd 分享密码,写入伪 DOM(#pwd / getElementById('pwd')),供新版页面取值
|
||||
*/
|
||||
public static ScriptObjectMirror executeDynamicJs(String jsText, String funName, String pwd) throws ScriptException,
|
||||
NoSuchMethodException {
|
||||
ScriptEngine engine = ENGINE_MANAGER.getEngineByName("JavaScript");
|
||||
try {
|
||||
engine.eval(JsContent.lz + "\n" + jsText);
|
||||
engine.eval(JsContent.lz);
|
||||
Invocable inv = (Invocable) engine;
|
||||
//调用js中的函数
|
||||
if (StringUtils.isNotEmpty(funName)) {
|
||||
inv.invokeFunction(funName);
|
||||
if (pwd != null) {
|
||||
inv.invokeFunction("__lzSetPwd", pwd);
|
||||
}
|
||||
return (ScriptObjectMirror) engine.get("signObj");
|
||||
try {
|
||||
engine.eval(jsText);
|
||||
if (StringUtils.isNotEmpty(funName)) {
|
||||
inv.invokeFunction(funName);
|
||||
}
|
||||
} catch (ScriptException | NoSuchMethodException | RuntimeException e) {
|
||||
ScriptObjectMirror captured = asSignObj(engine.get("signObj"));
|
||||
if (captured != null) {
|
||||
return captured;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return asSignObj(engine.get("signObj"));
|
||||
} finally {
|
||||
// 清理引擎持有的引用,帮助 GC 回收
|
||||
clearEngineBindings(engine);
|
||||
}
|
||||
}
|
||||
|
||||
private static ScriptObjectMirror asSignObj(Object sign) {
|
||||
if (sign instanceof ScriptObjectMirror mirror
|
||||
&& (mirror.get("url") != null || mirror.get("data") != null)) {
|
||||
return mirror;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 调用执行js文件(使用缓存的 ScriptEngineManager 创建新引擎实例)
|
||||
|
||||
@@ -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,125 @@
|
||||
package cn.qaiu.util;
|
||||
|
||||
import jdk.incubator.vector.ByteVector;
|
||||
import jdk.incubator.vector.IntVector;
|
||||
import jdk.incubator.vector.VectorMask;
|
||||
import jdk.incubator.vector.VectorShuffle;
|
||||
import jdk.incubator.vector.VectorSpecies;
|
||||
|
||||
import static jdk.incubator.vector.VectorOperators.*;
|
||||
|
||||
final class VectorBase64 {
|
||||
private static final VectorSpecies<Byte> SPECIES = ByteVector.SPECIES_PREFERRED;
|
||||
private static final int WIDTH = SPECIES.length();
|
||||
private static final int PACKED = WIDTH / 4 * 3;
|
||||
private static final VectorMask<Byte> PACKED_MASK = SPECIES.indexInRange(0, PACKED);
|
||||
// Each four-byte lane holds one quartet. Pack or expand its three binary bytes.
|
||||
private static final VectorShuffle<Byte> PACK = VectorShuffle.fromOp(SPECIES,
|
||||
i -> i < PACKED ? i / 3 * 4 + i % 3 : 0);
|
||||
private static final VectorShuffle<Byte> EXPAND = VectorShuffle.fromOp(SPECIES,
|
||||
i -> i / 4 * 3 + Math.min(i % 4, 2));
|
||||
|
||||
// Each low-nibble entry is a bit set of allowed high nibbles.
|
||||
private static final class Alphabet {
|
||||
final ByteVector lowMasks;
|
||||
final ByteVector highMasks;
|
||||
final ByteVector offsets;
|
||||
final byte last;
|
||||
final ByteVector encodeTable;
|
||||
|
||||
Alphabet(String letters) {
|
||||
byte[] low = new byte[Math.max(WIDTH, 16)];
|
||||
byte[] high = new byte[low.length];
|
||||
byte[] offset = new byte[low.length];
|
||||
byte[] chars = new byte[WIDTH];
|
||||
if (WIDTH >= 64) {
|
||||
for (int i = 0; i < 64; i++) {
|
||||
chars[i] = (byte) letters.charAt(i);
|
||||
}
|
||||
}
|
||||
encodeTable = ByteVector.fromArray(SPECIES, chars, 0);
|
||||
last = (byte) letters.charAt(63);
|
||||
for (int i = 0; i < letters.length(); i++) {
|
||||
int ch = letters.charAt(i);
|
||||
int bucket = ch >>> 4;
|
||||
byte bit = (byte) (1 << bucket);
|
||||
high[bucket] = bit;
|
||||
low[ch & 15] |= bit;
|
||||
if (ch != last) {
|
||||
offset[bucket] = (byte) (i - ch);
|
||||
}
|
||||
}
|
||||
lowMasks = ByteVector.fromArray(SPECIES, low, 0);
|
||||
highMasks = ByteVector.fromArray(SPECIES, high, 0);
|
||||
offsets = ByteVector.fromArray(SPECIES, offset, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static final Alphabet BASIC = new Alphabet(Base64Encoder.BASIC);
|
||||
private static final Alphabet URL = new Alphabet(Base64Encoder.URL);
|
||||
|
||||
private VectorBase64() {}
|
||||
|
||||
static boolean available() {
|
||||
if (WIDTH < 16) {
|
||||
return false;
|
||||
}
|
||||
// Incubator APIs can change between JDK releases. Link both kernels before enabling them.
|
||||
byte[] plain = new byte[PACKED];
|
||||
byte[] encoded = new byte[WIDTH];
|
||||
byte[] decoded = new byte[PACKED];
|
||||
plain[0] = (byte) 0xfb;
|
||||
encode(plain, encoded, true);
|
||||
decode(encoded, WIDTH, decoded, true);
|
||||
return encoded[0] == '-' && java.util.Arrays.equals(plain, decoded);
|
||||
}
|
||||
|
||||
static int decode(byte[] input, int groupEnd, byte[] output, boolean url) {
|
||||
Alphabet alphabet = url ? URL : BASIC;
|
||||
int limit = SPECIES.loopBound(groupEnd);
|
||||
int dst = 0;
|
||||
for (int src = 0; src < limit; src += WIDTH) {
|
||||
ByteVector ascii = ByteVector.fromArray(SPECIES, input, src);
|
||||
ByteVector high = ascii.lanewise(LSHR, 4);
|
||||
ByteVector low = ascii.and((byte) 15);
|
||||
// The low-nibble table records which high nibbles form legal characters.
|
||||
if (high.selectFrom(alphabet.highMasks).and(low.selectFrom(alphabet.lowMasks)).eq((byte) 0).anyTrue()) {
|
||||
throw new IllegalArgumentException("Invalid Base64 character");
|
||||
}
|
||||
ByteVector values = ascii.add(high.selectFrom(alphabet.offsets)).blend((byte) 63, ascii.eq(alphabet.last));
|
||||
// [a,b,c,d] -> [(a<<2)|(b>>4), (b<<4)|(c>>2), (c<<6)|d, unused].
|
||||
IntVector w = values.reinterpretAsInts();
|
||||
IntVector bytes = w.lanewise(LSHL, 2).and(0xfc).or(w.lanewise(LSHR, 12).and(3))
|
||||
.or(w.lanewise(LSHL, 4).and(0xf000)).or(w.lanewise(LSHR, 10).and(0x0f00))
|
||||
.or(w.lanewise(LSHL, 6).and(0xc00000)).or(w.lanewise(LSHR, 8).and(0x3f0000));
|
||||
bytes.reinterpretAsBytes().rearrange(PACK).intoArray(output, dst, PACKED_MASK);
|
||||
dst += PACKED;
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
static int encode(byte[] input, byte[] output, boolean url) {
|
||||
int limit = input.length / PACKED * PACKED;
|
||||
int dst = 0;
|
||||
for (int src = 0; src < limit; src += PACKED) {
|
||||
IntVector w = ByteVector.fromArray(SPECIES, input, src, PACKED_MASK)
|
||||
.rearrange(EXPAND).reinterpretAsInts();
|
||||
// Undo the quartet packing, extracting four six-bit indices per lane.
|
||||
IntVector indices = w.lanewise(LSHR, 2).and(63)
|
||||
.or(w.lanewise(LSHL, 12).and(0x3000)).or(w.lanewise(LSHR, 4).and(0x0f00))
|
||||
.or(w.lanewise(LSHL, 10).and(0x3c0000)).or(w.lanewise(LSHR, 6).and(0x030000))
|
||||
.or(w.lanewise(LSHL, 8).and(0x3f000000));
|
||||
ByteVector v = indices.reinterpretAsBytes();
|
||||
if (WIDTH >= 64) {
|
||||
v.selectFrom((url ? URL : BASIC).encodeTable).intoArray(output, dst);
|
||||
} else {
|
||||
v.add((byte) 'A').blend(v.add((byte) ('a' - 26)), v.compare(GE, (byte) 26))
|
||||
.blend(v.add((byte) ('0' - 52)), v.compare(GE, (byte) 52))
|
||||
.blend((byte) (url ? '-' : '+'), v.eq((byte) 62))
|
||||
.blend((byte) (url ? '_' : '/'), v.eq((byte) 63)).intoArray(output, dst);
|
||||
}
|
||||
dst += WIDTH;
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,10 @@ public final class YeShareHostUtil {
|
||||
return "";
|
||||
}
|
||||
String key = shareKey.trim();
|
||||
int hashIndex = key.indexOf('#');
|
||||
if (hashIndex >= 0) {
|
||||
key = key.substring(0, hashIndex);
|
||||
}
|
||||
int queryIndex = key.indexOf('?');
|
||||
if (queryIndex >= 0) {
|
||||
key = key.substring(0, queryIndex);
|
||||
|
||||
@@ -7,50 +7,7 @@
|
||||
// 全局类型定义,使用JSDoc注释
|
||||
// 这些类型定义将在VSCode中提供代码补全和类型检查
|
||||
|
||||
// ============================================================================
|
||||
// Nashorn Java 互操作全局对象
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Java 全局对象类型定义 (Nashorn引擎提供)
|
||||
* 用于访问Java类型和进行Java互操作
|
||||
* @typedef {Object} JavaGlobal
|
||||
* @property {function(string): any} type - 获取Java类,参数为完整类名(如"java.util.zip.CRC32")
|
||||
* @property {function(any): any} from - 将Java对象转换为JavaScript对象
|
||||
* @property {function(any): any} to - 将JavaScript对象转换为Java对象
|
||||
* @property {function(any): boolean} isType - 检查对象是否为指定Java类型
|
||||
* @property {function(any): boolean} isJavaObject - 检查对象是否为Java对象
|
||||
* @property {function(any): boolean} isJavaMethod - 检查对象是否为Java方法
|
||||
* @property {function(any): boolean} isJavaFunction - 检查对象是否为Java函数
|
||||
*/
|
||||
|
||||
/**
|
||||
* Java 全局对象 (Nashorn引擎提供)
|
||||
* @global
|
||||
* @type {JavaGlobal}
|
||||
*/
|
||||
var Java;
|
||||
|
||||
/**
|
||||
* java 命名空间对象类型定义 (Nashorn引擎提供)
|
||||
* 用于直接访问Java包和类
|
||||
* @typedef {Object} JavaNamespace
|
||||
* @property {Object} lang - java.lang 包
|
||||
* @property {Object} util - java.util 包
|
||||
* @property {Object} io - java.io 包
|
||||
* @property {Object} net - java.net 包
|
||||
* @property {Object} math - java.math 包
|
||||
* @property {Object} security - java.security 包
|
||||
* @property {Object} text - java.text 包
|
||||
* @property {Object} time - java.time 包
|
||||
*/
|
||||
|
||||
/**
|
||||
* java 命名空间对象 (Nashorn引擎提供)
|
||||
* @global
|
||||
* @type {JavaNamespace}
|
||||
*/
|
||||
var java;
|
||||
// 解析脚本通过项目注入的接口访问分享信息、HTTP 和日志。
|
||||
|
||||
/**
|
||||
* @typedef {Object} ShareLinkInfo
|
||||
|
||||
@@ -1,46 +1,379 @@
|
||||
/**
|
||||
* 蓝奏云解析器js签名获取工具
|
||||
* 蓝奏云解析器 JS 沙箱:伪装 jQuery / document / window。
|
||||
* 新版页面会用 document.cookie、location.reload、querySelector、
|
||||
* $('#pwd').val()、.html()、.css() 等,这里做成可链式的最小实现。
|
||||
* kdns.js 在浏览器里是 `var killdns = true`,需一并注入,否则 kd 会被改成 0。
|
||||
*/
|
||||
|
||||
var signObj;
|
||||
var __lzPwd = '';
|
||||
var killdns = true;
|
||||
|
||||
function __lzSetPwd(p) {
|
||||
__lzPwd = p == null ? '' : String(p);
|
||||
}
|
||||
|
||||
function __lzEl(id) {
|
||||
var nid = String(id == null ? '' : id).replace(/^[#.]/, '');
|
||||
var el = {
|
||||
id: nid,
|
||||
_value: nid === 'pwd' ? __lzPwd : '',
|
||||
checked: false,
|
||||
disabled: false,
|
||||
innerHTML: '',
|
||||
innerText: '',
|
||||
textContent: '',
|
||||
className: '',
|
||||
style: { display: '', visibility: '', width: '', height: '' },
|
||||
classList: {
|
||||
add: function () {},
|
||||
remove: function () {},
|
||||
contains: function () { return false; },
|
||||
toggle: function () {}
|
||||
},
|
||||
setAttribute: function () {},
|
||||
getAttribute: function () { return null; },
|
||||
removeAttribute: function () {},
|
||||
addEventListener: function (t, fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
},
|
||||
removeEventListener: function () {},
|
||||
appendChild: function (n) { return n; },
|
||||
removeChild: function (n) { return n; },
|
||||
insertBefore: function (n) { return n; },
|
||||
click: function () {},
|
||||
focus: function () {},
|
||||
blur: function () {},
|
||||
submit: function () {},
|
||||
select: function () {},
|
||||
reset: function () {}
|
||||
};
|
||||
el.parentNode = el;
|
||||
el.parentElement = el;
|
||||
el.children = [];
|
||||
el.childNodes = [];
|
||||
el.firstChild = null;
|
||||
el.lastChild = null;
|
||||
try {
|
||||
Object.defineProperty(el, 'value', {
|
||||
get: function () { return nid === 'pwd' ? __lzPwd : el._value; },
|
||||
set: function (v) {
|
||||
el._value = v;
|
||||
if (nid === 'pwd') {
|
||||
__lzPwd = v == null ? '' : String(v);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
el.value = el._value;
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
function __lzJq(sel) {
|
||||
var id = '';
|
||||
if (typeof sel === 'string') {
|
||||
id = sel.replace(/^[#.]/, '');
|
||||
} else if (sel && sel.id) {
|
||||
id = String(sel.id);
|
||||
}
|
||||
var el = (sel && sel.style && sel.addEventListener) ? sel : __lzEl(id);
|
||||
var api = {
|
||||
0: el,
|
||||
length: 1,
|
||||
selector: sel,
|
||||
ready: function (fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(jQuery); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
on: function (t, fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
off: function () { return api; },
|
||||
bind: function (t, fn) { return api.on(t, fn); },
|
||||
unbind: function () { return api; },
|
||||
click: function (fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
focus: function (fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
blur: function () { return api; },
|
||||
keyup: function (fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
keydown: function (fn) { return api.keyup(fn); },
|
||||
keypress: function (fn) { return api.keyup(fn); },
|
||||
submit: function (fn) { return api.click(fn); },
|
||||
change: function (fn) { return api.click(fn); },
|
||||
hover: function () { return api; },
|
||||
val: function (v) {
|
||||
if (arguments.length === 0) {
|
||||
if (typeof el.value !== 'undefined') {
|
||||
return el.value;
|
||||
}
|
||||
return (id === 'pwd') ? __lzPwd : '';
|
||||
}
|
||||
el.value = v;
|
||||
return api;
|
||||
},
|
||||
html: function (v) {
|
||||
if (arguments.length === 0) {
|
||||
return el.innerHTML;
|
||||
}
|
||||
el.innerHTML = v;
|
||||
return api;
|
||||
},
|
||||
text: function (v) {
|
||||
if (arguments.length === 0) {
|
||||
return el.innerText;
|
||||
}
|
||||
el.innerText = v;
|
||||
el.textContent = v;
|
||||
return api;
|
||||
},
|
||||
attr: function (k, v) {
|
||||
if (arguments.length < 2) {
|
||||
return null;
|
||||
}
|
||||
return api;
|
||||
},
|
||||
prop: function (k, v) {
|
||||
if (arguments.length < 2) {
|
||||
return false;
|
||||
}
|
||||
return api;
|
||||
},
|
||||
css: function () { return api; },
|
||||
addClass: function () { return api; },
|
||||
removeClass: function () { return api; },
|
||||
toggleClass: function () { return api; },
|
||||
hasClass: function () { return false; },
|
||||
show: function () {
|
||||
el.style.display = '';
|
||||
return api;
|
||||
},
|
||||
hide: function () {
|
||||
el.style.display = 'none';
|
||||
return api;
|
||||
},
|
||||
fadeIn: function () { return api; },
|
||||
fadeOut: function () { return api; },
|
||||
animate: function () { return api; },
|
||||
find: function () { return api; },
|
||||
parent: function () { return api; },
|
||||
children: function () { return api; },
|
||||
eq: function () { return api; },
|
||||
first: function () { return api; },
|
||||
last: function () { return api; },
|
||||
each: function (fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn.call(el, 0, el); } catch (e) {}
|
||||
}
|
||||
return api;
|
||||
},
|
||||
append: function () { return api; },
|
||||
prepend: function () { return api; },
|
||||
remove: function () { return api; },
|
||||
empty: function () { return api; },
|
||||
ajax: function (obj) {
|
||||
signObj = obj;
|
||||
return api;
|
||||
},
|
||||
get: function () { return el; }
|
||||
};
|
||||
return api;
|
||||
}
|
||||
|
||||
var $, jQuery;
|
||||
|
||||
$ = jQuery = function () {
|
||||
return new jQuery.fn.init();
|
||||
}
|
||||
$ = jQuery = function (sel) {
|
||||
if (typeof sel === 'function') {
|
||||
try { sel(jQuery); } catch (e) {}
|
||||
return __lzJq(document);
|
||||
}
|
||||
return __lzJq(sel);
|
||||
};
|
||||
|
||||
jQuery.fn = jQuery.prototype = {
|
||||
init: function () {
|
||||
return {
|
||||
focus: function (a) {
|
||||
|
||||
},
|
||||
keyup: function(a) {
|
||||
|
||||
},
|
||||
ajax: function (obj) {
|
||||
signObj = obj
|
||||
}
|
||||
|
||||
}
|
||||
},
|
||||
|
||||
}
|
||||
|
||||
init: function (sel) {
|
||||
return __lzJq(sel);
|
||||
}
|
||||
};
|
||||
jQuery.fn.init.prototype = jQuery.fn;
|
||||
$.fn = jQuery.fn;
|
||||
|
||||
|
||||
// 伪装jquery.ajax函数获取关键数据
|
||||
$.ajax = function (obj) {
|
||||
signObj = obj
|
||||
}
|
||||
signObj = obj;
|
||||
return {
|
||||
done: function () { return this; },
|
||||
fail: function () { return this; },
|
||||
always: function () { return this; }
|
||||
};
|
||||
};
|
||||
$.get = function () {};
|
||||
$.post = function () {};
|
||||
$.extend = function () {
|
||||
var t = arguments[0] || {};
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
var s = arguments[i];
|
||||
if (s) {
|
||||
for (var k in s) {
|
||||
if (s.hasOwnProperty(k)) {
|
||||
t[k] = s[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return t;
|
||||
};
|
||||
$.each = function (obj, fn) {
|
||||
if (!obj || typeof fn !== 'function') {
|
||||
return obj;
|
||||
}
|
||||
if (typeof obj.length === 'number') {
|
||||
for (var i = 0; i < obj.length; i++) {
|
||||
fn.call(obj[i], i, obj[i]);
|
||||
}
|
||||
} else {
|
||||
for (var k in obj) {
|
||||
if (obj.hasOwnProperty(k)) {
|
||||
fn.call(obj[k], k, obj[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
$.isFunction = function (f) { return typeof f === 'function'; };
|
||||
$.isArray = function (a) {
|
||||
return Object.prototype.toString.call(a) === '[object Array]';
|
||||
};
|
||||
$.trim = function (s) {
|
||||
return s == null ? '' : String(s).replace(/^\s+|\s+$/g, '');
|
||||
};
|
||||
|
||||
var __lzLocation = {
|
||||
href: '',
|
||||
search: '',
|
||||
pathname: '/',
|
||||
hash: '',
|
||||
host: '',
|
||||
hostname: '',
|
||||
protocol: 'https:',
|
||||
port: '',
|
||||
origin: '',
|
||||
assign: function () {},
|
||||
replace: function () {},
|
||||
reload: function () {}
|
||||
};
|
||||
|
||||
var document = {
|
||||
getElementById: function (v) {
|
||||
return {
|
||||
value: 'v'
|
||||
cookie: '',
|
||||
title: '',
|
||||
domain: '',
|
||||
referrer: '',
|
||||
readyState: 'complete',
|
||||
hidden: false,
|
||||
visibilityState: 'visible',
|
||||
documentElement: null,
|
||||
body: null,
|
||||
head: null,
|
||||
location: __lzLocation,
|
||||
getElementById: function (id) { return __lzEl(id); },
|
||||
getElementsByClassName: function () { return []; },
|
||||
getElementsByTagName: function (t) {
|
||||
return t === 'script' ? [] : [__lzEl(t)];
|
||||
},
|
||||
getElementsByName: function () { return []; },
|
||||
querySelector: function (s) { return __lzEl(s); },
|
||||
querySelectorAll: function (s) { return [__lzEl(s)]; },
|
||||
createElement: function (t) { return __lzEl(t); },
|
||||
createTextNode: function (t) { return { nodeValue: t, data: t }; },
|
||||
createDocumentFragment: function () { return __lzEl('fragment'); },
|
||||
addEventListener: function (t, fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
},
|
||||
removeEventListener: function () {},
|
||||
write: function () {},
|
||||
writeln: function () {},
|
||||
open: function () {},
|
||||
close: function () {}
|
||||
};
|
||||
document.documentElement = __lzEl('html');
|
||||
document.body = __lzEl('body');
|
||||
document.head = __lzEl('head');
|
||||
|
||||
var navigator = {
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
|
||||
platform: 'Win32',
|
||||
language: 'zh-CN',
|
||||
cookieEnabled: true,
|
||||
onLine: true
|
||||
};
|
||||
|
||||
var location = __lzLocation;
|
||||
var console = {
|
||||
log: function () {},
|
||||
warn: function () {},
|
||||
error: function () {},
|
||||
info: function () {},
|
||||
debug: function () {}
|
||||
};
|
||||
|
||||
function setTimeout(fn, delay) {
|
||||
if (typeof fn === 'function' && (!delay || delay <= 0)) {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
function setInterval() { return 0; }
|
||||
function clearTimeout() {}
|
||||
function clearInterval() {}
|
||||
|
||||
var window = {
|
||||
location: __lzLocation,
|
||||
document: document,
|
||||
navigator: navigator,
|
||||
console: console,
|
||||
innerWidth: 1920,
|
||||
innerHeight: 1080,
|
||||
setTimeout: setTimeout,
|
||||
setInterval: setInterval,
|
||||
clearTimeout: clearTimeout,
|
||||
clearInterval: clearInterval,
|
||||
addEventListener: function (t, fn) {
|
||||
if (typeof fn === 'function') {
|
||||
try { fn(); } catch (e) {}
|
||||
}
|
||||
},
|
||||
removeEventListener: function () {},
|
||||
atob: function (s) { return s; },
|
||||
btoa: function (s) { return s; }
|
||||
};
|
||||
window.window = window;
|
||||
window.top = window;
|
||||
window.self = window;
|
||||
window.parent = window;
|
||||
window.jQuery = jQuery;
|
||||
window.$ = $;
|
||||
|
||||
var top = window;
|
||||
var self = window;
|
||||
var parent = window;
|
||||
@@ -55,8 +55,50 @@ def encode123(url, way, version, timestamp):
|
||||
# 返回加密后的URL参数
|
||||
return f"?{y}={time_long}-{a}-{final_crc}"
|
||||
|
||||
# 与 parser PasswordLoginRisk 保持一致:验证码/风控只提示改用 Authorization,不求解、不重试。
|
||||
_RISK_KEYWORDS = (
|
||||
"验证码", "风控", "安全风险", "安全验证", "安全校验", "滑块", "滑动验证",
|
||||
"拼图验证", "短信验证", "微信登录", "微信进行登录", "境外登录", "需要验证", "请验证",
|
||||
"请你验证", "进行验证", "完成验证", "二次验证", "人机验证", "操作频繁", "请求过于频繁",
|
||||
"请求频繁", "captcha", "recaptcha", "risk control",
|
||||
)
|
||||
_AUTH_HINT = (
|
||||
"账号密码登录触发了验证码/风控,已停止用户名密码登录(不会尝试验证码)。"
|
||||
"请改为配置 Authorization(浏览器登录后的 Bearer token / JWT,"
|
||||
"例如 localStorage 的 authorToken、请求头 authorization 或 Cookie 的 sso-token)。"
|
||||
"静态配置写在 app-dev.yml 的 auths.ye.authorization(与 auths.ye.token 等价);"
|
||||
"临时请求使用 authType=authorization 或 authType=accesstoken,token 填该令牌(不要重复带 Bearer 前缀)。"
|
||||
"说明见 parser/doc/auth-param/。"
|
||||
)
|
||||
|
||||
|
||||
def format_login_failure(result):
|
||||
"""把 123 登录失败响应转成用户可见说明。"""
|
||||
if not isinstance(result, dict):
|
||||
return "登录失败"
|
||||
message = result.get("message") or result.get("msg") or ""
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
data_message = data.get("message") or data.get("msg") or ""
|
||||
blob = f"{message} {data_message}".lower()
|
||||
risk_field = any(
|
||||
key.lower().find(flag) >= 0 and data.get(key) not in (None, False, 0, "", "false", "0")
|
||||
for key in data
|
||||
for flag in ("captcha", "vcode", "risk", "needverify", "need_verify", "slideverify", "verifycode", "verify_code")
|
||||
)
|
||||
if risk_field or any(keyword.lower() in blob for keyword in _RISK_KEYWORDS):
|
||||
code = result.get("code")
|
||||
upstream = message or data_message
|
||||
extra = f"code={code}" if code is not None else ""
|
||||
if upstream:
|
||||
extra = f"{extra}, message={upstream}" if extra else f"message={upstream}"
|
||||
return f"{_AUTH_HINT} 上游返回:{extra}" if extra else _AUTH_HINT
|
||||
if result.get("code") == 200:
|
||||
return "未获取到token"
|
||||
return f"登录失败: {message}" if message else "登录失败"
|
||||
|
||||
|
||||
def login_123pan(username, password):
|
||||
"""登录123盘获取token"""
|
||||
"""登录123盘获取token。成功返回 token,失败返回 None(错误已打印)。"""
|
||||
print(f"🔐 正在登录账号: {username}")
|
||||
|
||||
login_data = {
|
||||
@@ -73,16 +115,18 @@ def login_123pan(username, password):
|
||||
)
|
||||
result = response.json()
|
||||
|
||||
if result.get('code') == 200:
|
||||
if result.get('code') == 200 and result.get('data', {}).get('token'):
|
||||
token = result.get('data', {}).get('token', '')
|
||||
print(f"✅ 登录成功!")
|
||||
return token
|
||||
else:
|
||||
error_msg = result.get('message', '未知错误')
|
||||
print(f"❌ 登录失败: {error_msg}")
|
||||
error_msg = format_login_failure(result)
|
||||
login_123pan.last_error = error_msg
|
||||
print(f"❌ {error_msg}")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"❌ 登录请求失败: {e}")
|
||||
login_123pan.last_error = f"登录请求失败: {e}"
|
||||
print(f"❌ {login_123pan.last_error}")
|
||||
return None
|
||||
|
||||
def get_share_info(share_key, password=''):
|
||||
@@ -189,7 +233,7 @@ def start(link, password='', username='', user_password=''):
|
||||
if not token:
|
||||
return {
|
||||
"code": 201,
|
||||
"message": "登录失败"
|
||||
"message": getattr(login_123pan, "last_error", None) or "登录失败"
|
||||
}
|
||||
else:
|
||||
print("⚠️ 未提供登录信息,某些文件可能无法下载")
|
||||
|
||||
@@ -170,12 +170,29 @@ public class PanDomainTemplateTest {
|
||||
assertTrue("YE should match redirected mshare URL", redirectedUrl.find());
|
||||
assertEquals("lN7UVv-pbYJ", redirectedUrl.group("KEY"));
|
||||
|
||||
Matcher shareUrl = yePattern.matcher("https://1815268665.share.123pan.cn/123pan/iaKtVv-r4aCd");
|
||||
assertTrue("YE should match uid.share.123pan.cn URL", shareUrl.find());
|
||||
assertEquals("iaKtVv-r4aCd", shareUrl.group("KEY"));
|
||||
|
||||
Matcher htmlUrl = yePattern.matcher("https://www.123278.com/s/lN7UVv-pbYJ.html?pwd=abcd");
|
||||
assertTrue("YE should match html URL with query", htmlUrl.find());
|
||||
assertEquals("lN7UVv-pbYJ", htmlUrl.group("KEY"));
|
||||
|
||||
assertEquals("1813382308", YeShareHostUtil.getNumericSubdomainIdByShareKey("lN7UVv-pbYJ"));
|
||||
assertEquals("lN7UVv-pbYJ", YeShareHostUtil.normalizeShareKey("https://1813382308.mshare.123pan.cn/123pan/lN7UVv-pbYJ?pwd=abcd"));
|
||||
|
||||
Matcher hashUrl = yePattern.matcher("https://www.123pan.com/s/lN7UVv-pbYJ#/list/share");
|
||||
assertTrue("YE should match URL with hash fragment", hashUrl.matches());
|
||||
assertEquals("lN7UVv-pbYJ", hashUrl.group("KEY"));
|
||||
|
||||
String fakeQuery = "ref" + "=" + "example";
|
||||
Matcher yunUrl = yePattern.matcher("https://yun.123pan.com/s/lN7UVv-pbYJ?" + fakeQuery);
|
||||
assertTrue("YE should match yun.123pan.com", yunUrl.matches());
|
||||
assertEquals("lN7UVv-pbYJ", yunUrl.group("KEY"));
|
||||
|
||||
assertEquals("lN7UVv-pbYJ", YeShareHostUtil.normalizeShareKey("lN7UVv-pbYJ#/list/share"));
|
||||
assertEquals("lN7UVv-pbYJ", YeShareHostUtil.normalizeShareKey(
|
||||
"https://yun.123pan.com/s/lN7UVv-pbYJ?" + fakeQuery + "#/list"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package cn.qaiu.parser;
|
||||
|
||||
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.assertTrue;
|
||||
|
||||
public class PasswordLoginRiskTest {
|
||||
|
||||
@Test
|
||||
public void securityRiskMessageGuidesAuthorization() {
|
||||
JsonObject body = new JsonObject()
|
||||
.put("code", 401)
|
||||
.put("message", "当前账号存在安全风险,请使用短信验证码或者微信进行登录。");
|
||||
|
||||
assertTrue(PasswordLoginRisk.indicatesCaptchaOrRisk(body));
|
||||
String message = PasswordLoginRisk.describeLoginFailure(body);
|
||||
assertTrue(message.startsWith(PasswordLoginRisk.AUTHORIZATION_HINT));
|
||||
assertTrue(message.contains("验证码/风控"));
|
||||
assertTrue(message.contains("auths.ye.authorization"));
|
||||
assertTrue(message.contains("authType=authorization"));
|
||||
assertTrue(message.contains("authType=accesstoken"));
|
||||
assertTrue(message.contains("code=401"));
|
||||
assertTrue(message.contains("当前账号存在安全风险"));
|
||||
assertFalse(message.startsWith("登录失败:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void overseasRiskAndCaptchaPhrasesMatch() {
|
||||
assertRisk("当前账号存在境外登录风险,请使用短信验证码或者微信进行登录。");
|
||||
assertRisk("请完成安全验证");
|
||||
assertRisk("请进行滑块验证");
|
||||
assertRisk("操作频繁,请稍后再试");
|
||||
assertRisk("captcha required");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrongPasswordStaysDistinct() {
|
||||
JsonObject body = new JsonObject()
|
||||
.put("code", 500)
|
||||
.put("message", "用户名或密码错误");
|
||||
|
||||
assertFalse(PasswordLoginRisk.indicatesCaptchaOrRisk(body));
|
||||
assertEquals("登录失败: 用户名或密码错误", PasswordLoginRisk.describeLoginFailure(body));
|
||||
|
||||
JsonObject account = new JsonObject().put("code", 1).put("msg", "账号或密码错误");
|
||||
assertFalse(PasswordLoginRisk.indicatesCaptchaOrRisk(account));
|
||||
assertEquals("登录失败: 账号或密码错误", PasswordLoginRisk.describeLoginFailure(account));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void riskFieldWithoutKeywordStillHints() {
|
||||
JsonObject body = new JsonObject()
|
||||
.put("code", 200)
|
||||
.put("message", "ok")
|
||||
.put("data", new JsonObject().put("needCaptcha", true));
|
||||
|
||||
assertFalse(PasswordLoginRisk.isLoginSuccess(body));
|
||||
assertTrue(PasswordLoginRisk.indicatesCaptchaOrRisk(body));
|
||||
assertTrue(PasswordLoginRisk.describeLoginFailure(body).contains("Authorization"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void falseCaptchaFlagDoesNotHint() {
|
||||
JsonObject body = new JsonObject()
|
||||
.put("code", 500)
|
||||
.put("message", "用户名或密码错误")
|
||||
.put("data", new JsonObject().put("needCaptcha", false));
|
||||
|
||||
assertFalse(PasswordLoginRisk.indicatesCaptchaOrRisk(body));
|
||||
assertEquals("登录失败: 用户名或密码错误", PasswordLoginRisk.describeLoginFailure(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successTokenIsNotTreatedAsFailure() {
|
||||
JsonObject body = new JsonObject()
|
||||
.put("code", 200)
|
||||
.put("message", "ok")
|
||||
.put("data", new JsonObject().put("token", "jwt-token"));
|
||||
|
||||
assertTrue(PasswordLoginRisk.isLoginSuccess(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void blankTokenWithoutRiskKeepsMissingTokenMessage() {
|
||||
JsonObject body = new JsonObject()
|
||||
.put("code", 200)
|
||||
.put("message", "ok")
|
||||
.put("data", new JsonObject().put("token", ""));
|
||||
|
||||
assertFalse(PasswordLoginRisk.isLoginSuccess(body));
|
||||
assertEquals("未获取到token", PasswordLoginRisk.describeLoginFailure(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nonJsonCaptchaBodyUsesHint() {
|
||||
String body = "<html>请完成滑块验证</html>";
|
||||
String message = PasswordLoginRisk.nonJsonLoginFailure(body);
|
||||
assertTrue(message.startsWith(PasswordLoginRisk.AUTHORIZATION_HINT));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nonJsonWrongPasswordStaysFormatError() {
|
||||
assertEquals("登录响应格式异常: 用户名或密码错误",
|
||||
PasswordLoginRisk.nonJsonLoginFailure("用户名或密码错误"));
|
||||
}
|
||||
|
||||
private static void assertRisk(String message) {
|
||||
JsonObject body = new JsonObject().put("code", 5202).put("message", message);
|
||||
assertTrue(message, PasswordLoginRisk.indicatesCaptchaOrRisk(body));
|
||||
assertTrue(PasswordLoginRisk.describeLoginFailure(body).startsWith(PasswordLoginRisk.AUTHORIZATION_HINT));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.custom.CustomParserConfig;
|
||||
import io.vertx.core.Vertx;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.script.ScriptEngine;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ParserScriptEngineTest {
|
||||
@Test
|
||||
public void disablesClassLookupAndHostLoadersBeforeRunningScripts() throws Exception {
|
||||
SecurityClassFilter filter = new SecurityClassFilter();
|
||||
assertFalse(filter.exposeToScripts("java.lang.String"));
|
||||
assertFalse(filter.exposeToScripts("java.util.Formatter"));
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
for (String name : new String[]{"Java", "JavaImporter", "Packages", "java", "javax",
|
||||
"org", "com", "edu", "javafx", "load", "loadWithNewGlobal", "engine", "context", "exit", "quit"}) {
|
||||
assertEquals(name, "undefined", engine.eval("typeof " + name));
|
||||
assertEquals(name, Boolean.FALSE, engine.eval("Object.getOwnPropertyDescriptor(this, '" + name + "').writable"));
|
||||
assertEquals(name, Boolean.FALSE, engine.eval("Object.getOwnPropertyDescriptor(this, '" + name + "').configurable"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ordinaryScriptsCanStillCallAnInjectedParserApi() throws Exception {
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
engine.put("logger", new JsPlaygroundLogger());
|
||||
assertEquals("ok", engine.eval("logger.info('parser test'); JSON.parse('{\"result\":\"ok\"}').result"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bothExecutorsPreserveParserApisAndDisableHostGlobals() throws Exception {
|
||||
String script = """
|
||||
function parse(info, http, logger) {
|
||||
logger.info("parser test");
|
||||
return [info.getShareKey(), typeof fetch, typeof java, typeof loadWithNewGlobal].join("|");
|
||||
}
|
||||
""";
|
||||
String expected = "sample|function|undefined|undefined";
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().shareKey("sample").build();
|
||||
CustomParserConfig config = CustomParserConfig.builder()
|
||||
.type("sandbox_test").displayName("Sandbox test").isJsParser(true).jsCode(script).build();
|
||||
Vertx vertx = Vertx.vertx();
|
||||
try {
|
||||
WebClientVertxInit.init(vertx);
|
||||
try (JsPlaygroundExecutor playground = new JsPlaygroundExecutor(info, script);
|
||||
JsParserExecutor registered = new JsParserExecutor(info, config)) {
|
||||
assertEquals(expected, playground.executeParseAsync().toCompletionStage().toCompletableFuture()
|
||||
.get(10, TimeUnit.SECONDS));
|
||||
assertEquals(expected, registered.parse().toCompletionStage().toCompletableFuture()
|
||||
.get(10, TimeUnit.SECONDS));
|
||||
}
|
||||
} finally {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FjDownloadParamsTest {
|
||||
@Test
|
||||
public void anonymousIdentityIsEmptyRatherThanNull() throws Exception {
|
||||
JsonObject params = FjDownloadParams.create("123", null, "uuid", "share", 1000L);
|
||||
assertEquals("123|", decrypt(params.getString("fidEncode")));
|
||||
assertEquals("1000", decrypt(params.getString("ts")));
|
||||
assertEquals("123|1000", decrypt(params.getString("auth")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticatedIdentityAndTimestampAreRegenerated() throws Exception {
|
||||
JsonObject params = FjDownloadParams.create("123", "456", "uuid", "share", 2000L);
|
||||
assertEquals("123|456", decrypt(params.getString("fidEncode")));
|
||||
assertEquals("123|2000", decrypt(params.getString("auth")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void legacyLinksRecoverOnlyFileId() throws Exception {
|
||||
JsonObject old = JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|null"), "ts", "expired");
|
||||
assertEquals("123", FjDownloadParams.fileId(old));
|
||||
assertEquals("789", FjDownloadParams.fileId(JsonObject.of("fileId", "789")));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void invalidLegacyLinkFailsExplicitly() throws Exception {
|
||||
FjDownloadParams.fileId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("invalid")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upstreamErrorPreservesBusinessCodeAndMessage() {
|
||||
String message = FjDownloadParams.missingLocation(200, "{\"code\":401,\"msg\":\"请登录后下载\"}");
|
||||
assertTrue(message.contains("HTTP 200"));
|
||||
assertTrue(message.contains("code=401"));
|
||||
assertTrue(message.contains("请登录后下载"));
|
||||
assertTrue(FjDownloadParams.missingLocation(502, "").contains("响应体为空"));
|
||||
assertTrue(FjDownloadParams.missingLocation(502, "x".repeat(1000)).length() < 600);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ownerIdentityComesFromDirectoryDataOrLegacySignature() throws Exception {
|
||||
assertEquals("11069975", FjDownloadParams.ownerId(JsonObject.of("userId", 11069975L)));
|
||||
assertEquals("11069975", FjDownloadParams.ownerId(
|
||||
JsonObject.of("fidEncode", AESUtils.encrypt2Hex("61731757356|11069975"))));
|
||||
assertNull(FjDownloadParams.ownerId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|null"))));
|
||||
assertNull(FjDownloadParams.ownerId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|"))));
|
||||
}
|
||||
|
||||
private String decrypt(String value) throws Exception {
|
||||
return AESUtils.decryptByHexAES(value, AESUtils.CIPHER_AES0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.client.WebClient;
|
||||
import io.vertx.ext.web.client.WebClientOptions;
|
||||
import io.vertx.uritemplate.UriTemplate;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FjToolDownloadTest {
|
||||
private Vertx vertx;
|
||||
private WebClient local;
|
||||
private HttpServer server;
|
||||
private final AtomicInteger logins = new AtomicInteger();
|
||||
private final AtomicInteger downloads = new AtomicInteger();
|
||||
private String identity;
|
||||
private String businessError;
|
||||
private String contentEncoding;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
FjTool.resetToken();
|
||||
vertx = Vertx.vertx();
|
||||
WebClientVertxInit.init(vertx);
|
||||
local = WebClient.create(vertx, new WebClientOptions().setFollowRedirects(false));
|
||||
server = vertx.createHttpServer().requestHandler(req -> {
|
||||
if (req.path().equals("/ws/login")) {
|
||||
logins.incrementAndGet();
|
||||
req.response().setStatusCode(500).end("Share downloads must not require login");
|
||||
} else if (req.path().equals("/ws/file/redirect")) {
|
||||
downloads.incrementAndGet();
|
||||
try {
|
||||
identity = AESUtils.decryptByHexAES(req.getParam("downloadId"), AESUtils.CIPHER_AES0);
|
||||
long timestamp = Long.parseLong(AESUtils.decryptByHexAES(req.getParam("timestamp"), AESUtils.CIPHER_AES0));
|
||||
assertTrue(Math.abs(System.currentTimeMillis() - timestamp) < 10000);
|
||||
assertEquals(AESUtils.encrypt2Hex("123|" + timestamp), req.getParam("auth"));
|
||||
assertEquals("share", req.getParam("shareId"));
|
||||
if (businessError != null) {
|
||||
if (contentEncoding != null) {
|
||||
req.response().putHeader("Content-Encoding", contentEncoding);
|
||||
}
|
||||
req.response().end(businessError);
|
||||
} else {
|
||||
req.response().setStatusCode(302).putHeader("Location", "https://download.example/file").end();
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
req.response().setStatusCode(500).end(e.toString());
|
||||
}
|
||||
} else {
|
||||
req.response().setStatusCode(404).end();
|
||||
}
|
||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() throws Exception {
|
||||
local.close();
|
||||
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
FjTool.resetToken();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void directoryLinkUsesOwnerEvenWithConfiguredCredentials() throws Exception {
|
||||
ShareLinkInfo info = info();
|
||||
info.getOtherParam().put("auths", MultiMap.caseInsensitiveMultiMap()
|
||||
.set("username", "test-user").set("password", "test-password"));
|
||||
assertEquals("https://download.example/file", tool(info).parseById()
|
||||
.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS));
|
||||
assertEquals(0, logins.get());
|
||||
assertEquals(1, downloads.get());
|
||||
assertEquals("123|11069975", identity);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shareRequestUsesOwnerNotGlobalUserIdentity() throws Exception {
|
||||
FjTool.userId = "other-user";
|
||||
assertEquals("https://download.example/file", tool(info()).parseById()
|
||||
.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS));
|
||||
assertEquals("123|11069975", identity);
|
||||
assertEquals(0, logins.get());
|
||||
FjTool.userId = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upstreamBusinessErrorCompletesFutureWithReason() throws Exception {
|
||||
businessError = "{\"code\":403,\"msg\":\"需要会员\"}";
|
||||
try {
|
||||
tool(info()).parseById().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
fail("Expected upstream error");
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue(e.getCause().getMessage().contains("需要会员"));
|
||||
assertTrue(e.getCause().getMessage().contains("code=403"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unsupportedErrorEncodingFailsWithoutLeavingFuturePending() throws Exception {
|
||||
contentEncoding = "zstd";
|
||||
businessError = "upstream error";
|
||||
assertErrorBodyFailure("zstd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oversizedErrorBodyFailsWithoutLeavingFuturePending() throws Exception {
|
||||
businessError = "x".repeat(8 * 1024 * 1024 + 1);
|
||||
assertErrorBodyFailure("响应体过大");
|
||||
}
|
||||
|
||||
private void assertErrorBodyFailure(String expectedReason) throws Exception {
|
||||
try {
|
||||
tool(info()).parseById().toCompletionStage().toCompletableFuture().get(3, TimeUnit.SECONDS);
|
||||
fail("Expected response decoding error");
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue(e.getCause().getMessage(), e.getCause().getMessage().contains(expectedReason));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingOwnerFailsBeforeDownload() throws Exception {
|
||||
ShareLinkInfo info = info();
|
||||
info.getOtherParam().put("paramJson", JsonObject.of("fileId", "123", "shareId", "share"));
|
||||
try {
|
||||
tool(info).parseById().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
fail("Expected missing owner error");
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue(e.getCause().getMessage().contains("缺少分享者 userId"));
|
||||
}
|
||||
assertEquals(0, downloads.get());
|
||||
}
|
||||
|
||||
private ShareLinkInfo info() {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("fj").shareKey("share")
|
||||
.shareUrl("https://share.feijipan.com/s/share").build();
|
||||
info.getOtherParam().put("paramJson", JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|11069975"),
|
||||
"uuid", "test-uuid", "ts", "expired", "auth", "expired", "shareId", "share"));
|
||||
return info;
|
||||
}
|
||||
|
||||
private FjTool tool(ShareLinkInfo info) {
|
||||
WebClient routed = (WebClient) Proxy.newProxyInstance(WebClient.class.getClassLoader(),
|
||||
new Class<?>[]{WebClient.class}, (proxy, method, args) -> {
|
||||
if (args != null && args.length > 0 && args[0] instanceof UriTemplate template) {
|
||||
args[0] = Proxy.newProxyInstance(UriTemplate.class.getClassLoader(),
|
||||
new Class<?>[]{UriTemplate.class}, (p, m, a) -> {
|
||||
Object expanded = m.invoke(template, a);
|
||||
return expanded instanceof String url
|
||||
? url.replace("https://api.feijipan.com", "http://127.0.0.1:" + server.actualPort())
|
||||
: expanded;
|
||||
});
|
||||
}
|
||||
return method.invoke(local, args);
|
||||
});
|
||||
return new FjTool(info) {{ client = routed; clientNoRedirects = routed; }};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import io.vertx.core.MultiMap;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class IzXffHeaderTest {
|
||||
@Test
|
||||
public void offByDefault() {
|
||||
assertNull(IzXffHeader.resolve(null));
|
||||
assertNull(IzXffHeader.resolve(""));
|
||||
assertNull(IzXffHeader.resolve("OFF"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void literalAndRandom() {
|
||||
assertEquals("113.96.181.18", IzXffHeader.resolve("113.96.181.18"));
|
||||
String ip = IzXffHeader.resolve("random");
|
||||
assertTrue(ip, ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applyRemovesWhenOff() {
|
||||
MultiMap h = MultiMap.caseInsensitiveMultiMap().set("X-Forwarded-For", "1.1.1.1");
|
||||
System.clearProperty(IzXffHeader.PROP);
|
||||
if (System.getenv(IzXffHeader.ENV) == null) {
|
||||
IzXffHeader.apply(h);
|
||||
assertFalse(h.contains("X-Forwarded-For"));
|
||||
}
|
||||
System.setProperty(IzXffHeader.PROP, "8.8.8.8");
|
||||
IzXffHeader.apply(h);
|
||||
assertEquals("8.8.8.8", h.get("X-Forwarded-For"));
|
||||
System.clearProperty(IzXffHeader.PROP);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* 个性域名 a.lanzouw.com 不能被改写到 wwww.lanzoux.com(四个 w)。
|
||||
* 部分出口连不上四 w,页面请求会超时;ajax 只把四 w 当作最后兜底。
|
||||
*/
|
||||
public class LzToolShareUrlTest {
|
||||
|
||||
@Test
|
||||
public void personalDomainPageStaysOffWwww() {
|
||||
String resolved = LzTool.resolveSharePageUrl(
|
||||
"https://a.lanzouw.com/xxx",
|
||||
"https://w1.lanzn.com/xxx",
|
||||
"xxx");
|
||||
assertEquals("https://a.lanzouw.com/xxx", resolved);
|
||||
assertFalse(resolved.contains("wwww.lanzoux.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void folderPageKeepsOriginalHost() {
|
||||
String resolved = LzTool.resolveSharePageUrl(
|
||||
"https://a.lanzouw.com/b710887",
|
||||
"https://w1.lanzn.com/b710887",
|
||||
"b710887");
|
||||
assertEquals("https://a.lanzouw.com/b710887", resolved);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nodeShareIsNotRewrittenToWwww() {
|
||||
String resolved = LzTool.resolveSharePageUrl(
|
||||
"https://wwn.lanzouy.com/ihLkw1gezutg",
|
||||
"https://w1.lanzn.com/ihLkw1gezutg",
|
||||
"ihLkw1gezutg");
|
||||
assertEquals("https://wwn.lanzouy.com/ihLkw1gezutg", resolved);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void webpageQueryStaysOnOriginalHost() {
|
||||
String resolved = LzTool.resolveSharePageUrl(
|
||||
"https://a.lanzouw.com/iabc?webpage=wp1&pwd=secret",
|
||||
"https://w1.lanzn.com/iabc",
|
||||
"iabc");
|
||||
assertEquals("https://a.lanzouw.com/iabc?webpage=wp1", resolved);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void placeholderUsesStandardHostNotWwww() {
|
||||
assertEquals("https://w1.lanzn.com/", LzTool.SHARE_URL_PREFIX);
|
||||
assertFalse(LzTool.SHARE_URL_PREFIX.contains("wwww"));
|
||||
String resolved = LzTool.resolveSharePageUrl(
|
||||
"https://w1.lanzn.com/-",
|
||||
"https://w1.lanzn.com/-",
|
||||
"iFileId");
|
||||
assertEquals("https://w1.lanzn.com/iFileId", resolved);
|
||||
assertFalse(resolved.contains("wwww.lanzoux.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingShareUrlKeepsRealStandardHost() {
|
||||
String resolved = LzTool.resolveSharePageUrl(
|
||||
null,
|
||||
"https://www.lanzoux.com/iabc",
|
||||
"iabc");
|
||||
assertEquals("https://www.lanzoux.com/iabc", resolved);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ajaxFallbackOrderPutsWwwwLast() {
|
||||
List<String> fallback = LzTool.AJAX_FALLBACK_ORIGINS;
|
||||
assertEquals("https://w1.lanzn.com", fallback.get(0));
|
||||
assertEquals("https://www.lanzoux.com", fallback.get(1));
|
||||
assertEquals("https://wwww.lanzoux.com", fallback.get(fallback.size() - 1));
|
||||
|
||||
List<String> origins = LzTool.ajaxOrigins("https://a.lanzouw.com/xxx");
|
||||
assertEquals("https://a.lanzouw.com", origins.get(0));
|
||||
assertEquals("https://w1.lanzn.com", origins.get(1));
|
||||
assertEquals("https://www.lanzoux.com", origins.get(2));
|
||||
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
|
||||
assertTrue(origins.indexOf("https://wwww.lanzoux.com")
|
||||
> origins.indexOf("https://w1.lanzn.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ajaxOriginsDoNotDuplicateKnownHost() {
|
||||
List<String> origins = LzTool.ajaxOrigins("https://www.lanzoux.com/iabc");
|
||||
assertEquals(3, origins.size());
|
||||
assertEquals("https://www.lanzoux.com", origins.get(0));
|
||||
assertEquals("https://w1.lanzn.com", origins.get(1));
|
||||
assertEquals("https://wwww.lanzoux.com", origins.get(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void timeoutAjaxFallsBackButBusinessErrorDoesNot() {
|
||||
assertTrue(LzTool.ajaxResponseShouldFallback("{\"zt\":0,\"inf\":\"已超时\"}"));
|
||||
assertTrue(LzTool.ajaxResponseShouldFallback("{\"info\":\"请求超时\"}"));
|
||||
assertTrue(LzTool.ajaxResponseShouldFallback(""));
|
||||
assertTrue(LzTool.ajaxResponseShouldFallback("<html>blocked</html>"));
|
||||
assertFalse(LzTool.ajaxResponseShouldFallback("{\"zt\":0,\"inf\":\"密码错误\"}"));
|
||||
assertFalse(LzTool.ajaxResponseShouldFallback(
|
||||
"{\"zt\":1,\"inf\":\"name.zip\",\"dom\":\"https://x\",\"url\":\"abc\"}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filePagePrefersExistingHostOverWwww() {
|
||||
assertEquals("https://a.lanzouw.com/",
|
||||
LzTool.sharePageHostBase("https://a.lanzouw.com/b123", "https://w1.lanzn.com/b123"));
|
||||
assertEquals("https://w1.lanzn.com/",
|
||||
LzTool.sharePageHostBase("https://w1.lanzn.com/-", "https://w1.lanzn.com/-"));
|
||||
assertFalse(LzTool.sharePageHostBase("https://a.lanzouw.com/b123", null).contains("wwww"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void absoluteAjaxUrlIsKeptAndTriedFirst() {
|
||||
String html = """
|
||||
url : 'https://apifile.lanzouw.com/ajaxfile.php?file=320665771',
|
||||
data : { 'action':'downprocess','sign':isngis,'kd':kdns,'p':pwd, },
|
||||
""";
|
||||
String target = LzTool.fileAjaxTarget(html);
|
||||
assertEquals("https://apifile.lanzouw.com/ajaxfile.php?file=320665771", target);
|
||||
|
||||
List<String> origins = LzTool.fileAjaxOrigins(
|
||||
"https://wwaqg.lanzouu.com/iqouM49vy9ib", target);
|
||||
assertEquals("https://apifile.lanzouw.com", origins.get(0));
|
||||
assertTrue(origins.contains("https://wwaqg.lanzouu.com"));
|
||||
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
|
||||
assertTrue(origins.indexOf("https://apifile.lanzouw.com")
|
||||
< origins.indexOf("https://wwaqg.lanzouu.com"));
|
||||
assertTrue(origins.indexOf("https://wwww.lanzoux.com")
|
||||
> origins.indexOf("https://w1.lanzn.com"));
|
||||
assertEquals(1, origins.stream().filter("https://apifile.lanzouw.com"::equals).count());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void protocolRelativeAjaxBecomesHttps() {
|
||||
String html = "url : '//apifile.lanzouw.com/ajaxfile.php?file=9',";
|
||||
assertEquals("https://apifile.lanzouw.com/ajaxfile.php?file=9", LzTool.fileAjaxTarget(html));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void absoluteAjaxWinsOverRelativePathInSamePage() {
|
||||
String html = """
|
||||
//data : { url : '/ajaxfile.php?file=1' }
|
||||
url : "https://apifile.lanzouw.com/ajaxm.php?file=42",
|
||||
""";
|
||||
assertEquals("https://apifile.lanzouw.com/ajaxm.php?file=42", LzTool.fileAjaxTarget(html));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void relativeFileAjaxFallsThroughToApifileBeforeWwww() {
|
||||
String html = "url : '/ajaxfile.php?file=150233466',";
|
||||
assertEquals("/ajaxfile.php?file=150233466", LzTool.fileAjaxTarget(html));
|
||||
|
||||
List<String> origins = LzTool.fileAjaxOrigins("https://a.lanzouw.com/xxx", LzTool.fileAjaxTarget(html));
|
||||
assertEquals("https://a.lanzouw.com", origins.get(0));
|
||||
assertEquals("https://apifile.lanzouw.com", origins.get(1));
|
||||
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
|
||||
assertTrue(origins.indexOf("https://apifile.lanzouw.com")
|
||||
< origins.indexOf("https://wwww.lanzoux.com"));
|
||||
assertFalse(LzTool.ajaxOrigins("https://a.lanzouw.com/xxx").contains("https://apifile.lanzouw.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingAjaxTargetStillPutsApifileBeforeWwww() {
|
||||
List<String> origins = LzTool.fileAjaxOrigins("https://www.lanzoux.com/ihLkw1gezutg", null);
|
||||
assertEquals("https://www.lanzoux.com", origins.get(0));
|
||||
assertEquals("https://apifile.lanzouw.com", origins.get(1));
|
||||
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
|
||||
assertFalse(origins.get(0).contains("wwww"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import io.vertx.core.Vertx;
|
||||
import org.junit.Assume;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 对 Issue #282 的分享做一次真实访客解析。
|
||||
* 默认不跑:父 POM surefire skipTests=true,且本测试还要求 -Dquark.live=true。
|
||||
* mvn -pl parser -DskipTests=false -Dquark.live=true -Dtest=QkToolGuestFolderLiveTest test
|
||||
*/
|
||||
public class QkToolGuestFolderLiveTest {
|
||||
|
||||
@Test
|
||||
public void issue282FolderShareResolvesAnonymously() throws Exception {
|
||||
Assume.assumeTrue("set -Dquark.live=true to call Quark", Boolean.getBoolean("quark.live"));
|
||||
Vertx vertx = Vertx.vertx();
|
||||
WebClientVertxInit.init(vertx);
|
||||
QkTool tool = null;
|
||||
try {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
||||
.type("qk")
|
||||
.panName("夸克网盘")
|
||||
.shareKey("d34c18e9d62a")
|
||||
.shareUrl("https://pan.quark.cn/s/d34c18e9d62a")
|
||||
.build();
|
||||
tool = new QkTool(info);
|
||||
String url = tool.parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
||||
assertNotNull(url);
|
||||
assertTrue(url.startsWith("http"));
|
||||
FileInfo fileInfo = (FileInfo) info.getOtherParam().get("fileInfo");
|
||||
assertNotNull(fileInfo);
|
||||
assertNotNull(fileInfo.getFileName());
|
||||
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();
|
||||
}
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* 夸克目录项分类与访客选文件。不访问网络。
|
||||
* 父 POM 的 surefire 默认 skipTests=true,本地验证用:
|
||||
* mvn -pl parser -DskipTests=false -Dtest=QkToolShareListTest test
|
||||
*/
|
||||
public class QkToolShareListTest {
|
||||
|
||||
@Test
|
||||
public void folderIsNotADownloadableFile() {
|
||||
JsonObject folder = new JsonObject()
|
||||
.put("file", false)
|
||||
.put("dir", true)
|
||||
.put("file_type", 0)
|
||||
.put("file_name", "BiliTools最新版");
|
||||
assertTrue(QkTool.isQuarkFolder(folder));
|
||||
assertFalse(QkTool.isQuarkFile(folder));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void archiveAndInstallerCountAsFiles() {
|
||||
JsonObject rar = new JsonObject()
|
||||
.put("file", true)
|
||||
.put("dir", false)
|
||||
.put("file_type", 1)
|
||||
.put("obj_category", "archive")
|
||||
.put("size", 8228);
|
||||
JsonObject exe = new JsonObject()
|
||||
.put("file", true)
|
||||
.put("dir", false)
|
||||
.put("file_type", 1)
|
||||
.put("obj_category", "default")
|
||||
.put("size", 11919276);
|
||||
assertTrue(QkTool.isQuarkFile(rar));
|
||||
assertTrue(QkTool.isQuarkFile(exe));
|
||||
assertFalse(QkTool.isQuarkFolder(rar));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void directoryFlagWinsOverCategory() {
|
||||
JsonObject odd = new JsonObject()
|
||||
.put("file", false)
|
||||
.put("dir", true)
|
||||
.put("file_type", 0)
|
||||
.put("obj_category", "default");
|
||||
assertTrue(QkTool.isQuarkFolder(odd));
|
||||
assertFalse(QkTool.isQuarkFile(odd));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void guestOrderKeepsFirstFileThenSortsTheRestBySize() {
|
||||
JsonObject large = file("large", 90_000_000L);
|
||||
JsonObject mid = file("mid", 20_000_000L);
|
||||
JsonObject small = file("small", 8_000L);
|
||||
List<JsonObject> ordered = QkTool.orderGuestCandidates(List.of(large, mid, small));
|
||||
assertEquals("large", ordered.get(0).getString("file_name"));
|
||||
assertEquals("small", ordered.get(1).getString("file_name"));
|
||||
assertEquals("mid", ordered.get(2).getString("file_name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sizeLimitIsTransferFallbackAndLoginIsNot() {
|
||||
assertTrue(QkTool.needsTransferFallback(new RuntimeException(
|
||||
"分享直链获取失败(code=23018): download file size limit")));
|
||||
assertFalse(QkTool.needsTransferFallback(new RuntimeException("未登录或 Cookie 已失效")));
|
||||
assertTrue(QkTool.isGuestAuthError(new RuntimeException("code=31001 未登录")));
|
||||
assertFalse(QkTool.isGuestAuthError(new RuntimeException("code=23018 size limit")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void violationCodeIsExplainedWithoutFolderWording() {
|
||||
JsonObject json = new JsonObject().put("code", 41010).put("message", "文件涉及违规内容");
|
||||
String msg = QkTool.quarkApiFailure("https://drive-pc.quark.cn/token", json);
|
||||
assertTrue(msg.contains("违规"));
|
||||
assertTrue(msg.contains("41010"));
|
||||
assertFalse(msg.contains("都是文件夹"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void zeroBytePlaceholderIsDroppedWhenARealFileExists() {
|
||||
JsonObject placeholder = file("等待更新", 0L);
|
||||
JsonObject real = file("notes.rar", 8228L);
|
||||
List<JsonObject> kept = QkTool.preferSizedFiles(List.of(placeholder, real));
|
||||
assertEquals(1, kept.size());
|
||||
assertEquals("notes.rar", kept.get(0).getString("file_name"));
|
||||
assertTrue(QkTool.hasPositiveSize(List.of(real)));
|
||||
assertFalse(QkTool.hasPositiveSize(List.of(placeholder)));
|
||||
assertEquals(1, QkTool.preferSizedFiles(List.of(placeholder)).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oversizeHintPointsAtCookie() {
|
||||
assertTrue(QkTool.GUEST_OVERSIZE_MSG.contains("auths.qk.cookie"));
|
||||
assertTrue(QkTool.GUEST_OVERSIZE_MSG.contains("23018"));
|
||||
assertFalse(QkTool.GUEST_OVERSIZE_MSG.contains("都是文件夹"));
|
||||
assertTrue(QkTool.GUEST_LOGIN_MSG.contains("auths.qk.cookie"));
|
||||
}
|
||||
|
||||
private static JsonObject file(String name, long size) {
|
||||
return new JsonObject().put("file_name", name).put("size", size).put("file", true);
|
||||
}
|
||||
}
|
||||
@@ -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,40 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* 123 登录提示。不访问网络。
|
||||
* mvn -pl parser -DskipTests=false -Dtest=Ye2LoginHintTest test
|
||||
*/
|
||||
public class Ye2LoginHintTest {
|
||||
|
||||
@Test
|
||||
public void loginCodesAndMessagesAreRecognized() {
|
||||
assertTrue(Ye2Tool.isYeLoginRequired(5112, "您需要注册登录或付费后下载"));
|
||||
assertTrue(Ye2Tool.isYeLoginRequired(401, "请登录后下载"));
|
||||
assertTrue(Ye2Tool.isYeLoginRequired(0, "需要登录才能下载"));
|
||||
assertFalse(Ye2Tool.isYeLoginRequired(0, "ok"));
|
||||
assertFalse(Ye2Tool.isYeLoginRequired(null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingAuthTellsUserToConfigureLocalAuthorization() {
|
||||
String msg = Ye2Tool.loginRequiredDownloadMessage(false, null);
|
||||
assertTrue(msg.contains("auths.ye.authorization"));
|
||||
assertTrue(msg.contains("5112"));
|
||||
assertTrue(msg.contains("公共云解析"));
|
||||
assertTrue(msg.contains("ye:分享key@提取码"));
|
||||
assertFalse(msg.contains("验证码求解"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configuredAuthStillPointsAtLocalTokenWhenUpstreamRejects() {
|
||||
String msg = Ye2Tool.loginRequiredDownloadMessage(true, "请登录后下载");
|
||||
assertTrue(msg.contains("auths.ye.authorization"));
|
||||
assertTrue(msg.contains("上游信息: 请登录后下载"));
|
||||
assertFalse(msg.contains("{"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package cn.qaiu.util;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.Random;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class Base64DecoderTest {
|
||||
@Test
|
||||
public void matchesJdkForStandardAndUrlSafeEncodings() {
|
||||
Random random = new Random(114938);
|
||||
for (int length = 0; length <= 512; length++) {
|
||||
assertRoundTrip(random, length);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void decodesCompleteGroupsAndEveryTailAcrossLargeInputs() {
|
||||
Random random = new Random(20261120);
|
||||
for (int boundary : new int[]{1024, 8192, 65536}) {
|
||||
for (int offset = -2; offset <= 2; offset++) {
|
||||
assertRoundTrip(random, boundary + offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesJdkForInvalidCharactersAtGroupAndTailBoundaries() {
|
||||
for (int length : new int[]{4, 6, 7, 8}) {
|
||||
String valid = "A".repeat(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
for (String invalid : new String[]{"!", "=", "\u0141", "\ud83d\ude00"}) {
|
||||
String value = valid.substring(0, i) + invalid + valid.substring(i + 1);
|
||||
assertCompatible(value, Base64.getDecoder(), Base64Decoder::decode);
|
||||
assertCompatible(value, Base64.getUrlDecoder(), Base64Decoder::decodeUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesJdkForPaddingAlphabetAndInvalidCharacters() {
|
||||
for (String value : new String[]{"", "A", "AA", "AB==", "ABC=", "ABCD", "AA=", "AAA==",
|
||||
"AA==AA", "AA==\n", " AA", "A A", "AA\u00e9", "AA\u2603", "+/8=", "-_8=", "+_8=", "===="}) {
|
||||
assertCompatible(value, Base64.getDecoder(), Base64Decoder::decode);
|
||||
assertCompatible(value, Base64.getUrlDecoder(), Base64Decoder::decodeUrl);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void preservesLegacyDownloadLinkFormats() {
|
||||
String value = "网盘下载😀";
|
||||
String standard = Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
|
||||
String escaped = URLEncoder.encode(standard, StandardCharsets.UTF_8);
|
||||
assertEquals(value, CommonUtils.urlBase64Decode(CommonUtils.urlBase64Encode(value)));
|
||||
assertEquals(value, CommonUtils.urlBase64Decode(standard));
|
||||
assertEquals(value, CommonUtils.urlBase64Decode(escaped));
|
||||
assertEquals(value, CommonUtils.urlBase64Decode(URLEncoder.encode(escaped, StandardCharsets.UTF_8)));
|
||||
assertEquals("f", CommonUtils.urlBase64Decode("Zg="));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesJdkAcrossSimdBlocksAndThreshold() {
|
||||
if (Boolean.getBoolean("nfd.test.requireVector")) {
|
||||
assertEquals(true, Base64Encoder.useVectors(4096));
|
||||
}
|
||||
Random random = new Random(114938);
|
||||
for (int boundary : new int[]{768, 1024, 4096}) {
|
||||
for (int offset = -65; offset <= 65; offset++) {
|
||||
byte[] plain = new byte[boundary + offset];
|
||||
random.nextBytes(plain);
|
||||
String standard = Base64.getEncoder().encodeToString(plain);
|
||||
String url = Base64.getUrlEncoder().withoutPadding().encodeToString(plain);
|
||||
assertEquals(standard, Base64Encoder.encode(plain));
|
||||
assertEquals(url, Base64Encoder.encodeUrlWithoutPadding(plain));
|
||||
assertArrayEquals(Base64.getEncoder().encode(plain), Base64Encoder.encodeBytes(plain));
|
||||
assertArrayEquals(plain, Base64Decoder.decode(standard));
|
||||
assertArrayEquals(plain, Base64Decoder.decodeUrl(url));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validatesBothAlphabetsInsideVectorBlocks() {
|
||||
char[] input = "A".repeat(2048).toCharArray();
|
||||
for (int ch = 0; ch < 256; ch++) {
|
||||
int position = 128 + ch % 64;
|
||||
input[position] = (char) ch;
|
||||
String encoded = new String(input);
|
||||
assertCompatible(encoded, Base64.getDecoder(), Base64Decoder::decode);
|
||||
assertCompatible(encoded, Base64.getUrlDecoder(), Base64Decoder::decodeUrl);
|
||||
input[position] = 'A';
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertRoundTrip(Random random, int length) {
|
||||
byte[] value = new byte[length];
|
||||
random.nextBytes(value);
|
||||
assertArrayEquals(value, Base64Decoder.decode(Base64.getEncoder().encodeToString(value)));
|
||||
assertArrayEquals(value, Base64Decoder.decode(Base64.getEncoder().withoutPadding().encodeToString(value)));
|
||||
assertArrayEquals(value, Base64Decoder.decodeUrl(Base64.getUrlEncoder().encodeToString(value)));
|
||||
assertArrayEquals(value, Base64Decoder.decodeUrl(Base64.getUrlEncoder().withoutPadding().encodeToString(value)));
|
||||
}
|
||||
|
||||
private static void assertCompatible(String value, Base64.Decoder jdk, Function<String, byte[]> replacement) {
|
||||
byte[] expected;
|
||||
try {
|
||||
expected = jdk.decode(value);
|
||||
} catch (IllegalArgumentException expectedFailure) {
|
||||
try {
|
||||
replacement.apply(value);
|
||||
} catch (IllegalArgumentException actualFailure) {
|
||||
return;
|
||||
}
|
||||
fail("Accepted invalid Base64 input: " + value);
|
||||
return;
|
||||
}
|
||||
assertArrayEquals(expected, replacement.apply(value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package cn.qaiu.util;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* 新版蓝奏页面会调用更多 document / jQuery API,沙箱必须能跑完并抓住 $.ajax。
|
||||
*/
|
||||
public class JsExecUtilsLzTest {
|
||||
|
||||
@Test
|
||||
public void testNewIframeAjaxWithDomApis() throws Exception {
|
||||
String js = """
|
||||
var lanosso = '';
|
||||
var down_1 = '';
|
||||
var wsk_sign = 'c20230908';
|
||||
var wp_sign = 'SIGN_ABC';
|
||||
var ajaxdata = 'MrBR';
|
||||
var kdns = 1;
|
||||
if (typeof(killdns)=='undefined'){
|
||||
var kdns = 0;
|
||||
}
|
||||
document.cookie = 'x=1';
|
||||
document.location.reload();
|
||||
document.querySelector('#tourl');
|
||||
document.createElement('div');
|
||||
$.ajax({
|
||||
type : 'post',
|
||||
url : '/ajaxfile.php?file=150233466',
|
||||
data : { 'action':'downprocess','websignkey':ajaxdata,'signs':ajaxdata,'sign':wp_sign,'websign':'','kd':kdns,'ves':1 },
|
||||
dataType : 'json',
|
||||
success:function(msg){
|
||||
$("#tourl").html("ok");
|
||||
$("#outime").css("display","block");
|
||||
}
|
||||
});
|
||||
""";
|
||||
ScriptObjectMirror sign = JsExecUtils.executeDynamicJs(js, null);
|
||||
assertNotNull(sign);
|
||||
assertEquals("/ajaxfile.php?file=150233466", String.valueOf(sign.get("url")));
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> data = (Map<String, Object>) sign.get("data");
|
||||
assertEquals("downprocess", String.valueOf(data.get("action")));
|
||||
assertEquals("SIGN_ABC", String.valueOf(data.get("sign")));
|
||||
assertEquals("MrBR", String.valueOf(data.get("websignkey")));
|
||||
assertEquals("1", String.valueOf(data.get("kd")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPwdViaJqueryValAndDocument() throws Exception {
|
||||
String js = """
|
||||
function down_p(){
|
||||
var pwd = $('#pwd').val();
|
||||
var pwd2 = document.getElementById('pwd').value;
|
||||
var pwd3 = document.querySelector('#pwd').value;
|
||||
$(".passwdinput").focus();
|
||||
$.ajax({
|
||||
type : 'post',
|
||||
url : '/ajaxm.php',
|
||||
data : { 'action':'downprocess','sign':'S1','p':pwd,'p2':pwd2,'p3':pwd3 }
|
||||
});
|
||||
}
|
||||
""";
|
||||
ScriptObjectMirror sign = JsExecUtils.executeDynamicJs(js, "down_p", "e4k4");
|
||||
assertNotNull(sign);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> data = (Map<String, Object>) sign.get("data");
|
||||
assertEquals("e4k4", String.valueOf(data.get("p")));
|
||||
assertEquals("e4k4", String.valueOf(data.get("p2")));
|
||||
assertEquals("e4k4", String.valueOf(data.get("p3")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReadyAndSuccessCallbackDoNotDropAjax() throws Exception {
|
||||
String js = """
|
||||
$(function(){
|
||||
document.getElementById('rpt').style.display = 'none';
|
||||
$.ajax({ url: '/ajaxm.php?file=1', data: { a: 1 } });
|
||||
$("#tourl").html("x");
|
||||
});
|
||||
""";
|
||||
ScriptObjectMirror sign = JsExecUtils.executeDynamicJs(js, null);
|
||||
assertNotNull(sign);
|
||||
assertTrue(String.valueOf(sign.get("url")).contains("ajaxm.php"));
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<revision>0.4.2</revision>
|
||||
<revision>0.4.10</revision>
|
||||
<java.version>17</java.version>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
@@ -36,6 +36,7 @@
|
||||
<jackson.version>2.18.9</jackson.version>
|
||||
<!-- Logback 最新稳定版 -->
|
||||
<logback.version>1.5.34</logback.version>
|
||||
<skipTests>true</skipTests>
|
||||
<junit.version>4.13.2</junit.version>
|
||||
</properties>
|
||||
|
||||
@@ -97,7 +98,7 @@
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
<configuration>
|
||||
<skipTests>true</skipTests>
|
||||
<skipTests>${skipTests}</skipTests>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
亿方云 (FangCloud) 分享链接有效性验证脚本
|
||||
|
||||
用法: 直接 `python3 verify_fangcloud_share.py` 运行, 分享链接已写死在 SHARE_URL
|
||||
里 (不走命令行传参), 要换链接就直接改这个常量。
|
||||
|
||||
根因(已用真实分享链接验证确认)
|
||||
--------------------------------
|
||||
GET https://v2.fangcloud.cn/apps/share_links/info/{uname}
|
||||
返回的是 200 + JSON, 结构形如:
|
||||
|
||||
{
|
||||
"process": {
|
||||
"is_closed": false,
|
||||
"is_expired": false,
|
||||
"item": {"type": "file", "id": 45006535173, "name": "..."},
|
||||
...
|
||||
}
|
||||
}
|
||||
|
||||
FcTool.java 原来的实现判断有效性时读的是响应体**顶层**的 "is_valid" 字段
|
||||
(`json.getBoolean("is_valid")`), 但这个字段根本不存在于该接口的实际响应里
|
||||
(有效性信息实际上是 process.is_closed / process.is_expired, 且没有任何
|
||||
名叫 "is_valid" 的字段) —— 所以旧的判断逻辑其实从未真正读取过这个接口的
|
||||
有效性判断, 而是走的另一套 HTML 抓取 typed_id 的流程, 分享失效时会得到一个
|
||||
"未匹配到文件id(typed_id)" 这种令人困惑的技术报错, 而不是清晰的"分享已失效"。
|
||||
|
||||
修复方案(已同步到 FcTool.java): 解析前先请求一次
|
||||
https://v2.fangcloud.cn/apps/share_links/info/{uname}, 用
|
||||
process.is_closed / process.is_expired 判断分享是否有效, 无效则直接返回
|
||||
"分享已失效或不存在", 有效再继续走原来的 HTML + files/download 流程。
|
||||
|
||||
本脚本用于本地复现/回归验证这条判断逻辑, 并顺带跑一遍完整的取直链流程。
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
import requests
|
||||
|
||||
# 直接写死分享链接, 不通过命令行参数传入
|
||||
SHARE_URL = "https://v2.fangcloud.cn/h5/share/ded6dc6b9c3672b40b769804bf"
|
||||
|
||||
# 如果分享有密码, 在这里填上, 没有就留空字符串
|
||||
SHARE_PASSWORD = ""
|
||||
|
||||
HEADERS = {
|
||||
"User-Agent": (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
|
||||
),
|
||||
"Accept": "application/json, text/html;q=0.9, */*;q=0.8",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
||||
}
|
||||
|
||||
# 修复后的正则, 额外兼容 /h5/share/ 移动端落地页路径 (对齐 PanDomainTemplate.FC)
|
||||
FC_REGEX = re.compile(r"https://v2\.fangcloud\.(com|cn)/(?:h5/)?(s|share|sharing)/(?P<KEY>.+)")
|
||||
|
||||
SHARE_INFO_URL = "https://v2.fangcloud.cn/apps/share_links/info/{key}"
|
||||
SHARE_URL_PREFIX = "https://v2.fangcloud.com/sharing/{key}"
|
||||
DOWN_REQUEST_URL = "https://v2.fangcloud.cn/apps/files/download"
|
||||
|
||||
TYPED_ID_RE = re.compile(r'id="typed_id"\s+value="file_(\d+)"')
|
||||
|
||||
|
||||
def extract_share_key(url: str) -> str:
|
||||
m = FC_REGEX.search(url)
|
||||
if not m:
|
||||
raise ValueError(f"无法从链接中提取 shareKey (正则不匹配): {url}")
|
||||
return m.group("KEY")
|
||||
|
||||
|
||||
def check_is_valid(share_key: str, session: requests.Session) -> bool:
|
||||
print("=" * 70)
|
||||
print("Step 1. 请求 share_links/info 判断分享有效性 (对齐 FcTool.java 修复后的逻辑)")
|
||||
print("=" * 70)
|
||||
url = SHARE_INFO_URL.format(key=share_key)
|
||||
r = session.get(url, timeout=15)
|
||||
print(f"GET {url}")
|
||||
print(f"状态码: {r.status_code}")
|
||||
try:
|
||||
data = r.json()
|
||||
except Exception:
|
||||
print("响应不是合法JSON => 判定分享已失效或不存在\n")
|
||||
return False
|
||||
|
||||
process = data.get("process")
|
||||
if not process:
|
||||
print("响应中没有 process 字段 => 判定分享已失效或不存在\n")
|
||||
return False
|
||||
|
||||
is_closed = bool(process.get("is_closed"))
|
||||
is_expired = bool(process.get("is_expired"))
|
||||
item = process.get("item")
|
||||
print(f"is_closed = {is_closed}, is_expired = {is_expired}, item = {item}")
|
||||
|
||||
if is_closed or is_expired:
|
||||
print("=> 分享已失效或不存在\n")
|
||||
return False
|
||||
|
||||
print("=> 分享有效\n")
|
||||
return True
|
||||
|
||||
|
||||
def get_download_url(share_key: str, pwd: str, session: requests.Session) -> str:
|
||||
print("=" * 70)
|
||||
print("Step 2. 走原有 HTML + files/download 流程取直链")
|
||||
print("=" * 70)
|
||||
r = session.get(SHARE_URL_PREFIX.format(key=share_key), timeout=15)
|
||||
print(f"GET {SHARE_URL_PREFIX.format(key=share_key)} -> {r.status_code}, 最终URL: {r.url}")
|
||||
|
||||
html = r.text
|
||||
if pwd:
|
||||
# 加密分享: 提交密码换取跳转后的落地页 (此处仅示意, 具体见 FcTool.java)
|
||||
m = re.search(r'name="requesttoken"\s+value="([a-zA-Z0-9_+=]+)"', html)
|
||||
if not m:
|
||||
raise RuntimeError("未匹配到加密分享的密码输入页面的 requesttoken")
|
||||
token = m.group(1)
|
||||
r2 = session.post(
|
||||
"https://v2.fangcloud.cn/sharing/" + share_key,
|
||||
data={"requesttoken": token, "password": pwd},
|
||||
timeout=15,
|
||||
)
|
||||
html = r2.text
|
||||
|
||||
m = TYPED_ID_RE.search(html)
|
||||
if not m:
|
||||
raise RuntimeError("未匹配到文件id(typed_id), 分享可能是文件夹或页面结构有变化")
|
||||
fid = m.group(1)
|
||||
print(f"提取到 file_id = {fid}")
|
||||
|
||||
r3 = session.get(
|
||||
DOWN_REQUEST_URL,
|
||||
params={"file_id": fid, "scenario": "share", "unique_name": share_key},
|
||||
timeout=15,
|
||||
allow_redirects=False,
|
||||
)
|
||||
print(f"GET {DOWN_REQUEST_URL} -> {r3.status_code}")
|
||||
if r3.status_code in (301, 302) and r3.headers.get("Location"):
|
||||
return r3.headers["Location"]
|
||||
data = r3.json()
|
||||
if not data.get("success"):
|
||||
raise RuntimeError(f"取直链失败: {data}")
|
||||
return data["download_url"]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
share_key = extract_share_key(SHARE_URL)
|
||||
print(f"分享链接: {SHARE_URL}")
|
||||
print(f"提取到的 shareKey: {share_key}\n")
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update(HEADERS)
|
||||
|
||||
if not check_is_valid(share_key, session):
|
||||
print("结论: 分享无效, 不再继续取直链。")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
url = get_download_url(share_key, SHARE_PASSWORD, session)
|
||||
print(f"\n>>> 直链: {url}")
|
||||
except Exception as e:
|
||||
print(f"\n取直链失败: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,13 +1,14 @@
|
||||
{
|
||||
"name": "nfd-web",
|
||||
"version": "0.4.2",
|
||||
"version": "0.4.10",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"serve": "vue-cli-service serve",
|
||||
"dev": "vue-cli-service serve",
|
||||
"build": "node scripts/sync-version.js && vue-cli-service build && node scripts/compress-vs.js",
|
||||
"build:no-compress": "node scripts/sync-version.js && vue-cli-service build",
|
||||
"lint": "vue-cli-service lint"
|
||||
"lint": "vue-cli-service lint",
|
||||
"test": "node --test src/utils/batchTreeCollect.spec.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.1",
|
||||
|
||||
@@ -103,7 +103,23 @@
|
||||
<splitpanes v-if="!isMobile" class="split-theme custom-splitpanes" style="height:100%;">
|
||||
<pane>
|
||||
<div class="tree-sidebar">
|
||||
<div class="tree-scroll-wrap">
|
||||
<div class="tree-toolbar">
|
||||
<span class="tree-toolbar-title">
|
||||
<i class="fas fa-sitemap" aria-hidden="true"></i> 文件树
|
||||
</span>
|
||||
<el-button
|
||||
v-if="!batchMode"
|
||||
type="warning"
|
||||
size="small"
|
||||
@click="toggleBatchMode"
|
||||
>
|
||||
<i class="fas fa-check-double"></i> 批量下载
|
||||
</el-button>
|
||||
<span v-else class="tree-toolbar-hint">
|
||||
{{ treeExpanding ? '正在展开并收集文件…' : `勾选文件夹将自动展开(最多 ${effectiveBatchMaxDepth} 层)` }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
||||
<el-tree
|
||||
ref="fileTree"
|
||||
:data="treeData"
|
||||
@@ -115,6 +131,7 @@
|
||||
:show-checkbox="batchMode"
|
||||
:check-strictly="false"
|
||||
@node-click="onNodeClick"
|
||||
@check="onTreeCheck"
|
||||
@check-change="onTreeCheckChange"
|
||||
:default-expand-all="false"
|
||||
:default-expanded-keys="['root']"
|
||||
@@ -128,7 +145,7 @@
|
||||
<el-button
|
||||
type="primary"
|
||||
size="small"
|
||||
:disabled="selectedFiles.length === 0 || batchDownloading || batchBrowserDownloadDisabled"
|
||||
:disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding || batchBrowserDownloadDisabled"
|
||||
:loading="batchDownloading"
|
||||
@click="batchBrowserDownload"
|
||||
:title="batchBrowserDownloadDisabled ? '所选文件需使用下载器下载' : ''"
|
||||
@@ -138,7 +155,7 @@
|
||||
<el-button
|
||||
type="success"
|
||||
size="small"
|
||||
:disabled="selectedFiles.length === 0 || batchDownloading"
|
||||
:disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding"
|
||||
:loading="batchDownloading"
|
||||
@click="batchSendToDownloader"
|
||||
>
|
||||
@@ -236,7 +253,23 @@
|
||||
<!-- 移动端:上下布局 -->
|
||||
<template v-else>
|
||||
<div class="mobile-tree-top">
|
||||
<div class="tree-scroll-wrap">
|
||||
<div class="tree-toolbar">
|
||||
<span class="tree-toolbar-title">
|
||||
<i class="fas fa-sitemap" aria-hidden="true"></i> 文件树
|
||||
</span>
|
||||
<el-button
|
||||
v-if="!batchMode"
|
||||
type="warning"
|
||||
size="small"
|
||||
@click="toggleBatchMode"
|
||||
>
|
||||
<i class="fas fa-check-double"></i> 批量下载
|
||||
</el-button>
|
||||
<span v-else class="tree-toolbar-hint">
|
||||
{{ treeExpanding ? '正在展开并收集文件…' : `勾选文件夹将自动展开(最多 ${effectiveBatchMaxDepth} 层)` }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
||||
<el-tree
|
||||
ref="fileTree"
|
||||
:data="treeData"
|
||||
@@ -248,6 +281,7 @@
|
||||
:show-checkbox="batchMode"
|
||||
:check-strictly="false"
|
||||
@node-click="onNodeClick"
|
||||
@check="onTreeCheck"
|
||||
@check-change="onTreeCheckChange"
|
||||
:default-expand-all="false"
|
||||
:default-expanded-keys="['root']"
|
||||
@@ -328,8 +362,8 @@
|
||||
<div v-if="batchMode" class="mobile-batch-footer">
|
||||
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
||||
<div class="tree-sidebar-actions">
|
||||
<el-button type="primary" size="small" :disabled="selectedFiles.length === 0 || batchDownloading || batchBrowserDownloadDisabled" :loading="batchDownloading" @click="batchBrowserDownload" :title="batchBrowserDownloadDisabled ? '所选文件需使用下载器下载' : ''">浏览器下载</el-button>
|
||||
<el-button type="success" size="small" :disabled="selectedFiles.length === 0 || batchDownloading" :loading="batchDownloading" @click="batchSendToDownloader">发送到下载器</el-button>
|
||||
<el-button type="primary" size="small" :disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding || batchBrowserDownloadDisabled" :loading="batchDownloading" @click="batchBrowserDownload" :title="batchBrowserDownloadDisabled ? '所选文件需使用下载器下载' : ''">浏览器下载</el-button>
|
||||
<el-button type="success" size="small" :disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding" :loading="batchDownloading" @click="batchSendToDownloader">发送到下载器</el-button>
|
||||
<el-button size="small" @click="toggleBatchMode">取消</el-button>
|
||||
</div>
|
||||
<div v-if="batchDownloading" class="batch-progress-info">
|
||||
@@ -420,6 +454,16 @@ import 'splitpanes/dist/splitpanes.css'
|
||||
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,
|
||||
getTreeNodeId,
|
||||
normalizeTreeItem,
|
||||
uniqueFiles,
|
||||
collectFolderFiles
|
||||
} = batchTreeCollect
|
||||
|
||||
export default {
|
||||
name: 'DirectoryTree',
|
||||
@@ -445,6 +489,11 @@ export default {
|
||||
viewMode: {
|
||||
type: String,
|
||||
default: 'pane' // 'pane' or 'tree'
|
||||
},
|
||||
// 树批量勾选文件夹时的最大展开深度;用户勾选的文件夹为第 0 层,默认 5
|
||||
batchMaxDepth: {
|
||||
type: Number,
|
||||
default: DEFAULT_BATCH_MAX_DEPTH
|
||||
}
|
||||
},
|
||||
data() {
|
||||
@@ -477,7 +526,8 @@ export default {
|
||||
batchMode: false,
|
||||
selectedFiles: [],
|
||||
batchDownloading: false,
|
||||
batchProgress: { current: 0, total: 0, failed: 0 }
|
||||
batchProgress: { current: 0, total: 0, failed: 0 },
|
||||
treeExpanding: false
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
@@ -513,6 +563,10 @@ export default {
|
||||
batchBrowserDownloadDisabled() {
|
||||
return this.selectedFiles.length > 0
|
||||
&& this.selectedFiles.every(f => this.needsDownloader(f))
|
||||
},
|
||||
effectiveBatchMaxDepth() {
|
||||
const depth = Number(this.batchMaxDepth)
|
||||
return Number.isFinite(depth) && depth >= 0 ? depth : DEFAULT_BATCH_MAX_DEPTH
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
@@ -525,10 +579,7 @@ export default {
|
||||
id: 'root',
|
||||
fileName: '全部文件',
|
||||
fileType: 'folder',
|
||||
children: (newList || []).map(item => ({
|
||||
...item,
|
||||
isLeaf: item.fileType !== 'folder'
|
||||
})),
|
||||
children: (newList || []).map(item => normalizeTreeItem(item)),
|
||||
isLeaf: false
|
||||
}
|
||||
]
|
||||
@@ -536,6 +587,9 @@ export default {
|
||||
}
|
||||
}
|
||||
},
|
||||
created() {
|
||||
this.resetTreeCollectState()
|
||||
},
|
||||
methods: {
|
||||
...fileTypeUtils,
|
||||
apiKeyHeaders() {
|
||||
@@ -563,17 +617,14 @@ export default {
|
||||
}
|
||||
return this.withAuth(`${baseUrl}?${params.toString()}`)
|
||||
},
|
||||
// 懒加载子节点
|
||||
// 懒加载子节点(批量勾选文件夹时会通过 node.expand → store.load 复用此方法)
|
||||
loadNode(node, resolve) {
|
||||
if (node.level === 0) {
|
||||
resolve(this.treeData[0].children)
|
||||
resolve((this.treeData[0]?.children || []).map(item => normalizeTreeItem(item)))
|
||||
} else if (node.data.fileType === 'folder' && node.data.parserUrl) {
|
||||
axios.get(this.withAuth(node.data.parserUrl), { headers: this.apiKeyHeaders() }).then(res => {
|
||||
if (res.data.code === 200) {
|
||||
const children = (res.data.data || []).map(item => ({
|
||||
...item,
|
||||
isLeaf: item.fileType !== 'folder'
|
||||
}))
|
||||
const children = (res.data.data || []).map(item => normalizeTreeItem(item))
|
||||
resolve(children)
|
||||
} else {
|
||||
this.$message.error(res.data.msg || '获取子节点失败')
|
||||
@@ -708,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('该文件暂无下载链接')
|
||||
@@ -755,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)
|
||||
@@ -898,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) {
|
||||
@@ -970,9 +1001,156 @@ export default {
|
||||
this.selectedFiles = []
|
||||
this.batchDownloading = false
|
||||
this.batchProgress = { current: 0, total: 0, failed: 0 }
|
||||
// tree 模式下清除勾选
|
||||
if (this.$refs.fileTree) {
|
||||
this.$refs.fileTree.setCheckedKeys([])
|
||||
this.treeExpanding = false
|
||||
this.resetTreeCollectState()
|
||||
const tree = this.getFileTree()
|
||||
if (tree) {
|
||||
tree.setCheckedKeys([])
|
||||
}
|
||||
},
|
||||
resetTreeCollectState() {
|
||||
this._folderCheckQueue = []
|
||||
this._queuedFolderKeys = new Set()
|
||||
this._visitedInCollect = new Set()
|
||||
this._folderLoadPromises = new Map()
|
||||
this._treeCollecting = false
|
||||
},
|
||||
getFileTree() {
|
||||
const ref = this.$refs.fileTree
|
||||
if (!ref) return null
|
||||
return Array.isArray(ref) ? ref[0] : ref
|
||||
},
|
||||
findTreeNode(data) {
|
||||
const tree = this.getFileTree()
|
||||
if (!tree || !data) return null
|
||||
const key = getTreeNodeId(data)
|
||||
if (key) {
|
||||
const byKey = tree.getNode(key)
|
||||
if (byKey) return byKey
|
||||
}
|
||||
const byData = tree.getNode(data)
|
||||
if (byData) return byData
|
||||
const nodesMap = tree.store?.nodesMap
|
||||
if (nodesMap) {
|
||||
return Object.values(nodesMap).find(node => getTreeNodeId(node.data) === key) || null
|
||||
}
|
||||
return null
|
||||
},
|
||||
ensureTreeNodeLoaded(node) {
|
||||
if (!node) return Promise.resolve(null)
|
||||
const key = getTreeNodeId(node.data)
|
||||
if (key && this._folderLoadPromises.has(key)) {
|
||||
return this._folderLoadPromises.get(key)
|
||||
}
|
||||
const promise = new Promise((resolve) => {
|
||||
if (node.loaded && node.expanded) {
|
||||
resolve(node)
|
||||
return
|
||||
}
|
||||
let settled = false
|
||||
const finish = () => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
resolve(node)
|
||||
}
|
||||
const timer = setTimeout(finish, 20000)
|
||||
const expandNow = () => {
|
||||
if (node.loaded && node.expanded) {
|
||||
clearTimeout(timer)
|
||||
finish()
|
||||
return
|
||||
}
|
||||
try {
|
||||
node.expand(() => {
|
||||
clearTimeout(timer)
|
||||
finish()
|
||||
})
|
||||
} catch (e) {
|
||||
clearTimeout(timer)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
if (node.loading) {
|
||||
const started = Date.now()
|
||||
const poll = () => {
|
||||
if (!node.loading || Date.now() - started > 20000) {
|
||||
expandNow()
|
||||
return
|
||||
}
|
||||
setTimeout(poll, 50)
|
||||
}
|
||||
poll()
|
||||
return
|
||||
}
|
||||
expandNow()
|
||||
})
|
||||
if (key) this._folderLoadPromises.set(key, promise)
|
||||
return promise
|
||||
},
|
||||
isCheckedInInfo(data, info) {
|
||||
if (!info) return false
|
||||
const key = getTreeNodeId(data)
|
||||
if (key && (info.checkedKeys || []).map(String).includes(key)) return true
|
||||
return (info.checkedNodes || []).some(n => getTreeNodeId(n) === key)
|
||||
},
|
||||
syncSelectedFilesFromTree(extraFiles = []) {
|
||||
const tree = this.getFileTree()
|
||||
const fromTree = tree
|
||||
? tree.getCheckedNodes().filter(n => this.isDownloadableFile(n))
|
||||
: []
|
||||
this.selectedFiles = uniqueFiles([...fromTree, ...extraFiles])
|
||||
},
|
||||
enqueueFolderCollect(folderData) {
|
||||
const key = getTreeNodeId(folderData)
|
||||
if (!key || this._queuedFolderKeys.has(key) || this._visitedInCollect.has(key)) return
|
||||
this._queuedFolderKeys.add(key)
|
||||
this._folderCheckQueue.push(folderData)
|
||||
this.drainFolderCollectQueue()
|
||||
},
|
||||
async drainFolderCollectQueue() {
|
||||
if (this._treeCollecting) return
|
||||
this._treeCollecting = true
|
||||
this.treeExpanding = true
|
||||
try {
|
||||
while (this._folderCheckQueue.length) {
|
||||
const next = this._folderCheckQueue.shift()
|
||||
this._queuedFolderKeys.delete(getTreeNodeId(next))
|
||||
await this.handleFolderCheck(next)
|
||||
}
|
||||
} finally {
|
||||
this._treeCollecting = false
|
||||
this.treeExpanding = false
|
||||
this._visitedInCollect.clear()
|
||||
}
|
||||
},
|
||||
async handleFolderCheck(folderData) {
|
||||
try {
|
||||
const ctx = await collectFolderFiles({
|
||||
folderData,
|
||||
depth: 0,
|
||||
maxDepth: this.effectiveBatchMaxDepth,
|
||||
getNode: (data) => this.findTreeNode(data),
|
||||
ensureLoaded: (node) => this.ensureTreeNodeLoaded(node),
|
||||
isDownloadable: (data) => this.isDownloadableFile(data),
|
||||
visitedKeys: this._visitedInCollect
|
||||
})
|
||||
this.syncSelectedFilesFromTree(ctx.files)
|
||||
if (ctx.depthExceeded) {
|
||||
this.$message.warning(
|
||||
`已达到最大展开深度(${this.effectiveBatchMaxDepth} 层),部分深层文件未勾选`
|
||||
)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('批量展开文件夹失败:', e)
|
||||
this.$message.error('展开文件夹失败,已跳过部分内容')
|
||||
this.syncSelectedFilesFromTree()
|
||||
}
|
||||
},
|
||||
// 用户点击复选框(不含级联),文件夹勾选时触发递归展开
|
||||
onTreeCheck(data, info) {
|
||||
if (!this.batchMode || !data || data.fileType !== 'folder') return
|
||||
if (this.isCheckedInInfo(data, info)) {
|
||||
this.enqueueFolderCollect(data)
|
||||
}
|
||||
},
|
||||
isFileSelected(file) {
|
||||
@@ -988,6 +1166,8 @@ export default {
|
||||
}
|
||||
},
|
||||
onBatchClick(file) {
|
||||
// 窗格批量:点击文件夹仍进入该目录(避免破坏现有导航)。
|
||||
// 仅收集当前目录文件;递归展开只在树模式勾选文件夹时进行。
|
||||
if (file.fileType === 'folder') {
|
||||
this.enterFolder(file)
|
||||
return
|
||||
@@ -1001,9 +1181,8 @@ export default {
|
||||
this.selectedFiles = []
|
||||
},
|
||||
onTreeCheckChange() {
|
||||
if (!this.$refs.fileTree) return
|
||||
const checked = this.$refs.fileTree.getCheckedNodes()
|
||||
this.selectedFiles = checked.filter(n => this.isDownloadableFile(n))
|
||||
if (!this.batchMode || this._treeCollecting) return
|
||||
this.syncSelectedFilesFromTree()
|
||||
},
|
||||
extractTypeParam(file) {
|
||||
if (!file.parserUrl) return null
|
||||
@@ -1039,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++
|
||||
@@ -1762,6 +1935,48 @@ html, body, #app, .main-container, .directory-tree, .content-card {
|
||||
border-right: 1px solid #eaeaea;
|
||||
}
|
||||
|
||||
.tree-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
flex-shrink: 0;
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px solid #eaeaea;
|
||||
background: #f8f9fa;
|
||||
}
|
||||
|
||||
.dark-theme .tree-toolbar {
|
||||
border-bottom-color: #404040;
|
||||
background: #232323;
|
||||
}
|
||||
|
||||
.tree-toolbar-title {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.dark-theme .tree-toolbar-title {
|
||||
color: #e1e1e1;
|
||||
}
|
||||
|
||||
.tree-toolbar-hint {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.dark-theme .tree-toolbar-hint {
|
||||
color: #bdc3c7;
|
||||
}
|
||||
|
||||
.tree-content {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
@@ -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,65 @@
|
||||
<template>
|
||||
<el-radio-group
|
||||
:model-value="modelValue"
|
||||
size="small"
|
||||
class="view-mode-switch"
|
||||
@update:model-value="$emit('update:modelValue', $event)"
|
||||
>
|
||||
<el-radio-button label="pane" title="窗格视图">
|
||||
<i class="fas fa-th" aria-hidden="true"></i>
|
||||
<span class="view-mode-text">{{ paneLabel }}</span>
|
||||
</el-radio-button>
|
||||
<el-radio-button label="tree" title="文件树视图">
|
||||
<i class="fas fa-sitemap" aria-hidden="true"></i>
|
||||
<span class="view-mode-text">{{ treeLabel }}</span>
|
||||
</el-radio-button>
|
||||
</el-radio-group>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: 'ViewModeSwitch',
|
||||
props: {
|
||||
modelValue: {
|
||||
type: String,
|
||||
default: 'pane'
|
||||
},
|
||||
paneLabel: {
|
||||
type: String,
|
||||
default: '窗格'
|
||||
},
|
||||
treeLabel: {
|
||||
type: String,
|
||||
default: '文件树'
|
||||
}
|
||||
},
|
||||
emits: ['update:modelValue']
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.view-mode-switch :deep(.el-radio-button__inner) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
min-height: 36px;
|
||||
min-width: 76px;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
.view-mode-switch i {
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
}
|
||||
.view-mode-text {
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.view-mode-switch :deep(.el-radio-button__inner) {
|
||||
min-width: 68px;
|
||||
min-height: 40px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -246,8 +246,8 @@
|
||||
storage: 'hash'
|
||||
},
|
||||
'123pan': {
|
||||
reg: /((?:https?:\/\/)?www\.(123pan|123865|123684)\.com\/s\/[\w-]{6,})/,
|
||||
host: /www\.123pan\.com/,
|
||||
reg: /((?:https?:\/\/)?(?:[a-zA-Z\d-]+\.(?:m?share)\.123pan\.cn\/123pan\/[\w-]+|(?:www\.)?(?:123panpay|123pan|123\d{3})\.(?:com|cn)\/s\/[\w-]{6,}(?:\.html)?)(?:\?[^#\s]*)?)/i,
|
||||
host: /(?:[a-zA-Z\d-]+\.(?:m?share)\.123pan\.cn|(?:www\.)?(?:123panpay|123pan|123\d{3})\.(?:com|cn))/i,
|
||||
input: ['.ca-fot input', ".appinput .appinput"],
|
||||
button: ['.ca-fot button', ".appinput button"],
|
||||
name: '123云盘',
|
||||
@@ -377,6 +377,7 @@
|
||||
parseLink(text = '') {
|
||||
let obj = {name: '', link: '', storage: '', storagePwdName: ''};
|
||||
if (text) {
|
||||
text = String(text).trim();
|
||||
try {
|
||||
text = decodeURIComponent(text);
|
||||
} catch {
|
||||
@@ -390,6 +391,9 @@
|
||||
let matches = text.match(val.reg);
|
||||
obj.name = val.name;
|
||||
obj.link = matches[0];
|
||||
if (obj.link && !/^https?:\/\//i.test(obj.link)) {
|
||||
obj.link = 'https://' + obj.link.replace(/^\/\//, '');
|
||||
}
|
||||
obj.storage = val.storage;
|
||||
obj.storagePwdName = val.storagePwdName || null;
|
||||
if (val.replaceHost) {
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* 文件树批量勾选:按深度递归展开并收集可下载文件。
|
||||
*
|
||||
* Depth convention (checked folder = depth 0):
|
||||
* - 用户勾选的文件夹为第 0 层。
|
||||
* - 其直接子项为第 1 层。
|
||||
* - 当 depth < maxDepth 时继续展开子文件夹;默认 maxDepth = 5,
|
||||
* 即最多再向下展开 5 层(第 0/1/2/3/4 层会 load,第 5 层文件夹不再展开)。
|
||||
* - 触及上限时若仍有未加载/剩余子文件夹,标记 depthExceeded,由 UI 提示跳过。
|
||||
*/
|
||||
|
||||
const DEFAULT_BATCH_MAX_DEPTH = 5
|
||||
|
||||
function getTreeNodeId(item) {
|
||||
if (!item) return ''
|
||||
if (item.id) return String(item.id)
|
||||
if (item.fileId) return `fid:${item.fileId}`
|
||||
if (item.parserUrl) return `url:${item.parserUrl}`
|
||||
return `name:${item.fileName || ''}:${item.fileType || ''}`
|
||||
}
|
||||
|
||||
function normalizeTreeItem(item) {
|
||||
if (!item || typeof item !== 'object') return item
|
||||
return {
|
||||
...item,
|
||||
id: getTreeNodeId(item),
|
||||
isLeaf: item.fileType !== 'folder'
|
||||
}
|
||||
}
|
||||
|
||||
function fileIdentity(file) {
|
||||
return `${file?.parserUrl || ''}::${file?.fileName || ''}::${file?.fileId || file?.id || ''}`
|
||||
}
|
||||
|
||||
function uniqueFiles(files) {
|
||||
const seen = new Set()
|
||||
const out = []
|
||||
for (const file of files || []) {
|
||||
const key = fileIdentity(file)
|
||||
if (!key || seen.has(key)) continue
|
||||
seen.add(key)
|
||||
out.push(file)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function isFolderNode(data) {
|
||||
return !!(data && data.fileType === 'folder')
|
||||
}
|
||||
|
||||
function collectAlreadyLoadedFiles(node, isDownloadable, ctx) {
|
||||
for (const child of node.childNodes || []) {
|
||||
if (isDownloadable(child.data)) {
|
||||
ctx.files.push(child.data)
|
||||
} else if (isFolderNode(child.data) && child.loaded) {
|
||||
collectAlreadyLoadedFiles(child, isDownloadable, ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function hasUnexploredFolders(node) {
|
||||
if (!node) return false
|
||||
if (isFolderNode(node.data) && !node.loaded) return true
|
||||
return (node.childNodes || []).some((child) => {
|
||||
if (!isFolderNode(child.data)) return false
|
||||
if (!child.loaded) return true
|
||||
return hasUnexploredFolders(child)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归展开文件夹并收集可下载文件(对接 el-tree node / loadNode)。
|
||||
*
|
||||
* @param {object} opts
|
||||
* @param {object} opts.folderData 勾选的文件夹 data(depth 从 0 计)
|
||||
* @param {number} [opts.depth=0]
|
||||
* @param {number} opts.maxDepth
|
||||
* @param {(data: object) => any} opts.getNode el-tree getNode
|
||||
* @param {(node: any) => Promise<any>} opts.ensureLoaded 展开并触发懒加载
|
||||
* @param {(data: object) => boolean} opts.isDownloadable
|
||||
* @param {Set<string>} [opts.visitedKeys]
|
||||
* @param {(data: object) => string} [opts.getKey]
|
||||
* @param {{ files: object[], depthExceeded: boolean }} [opts.ctx]
|
||||
*/
|
||||
async function collectFolderFiles(opts) {
|
||||
const {
|
||||
folderData,
|
||||
depth = 0,
|
||||
maxDepth,
|
||||
getNode,
|
||||
ensureLoaded,
|
||||
isDownloadable,
|
||||
getKey = getTreeNodeId,
|
||||
visitedKeys = new Set(),
|
||||
ctx = { files: [], depthExceeded: false }
|
||||
} = opts
|
||||
|
||||
if (!folderData || typeof maxDepth !== 'number') return ctx
|
||||
|
||||
const key = getKey(folderData)
|
||||
if (key) visitedKeys.add(key)
|
||||
|
||||
const node = getNode(folderData)
|
||||
if (!node) return ctx
|
||||
|
||||
if (depth >= maxDepth) {
|
||||
// 未 load 的节点在真实 el-tree 中没有 childNodes,不能把预置子项算进去
|
||||
if (node.loaded) {
|
||||
collectAlreadyLoadedFiles(node, isDownloadable, ctx)
|
||||
if (hasUnexploredFolders(node)) {
|
||||
ctx.depthExceeded = true
|
||||
}
|
||||
} else if (isFolderNode(node.data)) {
|
||||
ctx.depthExceeded = true
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureLoaded(node)
|
||||
} catch {
|
||||
// 单层加载失败:跳过该分支,不中断整次收集
|
||||
return ctx
|
||||
}
|
||||
|
||||
for (const child of node.childNodes || []) {
|
||||
const data = child.data
|
||||
if (!data) continue
|
||||
if (isDownloadable(data)) {
|
||||
ctx.files.push(data)
|
||||
} else if (isFolderNode(data)) {
|
||||
await collectFolderFiles({
|
||||
...opts,
|
||||
folderData: data,
|
||||
depth: depth + 1,
|
||||
visitedKeys,
|
||||
ctx
|
||||
})
|
||||
}
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_BATCH_MAX_DEPTH,
|
||||
getTreeNodeId,
|
||||
normalizeTreeItem,
|
||||
fileIdentity,
|
||||
uniqueFiles,
|
||||
isFolderNode,
|
||||
collectFolderFiles
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
const { describe, it } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
|
||||
const {
|
||||
DEFAULT_BATCH_MAX_DEPTH,
|
||||
getTreeNodeId,
|
||||
normalizeTreeItem,
|
||||
fileIdentity,
|
||||
uniqueFiles,
|
||||
collectFolderFiles
|
||||
} = require('./batchTreeCollect.js')
|
||||
|
||||
function file(name, extra = {}) {
|
||||
return {
|
||||
fileName: name,
|
||||
fileType: 'file',
|
||||
parserUrl: `/v2/redirectUrl/demo/${name}`,
|
||||
...extra
|
||||
}
|
||||
}
|
||||
|
||||
function folder(name, extra = {}) {
|
||||
return {
|
||||
fileName: name,
|
||||
fileType: 'folder',
|
||||
parserUrl: `/v2/getFileList?dir=${name}`,
|
||||
...extra
|
||||
}
|
||||
}
|
||||
|
||||
function makeNode(data, children = [], { loaded = true, expanded = true, failLoad = false } = {}) {
|
||||
const node = {
|
||||
data,
|
||||
loaded,
|
||||
expanded,
|
||||
childNodes: [],
|
||||
expand(cb) {
|
||||
if (failLoad) throw new Error('load failed')
|
||||
this.loaded = true
|
||||
this.expanded = true
|
||||
if (cb) cb()
|
||||
}
|
||||
}
|
||||
node.childNodes = children.map((child) => (child.data ? child : makeNode(child)))
|
||||
return node
|
||||
}
|
||||
|
||||
function createStore(rootNode) {
|
||||
const map = new Map()
|
||||
const walk = (node) => {
|
||||
map.set(getTreeNodeId(node.data), node)
|
||||
for (const child of node.childNodes || []) walk(child)
|
||||
}
|
||||
walk(rootNode)
|
||||
return {
|
||||
getNode(data) {
|
||||
return map.get(getTreeNodeId(data)) || null
|
||||
},
|
||||
async ensureLoaded(node) {
|
||||
if (node.loaded && node.expanded) return node
|
||||
await new Promise((resolve) => node.expand(resolve))
|
||||
for (const child of node.childNodes || []) {
|
||||
map.set(getTreeNodeId(child.data), child)
|
||||
}
|
||||
return node
|
||||
},
|
||||
isDownloadable(data) {
|
||||
return !!(data && data.parserUrl && data.fileType !== 'folder' && data.fileType !== 'url')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('batchTreeCollect helpers', () => {
|
||||
it('uses checked folder as depth 0 and defaults max depth to 5', () => {
|
||||
assert.equal(DEFAULT_BATCH_MAX_DEPTH, 5)
|
||||
assert.equal(getTreeNodeId({ id: 'root' }), 'root')
|
||||
assert.equal(normalizeTreeItem({ fileId: 'abc', fileType: 'folder' }).id, 'fid:abc')
|
||||
assert.equal(normalizeTreeItem({ fileId: 'abc', fileType: 'folder' }).isLeaf, false)
|
||||
})
|
||||
|
||||
it('deduplicates files by parserUrl + name + id', () => {
|
||||
const a = file('a.txt', { fileId: '1' })
|
||||
const dup = file('a.txt', { fileId: '1' })
|
||||
const b = file('b.txt', { fileId: '2' })
|
||||
assert.equal(fileIdentity(a), fileIdentity(dup))
|
||||
assert.deepEqual(uniqueFiles([a, dup, b]).map((f) => f.fileName), ['a.txt', 'b.txt'])
|
||||
})
|
||||
|
||||
it('collects current-level files and recurses into folders', async () => {
|
||||
const leafA = file('a.txt')
|
||||
const leafB = file('b.txt')
|
||||
const nested = folder('nested')
|
||||
const root = folder('root')
|
||||
const store = createStore(makeNode(root, [
|
||||
makeNode(leafA),
|
||||
makeNode(nested, [makeNode(leafB)])
|
||||
]))
|
||||
|
||||
const ctx = await collectFolderFiles({
|
||||
folderData: root,
|
||||
maxDepth: 4,
|
||||
...store
|
||||
})
|
||||
assert.equal(ctx.depthExceeded, false)
|
||||
assert.deepEqual(ctx.files.map((f) => f.fileName).sort(), ['a.txt', 'b.txt'])
|
||||
})
|
||||
|
||||
it('default depth 5 expands four descendant folders then stops', async () => {
|
||||
// depth 0 root → 1 d1 → 2 d2 → 3 d3 → 4 d4 → 5 d5 (cap, still has leftover folder)
|
||||
const skipped = file('skipped.txt')
|
||||
const capFile = file('cap.txt')
|
||||
const d5 = folder('d5')
|
||||
const d4 = folder('d4')
|
||||
const d3 = folder('d3')
|
||||
const d2 = folder('d2')
|
||||
const d1 = folder('d1')
|
||||
const root = folder('root')
|
||||
const tree = makeNode(root, [
|
||||
makeNode(d1, [
|
||||
makeNode(d2, [
|
||||
makeNode(d3, [
|
||||
makeNode(d4, [
|
||||
makeNode(d5, [
|
||||
makeNode(capFile),
|
||||
makeNode(folder('d6'), [makeNode(skipped)], { loaded: false, expanded: false })
|
||||
], { loaded: true })
|
||||
])
|
||||
])
|
||||
])
|
||||
])
|
||||
])
|
||||
const store = createStore(tree)
|
||||
const loadedIds = []
|
||||
const ctx = await collectFolderFiles({
|
||||
folderData: root,
|
||||
maxDepth: DEFAULT_BATCH_MAX_DEPTH,
|
||||
getNode: store.getNode,
|
||||
ensureLoaded: async (node) => {
|
||||
loadedIds.push(node.data.fileName)
|
||||
return store.ensureLoaded(node)
|
||||
},
|
||||
isDownloadable: store.isDownloadable
|
||||
})
|
||||
assert.equal(ctx.depthExceeded, true)
|
||||
assert.deepEqual(ctx.files.map((f) => f.fileName), ['cap.txt'])
|
||||
assert.ok(!ctx.files.some((f) => f.fileName === 'skipped.txt'))
|
||||
assert.ok(loadedIds.includes('d4'))
|
||||
assert.ok(!loadedIds.includes('d5'))
|
||||
})
|
||||
|
||||
it('stops expanding at maxDepth and warns when remaining folders exist', async () => {
|
||||
// depth 0: root
|
||||
// depth 1: d1
|
||||
// depth 2: d2
|
||||
// depth 3: d3
|
||||
// depth 4: d4 (cap when maxDepth=4) — still has child folder d5
|
||||
const deepFile = file('deep.txt')
|
||||
const skipped = file('skipped.txt')
|
||||
const d5 = folder('d5')
|
||||
const d4 = folder('d4')
|
||||
const d3 = folder('d3')
|
||||
const d2 = folder('d2')
|
||||
const d1 = folder('d1')
|
||||
const root = folder('root')
|
||||
|
||||
const d5Node = makeNode(d5, [makeNode(skipped)], { loaded: false, expanded: false })
|
||||
const d4Node = makeNode(d4, [makeNode(deepFile), d5Node], { loaded: true })
|
||||
const tree = makeNode(root, [
|
||||
makeNode(d1, [
|
||||
makeNode(d2, [
|
||||
makeNode(d3, [d4Node])
|
||||
])
|
||||
])
|
||||
])
|
||||
const store = createStore(tree)
|
||||
|
||||
let loadedIds = []
|
||||
const ctx = await collectFolderFiles({
|
||||
folderData: root,
|
||||
maxDepth: 4,
|
||||
getNode: store.getNode,
|
||||
ensureLoaded: async (node) => {
|
||||
loadedIds.push(node.data.fileName)
|
||||
return store.ensureLoaded(node)
|
||||
},
|
||||
isDownloadable: store.isDownloadable
|
||||
})
|
||||
|
||||
assert.equal(ctx.depthExceeded, true)
|
||||
assert.deepEqual(ctx.files.map((f) => f.fileName), ['deep.txt'])
|
||||
assert.ok(!ctx.files.some((f) => f.fileName === 'skipped.txt'))
|
||||
assert.ok(!loadedIds.includes('d4'), 'depth-4 folder must not be expanded')
|
||||
assert.ok(loadedIds.includes('root'))
|
||||
assert.ok(loadedIds.includes('d3'))
|
||||
})
|
||||
|
||||
it('collects already-loaded files at the depth cap without expanding further', async () => {
|
||||
const capFile = file('cap.txt')
|
||||
const inner = folder('inner')
|
||||
const cap = folder('cap')
|
||||
const root = folder('root')
|
||||
const tree = makeNode(root, [
|
||||
makeNode(cap, [
|
||||
makeNode(capFile),
|
||||
makeNode(inner, [makeNode(file('too-deep.txt'))], { loaded: false })
|
||||
])
|
||||
])
|
||||
const store = createStore(tree)
|
||||
const ctx = await collectFolderFiles({
|
||||
folderData: root,
|
||||
maxDepth: 1,
|
||||
...store
|
||||
})
|
||||
assert.equal(ctx.depthExceeded, true)
|
||||
assert.deepEqual(ctx.files.map((f) => f.fileName), ['cap.txt'])
|
||||
})
|
||||
|
||||
it('skips a branch when ensureLoaded throws', async () => {
|
||||
const ok = file('ok.txt')
|
||||
const badFolder = folder('bad')
|
||||
const root = folder('root')
|
||||
const badNode = makeNode(badFolder, [makeNode(file('lost.txt'))], { loaded: false, failLoad: true })
|
||||
const tree = makeNode(root, [makeNode(ok), badNode])
|
||||
const store = createStore(tree)
|
||||
const ctx = await collectFolderFiles({
|
||||
folderData: root,
|
||||
maxDepth: 4,
|
||||
getNode: store.getNode,
|
||||
ensureLoaded: async (node) => {
|
||||
if (node.data.fileName === 'bad') throw new Error('network')
|
||||
return store.ensureLoaded(node)
|
||||
},
|
||||
isDownloadable: store.isDownloadable
|
||||
})
|
||||
assert.deepEqual(ctx.files.map((f) => f.fileName), ['ok.txt'])
|
||||
})
|
||||
})
|
||||
@@ -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">
|
||||
@@ -90,7 +90,7 @@
|
||||
<!-- 开关按钮,控制是否自动读取剪切板 -->
|
||||
<el-switch v-model="autoReadClipboard" active-text="自动识别剪切板"></el-switch>
|
||||
|
||||
<el-input placeholder="请粘贴分享链接(http://或https://)" v-model="link" id="url" @paste="onPaste">
|
||||
<el-input placeholder="请粘贴分享链接(http://或https://)" v-model="link" id="url" @paste="onPaste" @blur="normalizeShortcutInput">
|
||||
<template #prepend>分享链接</template>
|
||||
<template #append v-if="!autoReadClipboard">
|
||||
<el-button @click="getPaste(true)">读取剪切板</el-button>
|
||||
@@ -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,11 +421,14 @@
|
||||
|
||||
<!-- 目录树组件 -->
|
||||
<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;">
|
||||
<el-radio-group v-model="directoryViewMode" size="small">
|
||||
<el-radio-button label="pane">窗格</el-radio-button>
|
||||
<el-radio-button label="tree">文件树</el-radio-button>
|
||||
</el-radio-group>
|
||||
<ViewModeSwitch v-model="directoryViewMode" pane-label="窗格" tree-label="文件树" />
|
||||
</div>
|
||||
<DirectoryTree
|
||||
:file-list="directoryData"
|
||||
@@ -619,8 +627,11 @@ import axios from 'axios'
|
||||
import QRCode from 'qrcode'
|
||||
import DarkMode from '@/components/DarkMode'
|
||||
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'
|
||||
@@ -629,7 +640,7 @@ import { PREVIEW_BASE_URL } from '@/utils/constants'
|
||||
|
||||
export default {
|
||||
name: 'Home',
|
||||
components: { DarkMode, DirectoryTree, DownloadDialog },
|
||||
components: { DarkMode, DirectoryTree, ViewModeSwitch, DownloadDialog },
|
||||
mixins: [fileTypeUtils],
|
||||
data() {
|
||||
return {
|
||||
@@ -752,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()
|
||||
@@ -772,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: {
|
||||
@@ -1143,10 +1182,24 @@ export default {
|
||||
normalizeShortcutInput() {
|
||||
if (!this.link) return
|
||||
const trimmed = this.link.trim()
|
||||
if (!trimmed) return
|
||||
if (!trimmed) {
|
||||
this.link = ''
|
||||
return
|
||||
}
|
||||
this.link = trimmed
|
||||
|
||||
// 已经是直接链接,跳过
|
||||
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) return
|
||||
// 已经是直接链接:仍尝试从整段文本中抽出标准分享地址
|
||||
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
|
||||
const linkInfo = parserUrl.parseLink(trimmed)
|
||||
if (linkInfo.link) {
|
||||
this.link = linkInfo.link
|
||||
const pwd = parserUrl.parsePwd(trimmed)
|
||||
if (!this.password && pwd) {
|
||||
this.password = pwd
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 尝试短格式
|
||||
const shortInfo = this.expandShortFormat(trimmed)
|
||||
@@ -1156,6 +1209,7 @@ export default {
|
||||
this.password = shortInfo.pwd
|
||||
}
|
||||
this.$message.success(`已识别短格式并自动转换,网盘类型: ${shortInfo.name}`)
|
||||
this.updateDirectLink()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1168,6 +1222,7 @@ export default {
|
||||
this.password = pwd
|
||||
}
|
||||
this.$message.success(`已从文本中识别到 ${linkInfo.name} 分享链接`)
|
||||
this.updateDirectLink()
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1182,7 +1237,6 @@ export default {
|
||||
clearResults() {
|
||||
this.parseResult = {}
|
||||
this.downloadUrl = null
|
||||
this.directLink = ''
|
||||
this.markdownText = ''
|
||||
this.showQRCode = false
|
||||
this.statisticsData = {}
|
||||
@@ -1326,10 +1380,8 @@ export default {
|
||||
const directoryResult = await this.callAPI('/v2/getFileList', params)
|
||||
this.directoryData = directoryResult.data || []
|
||||
this.showDirectoryTree = true
|
||||
// 目录解析成功后,将目录落地页作为智能直链
|
||||
const listUrl = `${this.baseUrl}/showList?url=${encodeURIComponent(this.link)}`
|
||||
this.showListLink = listUrl
|
||||
this.directLink = listUrl
|
||||
// 自动赋值分享链接
|
||||
this.showListLink = `${this.baseUrl}/showList?url=${encodeURIComponent(this.link)}`
|
||||
|
||||
this.$message.success(`目录解析成功!共找到 ${this.directoryData.length} 个文件/文件夹`)
|
||||
} catch (error) {
|
||||
@@ -1412,7 +1464,7 @@ export default {
|
||||
// 文件点击处理
|
||||
handleFileClick(file) {
|
||||
if (file.parserUrl) {
|
||||
window.open(file.parserUrl, '_blank', 'noopener,noreferrer')
|
||||
openNoReferrer(file.parserUrl)
|
||||
} else {
|
||||
this.$message.warning('该文件暂无下载链接')
|
||||
}
|
||||
@@ -1421,13 +1473,14 @@ export default {
|
||||
// 获取剪切板内容
|
||||
async getPaste(isManual = false) {
|
||||
try {
|
||||
const text = await navigator.clipboard.readText()
|
||||
const text = (await navigator.clipboard.readText() || '').trim()
|
||||
|
||||
const shortInfo = this.expandShortFormat(text)
|
||||
if (shortInfo) {
|
||||
if (shortInfo.link !== this.link || shortInfo.pwd !== this.password) {
|
||||
this.password = shortInfo.pwd
|
||||
this.link = shortInfo.link
|
||||
this.updateDirectLink()
|
||||
if (!this.hasClipboardSuccessTip) {
|
||||
this.$message.success(`自动识别分享成功, 网盘类型: ${shortInfo.name}; 分享URL ${this.link}; 分享密码: ${this.password || '空'}`)
|
||||
this.hasClipboardSuccessTip = true
|
||||
@@ -1446,6 +1499,8 @@ export default {
|
||||
if (linkInfo.link !== this.link || pwd !== this.password) {
|
||||
this.password = pwd
|
||||
this.link = linkInfo.link
|
||||
// 更新智能直链(包含认证参数)
|
||||
this.updateDirectLink()
|
||||
// 聚焦期间只提示一次
|
||||
if (!this.hasClipboardSuccessTip) {
|
||||
this.$message.success(`自动识别分享成功, 网盘类型: ${linkInfo.name}; 分享URL ${this.link}; 分享密码: ${this.password || '空'}`)
|
||||
@@ -1846,7 +1901,7 @@ export default {
|
||||
}
|
||||
},
|
||||
openUrl(url) {
|
||||
if (url) window.open(url, '_blank', 'noopener,noreferrer')
|
||||
openNoReferrer(url)
|
||||
},
|
||||
async loadDirectoryParseSupportedPans() {
|
||||
try {
|
||||
@@ -2120,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;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
<el-icon :size="50"><WarningFilled /></el-icon>
|
||||
</div>
|
||||
<div class="auth-title">演练场功能已禁用</div>
|
||||
<div class="auth-subtitle">请联系管理员启用演练场功能</div>
|
||||
<div class="auth-subtitle">请联系管理员检查演练场开关与服务日志。私有模式需要先设置实例专属的访问密码。</div>
|
||||
<el-button type="primary" size="large" @click="goHome" class="auth-button">
|
||||
<span>返回首页</span>
|
||||
</el-button>
|
||||
|
||||
@@ -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 }}
|
||||
|
||||
@@ -8,10 +8,12 @@
|
||||
</div>
|
||||
<div style="text-align:right;margin-bottom:12px;">
|
||||
<DarkMode @theme-change="toggleTheme" style="float: left;"/>
|
||||
<el-radio-group v-model="viewMode" size="small" style="margin-left:20px;">
|
||||
<el-radio-button label="pane">窗格</el-radio-button>
|
||||
<el-radio-button label="tree">目录树</el-radio-button>
|
||||
</el-radio-group>
|
||||
<ViewModeSwitch
|
||||
v-model="viewMode"
|
||||
pane-label="窗格"
|
||||
tree-label="目录树"
|
||||
style="margin-left:20px;"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="loading" style="text-align:center;margin-top:40px;">加载中...</div>
|
||||
<div v-else-if="error" style="color:red;text-align:center;margin-top:40px;">{{ error }}</div>
|
||||
@@ -29,11 +31,12 @@
|
||||
<script>
|
||||
import axios from 'axios'
|
||||
import DirectoryTree from '@/components/DirectoryTree'
|
||||
import ViewModeSwitch from '@/components/ViewModeSwitch'
|
||||
import DarkMode from '@/components/DarkMode'
|
||||
|
||||
export default {
|
||||
name: 'ShowList',
|
||||
components: { DirectoryTree, DarkMode },
|
||||
components: { DirectoryTree, ViewModeSwitch, DarkMode },
|
||||
data() {
|
||||
return {
|
||||
loading: true,
|
||||
|
||||
@@ -598,6 +598,8 @@ GET /v2/redirectUrl/pan/eyJmaWxlSWQiOiIxMjM0NTYifQ==
|
||||
- 小飞机盘 (fj)
|
||||
- 360亿方云 (fc)
|
||||
- 联想乐云 (le)
|
||||
- 夸克网盘 (qk)
|
||||
- UC网盘 (uc)
|
||||
- 文叔叔 (ws)
|
||||
- Cloudreve (ce)
|
||||
- 等等...
|
||||
|
||||
@@ -6,15 +6,16 @@ JS解析器演练场现在支持密码保护功能,可以通过配置文件控
|
||||
|
||||
## 配置说明
|
||||
|
||||
在 `web-service/src/main/resources/app-dev.yml` 文件中添加以下配置:
|
||||
编辑当前启用的配置文件。发行包默认使用 `resources/app-dev.yml`。
|
||||
|
||||
```yaml
|
||||
# JS演练场配置
|
||||
playground:
|
||||
enabled: false
|
||||
# 公开模式,默认false需要密码访问,设为true则无需密码
|
||||
public: false
|
||||
# 访问密码,建议修改默认密码!
|
||||
password: 'nfd_playground_2024'
|
||||
# 私有模式启用前须设置实例专属密码
|
||||
password: ''
|
||||
```
|
||||
|
||||
### 配置项说明
|
||||
@@ -24,8 +25,7 @@ playground:
|
||||
- `true`: 公开访问,无需密码
|
||||
|
||||
- `password`: 字符串,访问密码
|
||||
- 默认密码:`nfd_playground_2024`
|
||||
- **强烈建议在生产环境中修改为自定义密码!**
|
||||
- 无默认值。私有模式缺少密码、密码为空白或沿用旧版公开密码时,演练场保持关闭。
|
||||
|
||||
## 功能特点
|
||||
|
||||
@@ -64,24 +64,14 @@ playground:
|
||||
|
||||
⚠️ **重要安全提示:**
|
||||
|
||||
1. **修改默认密码**:在生产环境中,务必修改 `playground.password` 为自定义的强密码
|
||||
1. **设置专属密码**:启用私有模式前,请设置 `playground.password` 为自定义的强密码
|
||||
2. **使用密码保护**:建议保持 `public: false`,避免未授权访问
|
||||
3. **定期更换密码**:定期更换访问密码以提高安全性
|
||||
4. **配置文件保护**:确保配置文件的访问权限受到保护
|
||||
|
||||
## 系统启动提示
|
||||
|
||||
当系统启动时,会在日志中显示当前配置:
|
||||
|
||||
```
|
||||
INFO - Playground配置已加载: public=false, password=已设置
|
||||
```
|
||||
|
||||
如果使用默认密码,会显示警告:
|
||||
|
||||
```
|
||||
WARN - ⚠️ 警告:您正在使用默认密码,建议修改配置文件中的 playground.password 以确保安全!
|
||||
```
|
||||
配置文件及启用开关 `NFD_PLAYGROUND_ENABLED` 生效后,服务会检查私有模式密码。若检查失败,日志会提示配置 `playground.password` 并重启服务,其他功能继续启动。显式选择 `public: true` 会允许免密码访问管理接口。
|
||||
|
||||
## API 端点
|
||||
|
||||
@@ -145,9 +135,9 @@ A: 修改配置文件中的 `playground.password` 为新密码,然后重启服
|
||||
|
||||
A: 当前版本密码以明文形式存储在配置文件中,请确保配置文件的访问权限受到保护
|
||||
|
||||
### Q: Session 有效期多久?
|
||||
### 登录令牌有效期多久?
|
||||
|
||||
A: Session 由 Vert.x 管理,默认在浏览器会话期间有效,关闭浏览器后失效
|
||||
私有模式的令牌自签发起最多有效 24 小时。服务重启或重新加载演练场配置会使已签发的令牌失效。
|
||||
|
||||
## 后续版本计划
|
||||
|
||||
@@ -156,7 +146,6 @@ A: Session 由 Vert.x 管理,默认在浏览器会话期间有效,关闭浏
|
||||
- [ ] 支持环境变量配置密码
|
||||
- [ ] 支持加密存储密码
|
||||
- [ ] 支持多用户账户系统
|
||||
- [ ] 支持 Token 认证方式
|
||||
- [ ] 支持 Session 超时配置
|
||||
|
||||
## 相关文档
|
||||
|
||||
+12
-1
@@ -30,6 +30,16 @@
|
||||
<groupId>cn.qaiu</groupId>
|
||||
<artifactId>parser</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
@@ -81,7 +91,8 @@
|
||||
${project.basedir}/src/main/generated
|
||||
</generatedSourcesDirectory>
|
||||
<compilerArgs>
|
||||
<arg>-AoutputDirectory=${project.basedir}/src/main -Xlint:unchecked</arg>
|
||||
<arg>-AoutputDirectory=${project.basedir}/src/main</arg>
|
||||
<arg>-Xlint:unchecked</arg>
|
||||
</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
@@ -2,6 +2,7 @@ package cn.qaiu.lz.common.util;
|
||||
|
||||
import cn.qaiu.lz.web.model.AuthParam;
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import cn.qaiu.util.Base64Decoder;
|
||||
import cn.qaiu.vx.core.util.SharedDataUtil;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -9,7 +10,6 @@ import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* 认证参数编解码工具类
|
||||
@@ -88,7 +88,7 @@ public class AuthParamCodec {
|
||||
log.debug("认证参数规范化结果: {}", normalized);
|
||||
|
||||
// Step 2: Base64解码
|
||||
byte[] base64Decoded = Base64.getDecoder().decode(normalized);
|
||||
byte[] base64Decoded = Base64Decoder.decode(normalized);
|
||||
log.debug("Base64解码成功,长度: {}", base64Decoded.length);
|
||||
|
||||
// Step 3: AES解密
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package cn.qaiu.lz.common.util;
|
||||
|
||||
import cn.qaiu.util.Base64Encoder;
|
||||
import cn.qaiu.util.Base64Decoder;
|
||||
import cn.qaiu.lz.web.model.SysUser;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
|
||||
@@ -12,7 +14,6 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
@@ -48,8 +49,8 @@ public class JwtUtil {
|
||||
.put("iss", "netdisk-fast-download");
|
||||
|
||||
// Base64 encode header and payload
|
||||
String encodedHeader = Base64.getUrlEncoder().withoutPadding().encodeToString(header.encode().getBytes(StandardCharsets.UTF_8));
|
||||
String encodedPayload = Base64.getUrlEncoder().withoutPadding().encodeToString(payload.encode().getBytes(StandardCharsets.UTF_8));
|
||||
String encodedHeader = Base64Encoder.encodeUrlWithoutPadding(header.encode().getBytes(StandardCharsets.UTF_8));
|
||||
String encodedPayload = Base64Encoder.encodeUrlWithoutPadding(payload.encode().getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// Create signature
|
||||
String signature = hmacSha256(encodedHeader + "." + encodedPayload, SECRET_KEY);
|
||||
@@ -71,7 +72,7 @@ public class JwtUtil {
|
||||
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM);
|
||||
sha256Hmac.init(secretKey);
|
||||
byte[] signedBytes = sha256Hmac.doFinal(data.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(signedBytes);
|
||||
return Base64Encoder.encodeUrlWithoutPadding(signedBytes);
|
||||
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
|
||||
throw new RuntimeException("Error creating HMAC SHA256 signature", e);
|
||||
}
|
||||
@@ -102,7 +103,7 @@ public class JwtUtil {
|
||||
}
|
||||
|
||||
// 验证过期时间
|
||||
String payload = new String(Base64.getUrlDecoder().decode(encodedPayload), StandardCharsets.UTF_8);
|
||||
String payload = new String(Base64Decoder.decodeUrl(encodedPayload), StandardCharsets.UTF_8);
|
||||
JsonObject payloadJson = new JsonObject(payload);
|
||||
long expTime = payloadJson.getLong("exp", 0L);
|
||||
|
||||
@@ -125,7 +126,7 @@ public class JwtUtil {
|
||||
}
|
||||
|
||||
// Base64解码
|
||||
String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
|
||||
String payload = new String(Base64Decoder.decodeUrl(parts[1]), StandardCharsets.UTF_8);
|
||||
JsonObject jsonObject = new JsonObject(payload);
|
||||
return jsonObject.getString("id");
|
||||
}
|
||||
@@ -143,7 +144,7 @@ public class JwtUtil {
|
||||
}
|
||||
|
||||
// Base64解码
|
||||
String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
|
||||
String payload = new String(Base64Decoder.decodeUrl(parts[1]), StandardCharsets.UTF_8);
|
||||
JsonObject jsonObject = new JsonObject(payload);
|
||||
return jsonObject.getString("username");
|
||||
}
|
||||
@@ -161,7 +162,7 @@ public class JwtUtil {
|
||||
}
|
||||
|
||||
// Base64解码
|
||||
String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
|
||||
String payload = new String(Base64Decoder.decodeUrl(parts[1]), StandardCharsets.UTF_8);
|
||||
JsonObject jsonObject = new JsonObject(payload);
|
||||
return jsonObject.getString("role");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package cn.qaiu.lz.common.util;
|
||||
|
||||
import cn.qaiu.util.Base64Encoder;
|
||||
import cn.qaiu.util.Base64Decoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
@@ -39,8 +41,8 @@ public class PasswordUtil {
|
||||
byte[] hashedPassword = md.digest(plainPassword.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// 将盐和哈希值编码为Base64并拼接
|
||||
String saltBase64 = Base64.getEncoder().encodeToString(salt);
|
||||
String hashBase64 = Base64.getEncoder().encodeToString(hashedPassword);
|
||||
String saltBase64 = Base64Encoder.encode(salt);
|
||||
String hashBase64 = Base64Encoder.encode(hashedPassword);
|
||||
|
||||
// 返回格式:salt:hash
|
||||
return saltBase64 + DELIMITER + hashBase64;
|
||||
@@ -72,13 +74,13 @@ public class PasswordUtil {
|
||||
String hashBase64 = parts[1];
|
||||
|
||||
// 解码盐
|
||||
byte[] salt = Base64.getDecoder().decode(saltBase64);
|
||||
byte[] salt = Base64Decoder.decode(saltBase64);
|
||||
|
||||
// 使用相同的盐计算哈希值
|
||||
MessageDigest md = MessageDigest.getInstance(ALGORITHM);
|
||||
md.update(salt);
|
||||
byte[] calculatedHash = md.digest(plainPassword.getBytes(StandardCharsets.UTF_8));
|
||||
String calculatedHashBase64 = Base64.getEncoder().encodeToString(calculatedHash);
|
||||
String calculatedHashBase64 = Base64Encoder.encode(calculatedHash);
|
||||
|
||||
// 比较计算出的哈希值和存储的哈希值(使用常量时间比较防止时序攻击)
|
||||
return MessageDigest.isEqual(
|
||||
|
||||
@@ -26,7 +26,7 @@ public class PlaygroundConfig {
|
||||
/**
|
||||
* 单例实例
|
||||
*/
|
||||
private static PlaygroundConfig instance;
|
||||
private static volatile PlaygroundConfig instance = new PlaygroundConfig();
|
||||
|
||||
/**
|
||||
* 已颁发的认证Token及其创建时间
|
||||
@@ -47,9 +47,8 @@ public class PlaygroundConfig {
|
||||
|
||||
/**
|
||||
* 访问密码
|
||||
* 默认密码:nfd_playground_2024
|
||||
*/
|
||||
private String password = "nfd_playground_2024";
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* 私有构造函数
|
||||
@@ -117,13 +116,6 @@ public class PlaygroundConfig {
|
||||
* 获取单例实例
|
||||
*/
|
||||
public static PlaygroundConfig getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (PlaygroundConfig.class) {
|
||||
if (instance == null) {
|
||||
instance = new PlaygroundConfig();
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
@@ -131,23 +123,13 @@ public class PlaygroundConfig {
|
||||
* 从JsonObject加载配置
|
||||
*/
|
||||
public static void loadFromJson(JsonObject config) {
|
||||
PlaygroundConfig cfg = getInstance();
|
||||
if (config != null && config.containsKey("playground")) {
|
||||
JsonObject playgroundConfig = config.getJsonObject("playground");
|
||||
cfg.enabled = playgroundConfig.getBoolean("enabled", false);
|
||||
cfg.isPublic = playgroundConfig.getBoolean("public", false);
|
||||
cfg.password = playgroundConfig.getString("password", "nfd_playground_2024");
|
||||
|
||||
log.info("Playground配置已加载: enabled={}, public={}, password={}",
|
||||
cfg.enabled, cfg.isPublic, cfg.isPublic ? "N/A" : "已设置");
|
||||
|
||||
if (!cfg.enabled) {
|
||||
log.info("演练场功能已禁用");
|
||||
} else if (!cfg.isPublic && "nfd_playground_2024".equals(cfg.password)) {
|
||||
log.warn("⚠️ 警告:您正在使用默认密码,建议修改配置文件中的 playground.password 以确保安全!");
|
||||
PlaygroundConfig cfg = new PlaygroundConfig();
|
||||
if (config != null && config.getValue("playground") instanceof JsonObject playground) {
|
||||
cfg.enabled = playground.getBoolean("enabled", false);
|
||||
cfg.isPublic = playground.getBoolean("public", false);
|
||||
if (playground.getValue("password") instanceof String configuredPassword) {
|
||||
cfg.password = configuredPassword;
|
||||
}
|
||||
} else {
|
||||
log.info("未找到playground配置,使用默认值: enabled=false, public=false");
|
||||
}
|
||||
String enabledOverride = System.getProperty("NFD_PLAYGROUND_ENABLED");
|
||||
if (enabledOverride == null || enabledOverride.isBlank()) {
|
||||
@@ -155,7 +137,16 @@ public class PlaygroundConfig {
|
||||
}
|
||||
if (enabledOverride != null && !enabledOverride.isBlank()) {
|
||||
cfg.enabled = Boolean.parseBoolean(enabledOverride);
|
||||
log.info("Playground enabled 已被 NFD_PLAYGROUND_ENABLED 覆盖为 {}", cfg.enabled);
|
||||
}
|
||||
|
||||
// Validate after all overrides so enabling via the environment follows the same rules.
|
||||
if (cfg.enabled && !cfg.isPublic && (cfg.password == null || cfg.password.isBlank()
|
||||
|| "nfd_playground_2024".equals(cfg.password.strip()))) {
|
||||
cfg.enabled = false;
|
||||
log.warn("演练场已禁用:请在 app-dev.yml 中设置实例专属的 playground.password,替换空值或旧版默认密码,然后重启服务。");
|
||||
} else {
|
||||
log.info("演练场配置已加载:enabled={}, public={}", cfg.enabled, cfg.isPublic);
|
||||
}
|
||||
instance = cfg;
|
||||
}
|
||||
}
|
||||
@@ -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()) {
|
||||
@@ -463,11 +465,14 @@ public class ParserApi {
|
||||
// 获取版本号
|
||||
@RouteMapping("/build-version")
|
||||
public String getVersion() {
|
||||
return CommonUtil.getAppVersion()
|
||||
String version = CommonUtil.getAppVersion();
|
||||
if (version == null || version.isBlank()) {
|
||||
return "unknown";
|
||||
}
|
||||
return version
|
||||
.replace("-", "")
|
||||
.replace("Z", "")
|
||||
.replace("T", "_")
|
||||
.replace("-", "")
|
||||
.replace(":", "");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package cn.qaiu.lz.web.service.impl;
|
||||
|
||||
import cn.qaiu.util.Base64Encoder;
|
||||
import cn.qaiu.util.Base64Decoder;
|
||||
import cn.qaiu.db.pool.JDBCPoolInit;
|
||||
import cn.qaiu.lz.common.model.UserInfo;
|
||||
import cn.qaiu.lz.web.model.StatisticsInfo;
|
||||
@@ -21,7 +23,6 @@ import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@@ -457,9 +458,9 @@ public class DbServiceImpl implements DbService {
|
||||
long issuedAt = System.currentTimeMillis();
|
||||
String payload = accountId + ":" + issuedAt;
|
||||
String signature = hmacSha256(payload);
|
||||
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(payload.getBytes(StandardCharsets.UTF_8))
|
||||
String token = Base64Encoder.encodeUrlWithoutPadding(payload.getBytes(StandardCharsets.UTF_8))
|
||||
+ "."
|
||||
+ Base64.getUrlEncoder().withoutPadding().encodeToString(signature.getBytes(StandardCharsets.UTF_8));
|
||||
+ Base64Encoder.encodeUrlWithoutPadding(signature.getBytes(StandardCharsets.UTF_8));
|
||||
return Future.succeededFuture(token);
|
||||
} catch (Exception e) {
|
||||
return Future.failedFuture(e);
|
||||
@@ -526,7 +527,7 @@ public class DbServiceImpl implements DbService {
|
||||
|
||||
private boolean isLikelyEncrypted(String value) {
|
||||
try {
|
||||
byte[] decoded = Base64.getDecoder().decode(value);
|
||||
byte[] decoded = Base64Decoder.decode(value);
|
||||
return decoded.length > 16;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
@@ -538,8 +539,8 @@ public class DbServiceImpl implements DbService {
|
||||
throw new IllegalArgumentException("invalid donated account token");
|
||||
}
|
||||
String[] parts = token.split("\\.", 2);
|
||||
String payload = new String(Base64.getUrlDecoder().decode(parts[0]), StandardCharsets.UTF_8);
|
||||
String signature = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
|
||||
String payload = new String(Base64Decoder.decodeUrl(parts[0]), StandardCharsets.UTF_8);
|
||||
String signature = new String(Base64Decoder.decodeUrl(parts[1]), StandardCharsets.UTF_8);
|
||||
String expected = hmacSha256(payload);
|
||||
if (!expected.equals(signature)) {
|
||||
throw new IllegalArgumentException("donated account token signature invalid");
|
||||
@@ -562,7 +563,7 @@ public class DbServiceImpl implements DbService {
|
||||
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
|
||||
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_ALGORITHM));
|
||||
byte[] digest = mac.doFinal(payload.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(digest);
|
||||
return Base64Encoder.encode(digest);
|
||||
}
|
||||
|
||||
private String getDonatedAccountFailureTokenSignKey() {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package cn.qaiu.lz.web.util;
|
||||
|
||||
import cn.qaiu.util.Base64Encoder;
|
||||
import cn.qaiu.util.Base64Decoder;
|
||||
import cn.qaiu.vx.core.util.ConfigUtil;
|
||||
import cn.qaiu.vx.core.util.VertxHolder;
|
||||
import io.vertx.core.Future;
|
||||
@@ -13,7 +15,6 @@ import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
public class CryptoUtil {
|
||||
|
||||
@@ -68,7 +69,7 @@ public class CryptoUtil {
|
||||
byteBuffer.put(iv);
|
||||
byteBuffer.put(cipherText);
|
||||
|
||||
return Future.succeededFuture(Base64.getEncoder().encodeToString(byteBuffer.array()));
|
||||
return Future.succeededFuture(Base64Encoder.encode(byteBuffer.array()));
|
||||
} catch (Exception e) {
|
||||
return Future.failedFuture(new CryptoException("Encryption failed", e));
|
||||
}
|
||||
@@ -81,7 +82,7 @@ public class CryptoUtil {
|
||||
}
|
||||
return secretKeyFuture.compose(secretKey -> {
|
||||
try {
|
||||
byte[] decodedBytes = Base64.getDecoder().decode(strToDecrypt);
|
||||
byte[] decodedBytes = Base64Decoder.decode(strToDecrypt);
|
||||
|
||||
// Extract IV from the beginning of the decoded bytes
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(decodedBytes);
|
||||
|
||||
@@ -20,8 +20,8 @@ playground:
|
||||
enabled: false
|
||||
# 公开模式,默认false需要密码访问,设为true则无需密码
|
||||
public: false
|
||||
# 访问密码,建议修改默认密码!
|
||||
password: 'nfd_playground_2024'
|
||||
# 私有模式启用前请填写实例专属密码;留空或沿用旧版默认密码将禁用演练场。
|
||||
password: ''
|
||||
|
||||
# vertx核心线程配置(一般无需改的), 为0表示eventLoopPoolSize将会采用默认配置(CPU核心*2) workerPoolSize将会采用默认20
|
||||
vertx:
|
||||
@@ -134,7 +134,14 @@ proxy:
|
||||
|
||||
### 解析认证相关
|
||||
auths:
|
||||
# 123网盘:配置用户名密码
|
||||
# 夸克:小文件可免登录。大文件(访客 23018)再填本机 Cookie。空值等于没配。
|
||||
# 公共解析站没有共用夸克账号。
|
||||
# qk:
|
||||
# cookie:
|
||||
# 123:公共云解析不能共用账号。优先填 authorization(浏览器 authorToken / sso-token,不要带 Bearer)。
|
||||
# 账号密码触发验证码时会失败并提示改用 Authorization,本项目不处理验证码。
|
||||
# 5112 / 请登录后下载 / 您需要注册登录或付费后下载 是上游要求登录。
|
||||
ye:
|
||||
username:
|
||||
password:
|
||||
# authorization:
|
||||
@@ -0,0 +1,40 @@
|
||||
package cn.qaiu.lz.common.util;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
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 Base64CompatibilityTest {
|
||||
@Test
|
||||
public void acceptsStoredPasswordHash() {
|
||||
String password = "密码-test";
|
||||
String hash = PasswordUtil.hashPassword(password);
|
||||
assertTrue(PasswordUtil.checkPassword(password, hash));
|
||||
assertFalse(PasswordUtil.checkPassword("wrong", hash));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptsJwtWithUnpaddedUrlSafePayload() {
|
||||
String json = "{\"username\":\"下载用户\"}";
|
||||
String payload = Base64.getUrlEncoder().withoutPadding().encodeToString(json.getBytes(StandardCharsets.UTF_8));
|
||||
assertEquals("下载用户", JwtUtil.getUsernameFromToken("header." + payload + ".signature"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptsLegacyEncodedAuth() throws Exception {
|
||||
String key = "0123456789abcdef";
|
||||
String json = "{\"authType\":\"cookie\",\"token\":\"compatibility-test\"}";
|
||||
String base64 = cn.qaiu.util.AESUtils.encryptBase64ByAES(json, key);
|
||||
String urlEncoded = URLEncoder.encode(base64, StandardCharsets.UTF_8);
|
||||
assertEquals("cookie", AuthParamCodec.decode(urlEncoded, key).getAuthType());
|
||||
assertEquals("cookie", AuthParamCodec.decode(base64.replace('+', ' '), key).getAuthType());
|
||||
assertNull(AuthParamCodec.decode(base64 + "!", key));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package cn.qaiu.lz.web.config;
|
||||
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PlaygroundPasswordTest {
|
||||
@Test
|
||||
public void validatesPrivateModeAfterTheEnableOverride() {
|
||||
String key = "NFD_PLAYGROUND_ENABLED";
|
||||
String previous = System.getProperty(key);
|
||||
try {
|
||||
System.setProperty(key, "true");
|
||||
JsonObject playground = new JsonObject().put("enabled", false);
|
||||
JsonObject config = new JsonObject().put("playground", playground);
|
||||
for (String password : new String[]{null, "", " ", "nfd_playground_2024"}) {
|
||||
playground.put("password", password);
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
}
|
||||
playground.put("password", "instance-specific-test-value");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertTrue(PlaygroundConfig.getInstance().isEnabled());
|
||||
assertEquals(playground.getString("password"), PlaygroundConfig.getInstance().getPassword());
|
||||
String token = PlaygroundConfig.getInstance().generateToken();
|
||||
|
||||
PlaygroundConfig.loadFromJson(new JsonObject());
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
assertFalse(PlaygroundConfig.getInstance().validateToken(token));
|
||||
|
||||
playground.put("public", true).remove("password");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertTrue(PlaygroundConfig.getInstance().isEnabled());
|
||||
System.setProperty(key, "false");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
} finally {
|
||||
if (previous == null) System.clearProperty(key);
|
||||
else System.setProperty(key, previous);
|
||||
PlaygroundConfig.loadFromJson(new JsonObject());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user