mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-12-04 02:23:59 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ed0ec4036 | ||
|
|
62fa23542d | ||
|
|
0d133ee437 |
No files matched your search
@@ -1,8 +0,0 @@
|
|||||||
blank_issues_enabled: false
|
|
||||||
contact_links:
|
|
||||||
- name: 使用文档
|
|
||||||
url: https://nfd-parser.github.io/
|
|
||||||
about: 部署、接口和配置说明
|
|
||||||
- name: 已发布版本
|
|
||||||
url: https://github.com/qaiu/netdisk-fast-download/releases
|
|
||||||
about: 先看最新版本和更新说明,再反馈旧版本里已经修过的问题
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
name: 功能建议
|
|
||||||
description: 新功能或改进建议。不需要填写报错、日志或分享链接。
|
|
||||||
title: "[建议] "
|
|
||||||
labels:
|
|
||||||
- enhancement
|
|
||||||
body:
|
|
||||||
- type: markdown
|
|
||||||
attributes:
|
|
||||||
value: |
|
|
||||||
这里只讨论建议。解析失败或程序跑不起来,请分别使用对应模板。
|
|
||||||
|
|
||||||
如果要举例,只用可公开的测试分享,不要附带账号、令牌或私人文件。
|
|
||||||
- type: checkboxes
|
|
||||||
id: checks
|
|
||||||
attributes:
|
|
||||||
label: 提交前
|
|
||||||
options:
|
|
||||||
- label: 我查过现有 issue,没有找到相同建议
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: problem
|
|
||||||
attributes:
|
|
||||||
label: 想解决的问题
|
|
||||||
placeholder: 现在做什么不方便
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: proposal
|
|
||||||
attributes:
|
|
||||||
label: 建议怎么做
|
|
||||||
placeholder: 希望增加或改变什么
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: alternatives
|
|
||||||
attributes:
|
|
||||||
label: 还可以怎么做
|
|
||||||
description: 没有就留空。
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
name: 解析失败
|
|
||||||
description: 某个分享链接解析失败、列目录失败,或直链无法下载
|
|
||||||
title: "[解析失败] "
|
|
||||||
labels:
|
|
||||||
- bug
|
|
||||||
body:
|
|
||||||
- type: markdown
|
|
||||||
attributes:
|
|
||||||
value: |
|
|
||||||
只提交可以公开的测试分享。私人文件、含个人信息的分享不要发到这里。
|
|
||||||
|
|
||||||
不要粘贴 Cookie、Authorization、refresh_token、access token、网盘账号密码、后台密码,或未打码的配置。提取码、访问密码和账号密码不是一回事:下面只接受分享本身的提取码或访问密码。
|
|
||||||
- type: checkboxes
|
|
||||||
id: checks
|
|
||||||
attributes:
|
|
||||||
label: 提交前
|
|
||||||
options:
|
|
||||||
- label: 我查过现有 issue,没有找到相同问题
|
|
||||||
required: true
|
|
||||||
- label: 我看过当前版本和更新说明,这不是已经修好的问题
|
|
||||||
required: true
|
|
||||||
- label: 分享可以公开,且没有附带令牌、Cookie、账号密码或未脱敏配置
|
|
||||||
required: true
|
|
||||||
- type: input
|
|
||||||
id: version
|
|
||||||
attributes:
|
|
||||||
label: 版本号
|
|
||||||
description: 页面上的版本,或发布包名里的版本,例如 0.4.15。
|
|
||||||
placeholder: "0.4.15"
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: pan
|
|
||||||
attributes:
|
|
||||||
label: 网盘类型
|
|
||||||
options:
|
|
||||||
- 蓝奏云
|
|
||||||
- 蓝奏云优享
|
|
||||||
- 城通网盘
|
|
||||||
- 永硕 E 盘
|
|
||||||
- 123云盘
|
|
||||||
- 夸克网盘
|
|
||||||
- UC网盘
|
|
||||||
- 小飞机盘
|
|
||||||
- 其他(在现象里补充名称)
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: deploy
|
|
||||||
attributes:
|
|
||||||
label: 部署方式
|
|
||||||
options:
|
|
||||||
- 本机发布包
|
|
||||||
- Docker
|
|
||||||
- 自行编译
|
|
||||||
- 公共站点
|
|
||||||
- 其他
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: kind
|
|
||||||
attributes:
|
|
||||||
label: 分享内容
|
|
||||||
options:
|
|
||||||
- 单文件
|
|
||||||
- 目录
|
|
||||||
- 不确定
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: access
|
|
||||||
attributes:
|
|
||||||
label: 分享是否带密码
|
|
||||||
description: 提取码是分享链接自带的短码。不要填写网盘登录密码。
|
|
||||||
options:
|
|
||||||
- 无密码
|
|
||||||
- 只有提取码
|
|
||||||
- 有访问密码
|
|
||||||
- 不确定
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: input
|
|
||||||
id: passcode
|
|
||||||
attributes:
|
|
||||||
label: 提取码或访问密码
|
|
||||||
description: 没有就留空。这里不是账号密码。
|
|
||||||
placeholder: "例如 abcd"
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
- type: input
|
|
||||||
id: share-url
|
|
||||||
attributes:
|
|
||||||
label: 可公开的完整分享链接
|
|
||||||
description: 用专门准备的测试分享。没有可公开链接时留空,并在下一项说明原因。
|
|
||||||
placeholder: "https://"
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
- type: textarea
|
|
||||||
id: no-share-reason
|
|
||||||
attributes:
|
|
||||||
label: 不能提供测试分享的原因
|
|
||||||
description: 已经填写链接就留空。
|
|
||||||
placeholder: 例如分享含私人文件,只能描述现象
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
- type: checkboxes
|
|
||||||
id: share-or-reason
|
|
||||||
attributes:
|
|
||||||
label: 链接
|
|
||||||
options:
|
|
||||||
- label: 我填写了可公开的完整分享链接,或已经说明不能提供的原因
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: official
|
|
||||||
attributes:
|
|
||||||
label: 官方网页是否可用
|
|
||||||
options:
|
|
||||||
- 可以打开,并且能下载
|
|
||||||
- 可以打开,但不能下载
|
|
||||||
- 打不开或提示失效
|
|
||||||
- 还没在官方网页试过
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: expected
|
|
||||||
attributes:
|
|
||||||
label: 预期结果
|
|
||||||
placeholder: 应解析出直链,或列出目录中的文件
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: actual
|
|
||||||
attributes:
|
|
||||||
label: 实际结果
|
|
||||||
description: 写页面或接口返回的原文。不要贴令牌。
|
|
||||||
placeholder: 例如提示分享不存在,或直链返回 403
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: steps
|
|
||||||
attributes:
|
|
||||||
label: 复现步骤
|
|
||||||
placeholder: |
|
|
||||||
1. 使用上述版本和部署方式
|
|
||||||
2. 解析这个分享
|
|
||||||
3. 看到上述结果
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: logs
|
|
||||||
attributes:
|
|
||||||
label: 脱敏后的报错日志
|
|
||||||
description: 没有日志就写「无」。删除 Cookie、Authorization、token、密码和未脱敏配置后再粘贴。
|
|
||||||
render: shell
|
|
||||||
placeholder: 无
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
name: 部署或运行问题
|
|
||||||
description: 程序无法启动、页面打不开、配置或运行报错。不是某一个分享解析失败。
|
|
||||||
title: "[运行问题] "
|
|
||||||
labels:
|
|
||||||
- bug
|
|
||||||
body:
|
|
||||||
- type: markdown
|
|
||||||
attributes:
|
|
||||||
value: |
|
|
||||||
单个分享解析失败请改用「解析失败」。
|
|
||||||
|
|
||||||
不要粘贴 Cookie、Authorization、refresh_token、access token、网盘或后台密码、个人信息,以及未打码的配置。
|
|
||||||
- type: checkboxes
|
|
||||||
id: checks
|
|
||||||
attributes:
|
|
||||||
label: 提交前
|
|
||||||
options:
|
|
||||||
- label: 我查过现有 issue,没有找到相同问题
|
|
||||||
required: true
|
|
||||||
- label: 我看过当前版本和更新说明
|
|
||||||
required: true
|
|
||||||
- label: 日志和配置已经去掉令牌、密码和个人信息
|
|
||||||
required: true
|
|
||||||
- type: input
|
|
||||||
id: version
|
|
||||||
attributes:
|
|
||||||
label: 版本号
|
|
||||||
description: 例如 0.4.15。不确定就写获取方式。
|
|
||||||
placeholder: "0.4.15"
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: dropdown
|
|
||||||
id: deploy
|
|
||||||
attributes:
|
|
||||||
label: 部署方式
|
|
||||||
options:
|
|
||||||
- 本机发布包(Linux)
|
|
||||||
- 本机发布包(Windows)
|
|
||||||
- Docker
|
|
||||||
- 自行编译
|
|
||||||
- 其他
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: input
|
|
||||||
id: environment
|
|
||||||
attributes:
|
|
||||||
label: 系统环境
|
|
||||||
description: 操作系统、架构,以及是否用了代理。没有就写「未记录」。
|
|
||||||
placeholder: "例如 Ubuntu 22.04 x86_64"
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
- type: textarea
|
|
||||||
id: expected
|
|
||||||
attributes:
|
|
||||||
label: 预期结果
|
|
||||||
placeholder: 服务应正常启动,页面可以打开
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: actual
|
|
||||||
attributes:
|
|
||||||
label: 实际结果
|
|
||||||
placeholder: 启动后立即退出,或页面无法访问
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: steps
|
|
||||||
attributes:
|
|
||||||
label: 复现步骤
|
|
||||||
placeholder: |
|
|
||||||
1. 下载并解压对应版本
|
|
||||||
2. 按文档启动
|
|
||||||
3. 看到上述结果
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: logs
|
|
||||||
attributes:
|
|
||||||
label: 脱敏后的报错日志
|
|
||||||
description: 没有日志就写「无」。不要包含令牌、密码或完整私有配置。
|
|
||||||
render: shell
|
|
||||||
placeholder: 无
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
## v0.4.15
|
|
||||||
|
|
||||||
- 浏览器与服务端以相同的 UTF-8 密钥字节处理临时认证,兼容 16、24 和 32 字节的密钥。
|
|
||||||
- 临时认证不再使用发行包里的公共密钥。未手动配置的服务实例每次启动生成随机密钥,只记录来源和指纹。保留旧发行包配置的实例也会自动迁移。
|
|
||||||
- 捐赠池默认关闭。显式启用后,受支持的网盘使用服务端选号,不再向前端提供捐赠账号。已保存的捐赠记录不会删除。
|
|
||||||
- 清理网页和文档中的公共密钥。需要网页个人认证、外部客户端或多实例共享密钥的自建站,须显式配置和安全分发 `server.authEncryptKey`。
|
|
||||||
|
|
||||||
### 升级提醒
|
|
||||||
|
|
||||||
旧公共密钥生成的 `auth` 参数不再兼容。升级后请核对部署配置,并视部署情况清理过往解析缓存和轮换捐赠凭据。
|
|
||||||
@@ -9,9 +9,8 @@ on:
|
|||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- 'v*'
|
- 'v*'
|
||||||
# '*' 不匹配含 / 的分支名(如 cursor/xxx),会让功能分支推送也发布 :latest 镜像
|
|
||||||
branches-ignore:
|
branches-ignore:
|
||||||
- '**'
|
- '*'
|
||||||
paths-ignore:
|
paths-ignore:
|
||||||
- 'bin/**'
|
- 'bin/**'
|
||||||
- '.github/**'
|
- '.github/**'
|
||||||
@@ -303,6 +302,5 @@ jobs:
|
|||||||
netdisk-fast-download-linux-amd64.zip
|
netdisk-fast-download-linux-amd64.zip
|
||||||
netdisk-fast-download-windows-amd64.zip
|
netdisk-fast-download-windows-amd64.zip
|
||||||
tag_name: ${{ github.ref_name }}
|
tag_name: ${{ github.ref_name }}
|
||||||
body_path: .github/release-notes.md
|
|
||||||
generate_release_notes: true
|
generate_release_notes: true
|
||||||
fail_on_unmatched_files: true
|
fail_on_unmatched_files: true
|
||||||
@@ -1,8 +1,4 @@
|
|||||||
# 一款网盘分享链接云解析快速下载服务
|
# 一款网盘分享链接云解析快速下载服务
|
||||||
|
|
||||||
> [!TIP]
|
|
||||||
> 如果在线解析失败,可以试试 [NFD Client](https://github.com/qaiu/nfd-client-parser),在本机解析网盘分享链接。[下载安装包](https://github.com/qaiu/nfd-client-parser/releases/latest)
|
|
||||||
|
|
||||||
QQ交流群:1017480890
|
QQ交流群:1017480890
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/qaiu/netdisk-fast-download/actions/workflows/maven.yml"><img src="https://img.shields.io/github/actions/workflow/status/qaiu/netdisk-fast-download/build.yml?branch=main&style=flat"></a>
|
<a href="https://github.com/qaiu/netdisk-fast-download/actions/workflows/maven.yml"><img src="https://img.shields.io/github/actions/workflow/status/qaiu/netdisk-fast-download/build.yml?branch=main&style=flat"></a>
|
||||||
@@ -68,7 +64,7 @@ wget -O v01 "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%
|
|||||||
|
|
||||||
**注意⚠️小飞机解析有IP限制,多数云服务商的大陆IP会被拦截(可以自行配置代理),和本程序无关**
|
**注意⚠️小飞机解析有IP限制,多数云服务商的大陆IP会被拦截(可以自行配置代理),和本程序无关**
|
||||||
**注意⚠️收到很多用户反馈,小飞机近期封号频繁,请尽可能选择其他网盘分享**
|
**注意⚠️收到很多用户反馈,小飞机近期封号频繁,请尽可能选择其他网盘分享**
|
||||||
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提 issues,请先检查分享是否有效。**反馈时使用 [问题模板](https://github.com/qaiu/netdisk-fast-download/issues/new/choose),只提供可公开的测试分享,不要粘贴 Cookie、令牌或账号密码。
|
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提issues,请先检查分享是否有效。**
|
||||||
|
|
||||||
## 网盘支持情况:
|
## 网盘支持情况:
|
||||||
> 20230824 123云盘解析大文件(>100MB)失效,需要登录
|
> 20230824 123云盘解析大文件(>100MB)失效,需要登录
|
||||||
@@ -163,13 +159,14 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
|
|||||||
- `your_host` 替换为您的域名或 IP
|
- `your_host` 替换为您的域名或 IP
|
||||||
|
|
||||||
### 认证参数(v0.2.1+)
|
### 认证参数(v0.2.1+)
|
||||||
|
[可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
|
||||||
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。可通过 `auth` 参数传递认证信息:
|
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。可通过 `auth` 参数传递认证信息:
|
||||||
|
|
||||||
**参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码
|
**参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码
|
||||||
|
|
||||||
**加密方式**:
|
**加密方式**:
|
||||||
- 算法:AES/ECB/PKCS5Padding
|
- 算法:AES/ECB/PKCS5Padding
|
||||||
- 密钥:由自建服务显式配置并通过安全渠道交给可信客户端(无公共默认值)
|
- 密钥:`nfd_auth_key2026`(16字节)
|
||||||
- 流程:JSON → AES加密 → Base64 → URL编码
|
- 流程:JSON → AES加密 → Base64 → URL编码
|
||||||
|
|
||||||
**JSON 结构**:
|
**JSON 结构**:
|
||||||
@@ -198,20 +195,14 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
|
|||||||
GET /parser?url={分享链接}&pwd={密码}&auth={加密后的认证参数}
|
GET /parser?url={分享链接}&pwd={密码}&auth={加密后的认证参数}
|
||||||
```
|
```
|
||||||
|
|
||||||
> 💡 提示:自建站的可信客户端可在网页中填写其显式配置的服务认证密钥;网页不会获取或保存服务端密钥。
|
> 💡 提示:Web 界面已内置认证配置功能,可自动处理加密过程,无需手动构造参数。
|
||||||
> 不要在不受信任的站点输入服务密钥或网盘凭据。
|
> [可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
|
||||||
|
|
||||||
#### 升级与捐赠开关
|
|
||||||
|
|
||||||
- 没有手动配置密钥(包括升级后仍保留旧发布包默认配置)的实例,在每次启动时自动生成进程随机密钥。启动日志只记录来源和指纹,不输出原文。重启后,之前用进程密钥生成的认证参数会失效。
|
|
||||||
- 要让可信浏览器、外部工具或多实例使用同一密钥,显式配置 `server.authEncryptKey`,通过安全渠道分发;不要使用旧发布包默认值。
|
|
||||||
- 捐赠默认关闭。仅设置 `server.enableDonatedAccounts: true` 且启用数据库后,才允许提交和服务端选用捐赠账号。关闭不删除已有记录。旧的浏览器取号接口已移除。仅 123 云盘、小飞机和蓝奏优享可使用服务端捐赠池;需要在下载响应携带账号请求头的网盘暂不开放。
|
|
||||||
|
|
||||||
#### 密钥作用说明
|
#### 密钥作用说明
|
||||||
|
|
||||||
- `server.authEncryptKey`
|
- `server.authEncryptKey`
|
||||||
- 作用:用于 `auth` 参数的 AES 加解密
|
- 作用:用于 `auth` 参数的 AES 加解密
|
||||||
- 要求:16、24 或 32 个 UTF-8 字节
|
- 要求:16位(AES-128)
|
||||||
|
|
||||||
- `server.donatedAccountFailureTokenSignKey`
|
- `server.donatedAccountFailureTokenSignKey`
|
||||||
- 作用:用于“捐赠账号失败计数 token”的 HMAC 签名/验签
|
- 作用:用于“捐赠账号失败计数 token”的 HMAC 签名/验签
|
||||||
@@ -479,7 +470,7 @@ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtow
|
|||||||
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
|
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
|
||||||
```shell
|
```shell
|
||||||
cd ~
|
cd ~
|
||||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.15/netdisk-fast-download-linux-amd64.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
|
unzip netdisk-fast-download.zip
|
||||||
cd netdisk-fast-download
|
cd netdisk-fast-download
|
||||||
bash service-install.sh
|
bash service-install.sh
|
||||||
@@ -608,14 +599,3 @@ Core模块集成Vert.x实现类似spring的注解式路由API
|
|||||||
<a href="https://www.dkdun.cn/aff/WDBRYKGH" target="_blank">
|
<a href="https://www.dkdun.cn/aff/WDBRYKGH" target="_blank">
|
||||||
<img src="https://www.dkdun.cn/themes/web/www/upload/local68c2dbb2ab148.png" width="200">
|
<img src="https://www.dkdun.cn/themes/web/www/upload/local68c2dbb2ab148.png" width="200">
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
|
||||||
### 代理资源支持
|
|
||||||
|
|
||||||
<a href="https://proxy-seller.com/?partner=5799A39425654D33">
|
|
||||||
<img src="https://raw.githubusercontent.com/wujunwei928/parse-video-py/main/resources/proxy-seller-logo.png" alt="Proxy-Seller" width="120">
|
|
||||||
</a>
|
|
||||||
|
|
||||||
感谢 [Proxy-Seller](https://proxy-seller.com/?partner=5799A39425654D33) 提供代理 IP 支持,其香港 IP 可用于本项目。
|
|
||||||
|
|
||||||
[Proxy-Seller 优惠链接](https://proxy-seller.com/?partner=5799A39425654D33) · 专属折扣码:`BJSBDD_664959`
|
|
||||||
-107
@@ -1,107 +0,0 @@
|
|||||||
[English](#security-policy) | [简体中文](#安全政策)
|
|
||||||
|
|
||||||
# Security Policy
|
|
||||||
|
|
||||||
Thank you for helping keep netdisk-fast-download (NFD) and its users safe.
|
|
||||||
|
|
||||||
## Supported Versions
|
|
||||||
|
|
||||||
Security fixes are provided for the latest stable release. Older releases are not actively maintained and generally do not receive security backports. Users are strongly encouraged to upgrade to the latest stable release.
|
|
||||||
|
|
||||||
| Version | Supported |
|
|
||||||
| --- | --- |
|
|
||||||
| Latest stable release | ✅ |
|
|
||||||
| Older releases | ❌ |
|
|
||||||
|
|
||||||
## Reporting a Vulnerability
|
|
||||||
|
|
||||||
Please report suspected security vulnerabilities privately through [GitHub Private Vulnerability Reporting](https://github.com/qaiu/netdisk-fast-download/security/advisories/new). Do not disclose unpatched vulnerabilities in public Issues, Pull Requests, Discussions, or other public channels.
|
|
||||||
|
|
||||||
Please include the following information where possible:
|
|
||||||
|
|
||||||
- Affected version or commit
|
|
||||||
- Vulnerability description, affected component, and potential impact
|
|
||||||
- Reproduction steps or a minimal proof of concept
|
|
||||||
- Relevant configuration, logs, and deployment details, with sensitive information redacted
|
|
||||||
|
|
||||||
Do not include real credentials, authentication keys, API tokens, or personal data in your report. Test only systems you own or are authorized to test.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
This policy applies to security vulnerabilities in the official NFD project, including authentication, authorization, credential handling, and other security-sensitive functionality.
|
|
||||||
|
|
||||||
Ordinary bugs, upstream API changes, and compatibility issues without a security impact should be reported through [GitHub Issues](https://github.com/qaiu/netdisk-fast-download/issues). Issues caused solely by third-party services, unofficial modifications, or unsafe deployment configurations are generally outside the scope of this policy. However, vulnerabilities in NFD's default configuration or its handling of third-party services remain in scope.
|
|
||||||
|
|
||||||
## Security Response and Disclosure
|
|
||||||
|
|
||||||
Security reports are handled on a best-effort basis, taking into account severity, impact, and maintainer availability. We aim to assess reports, develop appropriate fixes or mitigations, and coordinate public disclosure with reporters where possible. No fixed response or remediation timeframe is guaranteed.
|
|
||||||
|
|
||||||
## Security Best Practices
|
|
||||||
|
|
||||||
- Keep NFD and its dependencies up to date.
|
|
||||||
- Use HTTPS and restrict access to sensitive administrative interfaces.
|
|
||||||
- Protect authentication keys, API tokens, and cloud-drive credentials; never expose them in public logs, frontend bundles, or diagnostic reports.
|
|
||||||
- Enable only the services and optional features you need.
|
|
||||||
- Revoke or rotate potentially compromised credentials promptly.
|
|
||||||
|
|
||||||
## Security Advisories
|
|
||||||
|
|
||||||
For published vulnerabilities, affected versions, fixes, and mitigation guidance, see [GitHub Security Advisories](https://github.com/qaiu/netdisk-fast-download/security/advisories) and [Release Notes](https://github.com/qaiu/netdisk-fast-download/releases).
|
|
||||||
|
|
||||||
## Acknowledgments
|
|
||||||
|
|
||||||
We appreciate everyone who responsibly reports vulnerabilities and helps improve the security of NFD.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# 安全政策
|
|
||||||
|
|
||||||
感谢你帮助维护 netdisk-fast-download(NFD)及其用户的安全。
|
|
||||||
|
|
||||||
## 支持的版本
|
|
||||||
|
|
||||||
安全修复面向最新稳定版本。历史版本不再主动维护,原则上不提供安全补丁回移。强烈建议用户及时升级至最新稳定版本。
|
|
||||||
|
|
||||||
| 版本 | 是否支持 |
|
|
||||||
| --- | --- |
|
|
||||||
| 最新稳定版 | ✅ |
|
|
||||||
| 历史版本 | ❌ |
|
|
||||||
|
|
||||||
## 漏洞报告
|
|
||||||
|
|
||||||
请通过 [GitHub 私密漏洞报告](https://github.com/qaiu/netdisk-fast-download/security/advisories/new) 渠道提交疑似安全漏洞。请勿在公开 Issue、Pull Request、Discussion 或其他公开渠道披露尚未修复的漏洞。
|
|
||||||
|
|
||||||
请尽可能提供以下信息:
|
|
||||||
|
|
||||||
- 受影响的版本或提交
|
|
||||||
- 漏洞描述、受影响组件及潜在影响
|
|
||||||
- 复现步骤或最小概念验证
|
|
||||||
- 相关配置、日志及部署信息(请先脱敏)
|
|
||||||
|
|
||||||
请勿在报告中包含真实账号凭据、认证密钥、API 令牌或个人数据。请仅在自己拥有或已获得授权的环境中进行安全测试。
|
|
||||||
|
|
||||||
## 适用范围
|
|
||||||
|
|
||||||
本政策适用于 NFD 官方项目中的安全漏洞,包括身份认证、访问控制、凭据处理及其他涉及安全的功能。
|
|
||||||
|
|
||||||
不涉及安全影响的普通缺陷、上游接口变更及兼容性问题,请通过 [GitHub Issues](https://github.com/qaiu/netdisk-fast-download/issues) 反馈。仅由第三方服务、非官方修改或不安全部署配置引起的问题,原则上不属于本政策的适用范围。但 NFD 默认配置或第三方服务处理逻辑中存在的安全漏洞仍在适用范围内。
|
|
||||||
|
|
||||||
## 安全响应与披露
|
|
||||||
|
|
||||||
维护者将根据漏洞严重程度、影响范围及可用时间尽力处理安全报告,包括漏洞评估、制定修复或缓解措施,并尽可能与报告人协调公开披露。不承诺固定的响应或修复时限。
|
|
||||||
|
|
||||||
## 安全最佳实践
|
|
||||||
|
|
||||||
- 及时更新 NFD 及其依赖组件。
|
|
||||||
- 使用 HTTPS,并限制敏感管理接口的访问权限。
|
|
||||||
- 妥善保管认证密钥、API 令牌及网盘凭据,切勿通过公开日志、前端构建产物或诊断报告泄露。
|
|
||||||
- 仅启用实际需要的服务及可选功能。
|
|
||||||
- 及时撤销或轮换可能泄露的凭据。
|
|
||||||
|
|
||||||
## 安全公告
|
|
||||||
|
|
||||||
已公开的漏洞、影响版本、修复及缓解措施,请参阅 [GitHub 安全公告](https://github.com/qaiu/netdisk-fast-download/security/advisories) 和 [版本发布说明](https://github.com/qaiu/netdisk-fast-download/releases)。
|
|
||||||
|
|
||||||
## 致谢
|
|
||||||
|
|
||||||
感谢所有负责任地报告漏洞并帮助提升 NFD 安全性的研究人员与社区成员。
|
|
||||||
+4
-4
@@ -4,26 +4,26 @@ NFD 解析器模块:聚合各类网盘/分享页解析,统一输出文件列
|
|||||||
|
|
||||||
- 语言:Java 17
|
- 语言:Java 17
|
||||||
- 构建:Maven
|
- 构建:Maven
|
||||||
- 模块版本:10.2.7
|
- 模块版本:10.2.5
|
||||||
|
|
||||||
## 依赖(Maven Central)
|
## 依赖(Maven Central)
|
||||||
```xml
|
```xml
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cn.qaiu</groupId>
|
<groupId>cn.qaiu</groupId>
|
||||||
<artifactId>parser</artifactId>
|
<artifactId>parser</artifactId>
|
||||||
<version>10.2.7</version>
|
<version>10.2.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
- Gradle Groovy DSL:
|
- Gradle Groovy DSL:
|
||||||
```groovy
|
```groovy
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation 'cn.qaiu:parser:10.2.7'
|
implementation 'cn.qaiu:parser:10.2.5'
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
- Gradle Kotlin DSL:
|
- Gradle Kotlin DSL:
|
||||||
```kotlin
|
```kotlin
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("cn.qaiu:parser:10.2.7")
|
implementation("cn.qaiu:parser:10.2.5")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@
|
|||||||
|
|
||||||
**加密方式**:
|
**加密方式**:
|
||||||
- 算法:AES/ECB/PKCS5Padding
|
- 算法:AES/ECB/PKCS5Padding
|
||||||
- 密钥:由自建服务显式配置并通过安全渠道交给可信客户端(无公共默认值)
|
- 密钥:`nfd_auth_key2026`(16字节)
|
||||||
- 流程:JSON → AES加密 → Base64 → URL编码
|
- 流程:JSON → AES加密 → Base64 → URL编码
|
||||||
|
|
||||||
**JSON 结构**:
|
**JSON 结构**:
|
||||||
|
|||||||
@@ -33,8 +33,8 @@ URL解码 → Base64解码 → AES解密 → JSON对象
|
|||||||
### 加密配置
|
### 加密配置
|
||||||
|
|
||||||
- **加密算法**: AES/ECB/PKCS5Padding
|
- **加密算法**: AES/ECB/PKCS5Padding
|
||||||
- **密钥长度**: 16、24 或 32 个 UTF-8 字节
|
- **密钥长度**: 16位(128位)
|
||||||
- **密钥**: 没有公共默认值。需要对接的可信客户端应使用自建服务显式配置的 `server.authEncryptKey`。
|
- **默认密钥**: `nfd_auth_key2026`(可在 `app-dev.yml` 中通过 `server.authEncryptKey` 配置)
|
||||||
|
|
||||||
### 密钥作用说明(重要)
|
### 密钥作用说明(重要)
|
||||||
|
|
||||||
@@ -43,7 +43,7 @@ URL解码 → Base64解码 → AES解密 → JSON对象
|
|||||||
1. `server.authEncryptKey`
|
1. `server.authEncryptKey`
|
||||||
- 用途:加解密 `auth` 参数(前端/调用方传入的认证信息)
|
- 用途:加解密 `auth` 参数(前端/调用方传入的认证信息)
|
||||||
- 影响范围:`/parser`、`/json/parser`、`/v2/linkInfo` 等接口中的 `auth` 参数
|
- 影响范围:`/parser`、`/json/parser`、`/v2/linkInfo` 等接口中的 `auth` 参数
|
||||||
- 注意:这是 **AES 对称加密密钥**,要求 16、24 或 32 字节
|
- 注意:这是 **AES 对称加密密钥**,要求 16 位
|
||||||
|
|
||||||
2. `server.donatedAccountFailureTokenSignKey`
|
2. `server.donatedAccountFailureTokenSignKey`
|
||||||
- 用途:签名和验签“捐赠账号失败计数 token”(用于防伪造、失败计数)
|
- 用途:签名和验签“捐赠账号失败计数 token”(用于防伪造、失败计数)
|
||||||
@@ -194,7 +194,7 @@ AuthParam decoded = AuthParamCodec.decode(encrypted);
|
|||||||
// 使用 CryptoJS 库
|
// 使用 CryptoJS 库
|
||||||
const CryptoJS = require('crypto-js');
|
const CryptoJS = require('crypto-js');
|
||||||
|
|
||||||
const AUTH_KEY = process.env.NFD_AUTH_ENCRYPT_KEY;
|
const AUTH_KEY = 'nfd_auth_key2026';
|
||||||
|
|
||||||
// 加密
|
// 加密
|
||||||
function encodeAuthParam(authObj) {
|
function encodeAuthParam(authObj) {
|
||||||
@@ -234,8 +234,7 @@ from urllib.parse import quote, unquote
|
|||||||
from Crypto.Cipher import AES
|
from Crypto.Cipher import AES
|
||||||
from Crypto.Util.Padding import pad, unpad
|
from Crypto.Util.Padding import pad, unpad
|
||||||
|
|
||||||
import os
|
AUTH_KEY = b'nfd_auth_key2026'
|
||||||
AUTH_KEY = os.environ['NFD_AUTH_ENCRYPT_KEY'].encode('utf-8')
|
|
||||||
|
|
||||||
def encode_auth_param(auth_obj):
|
def encode_auth_param(auth_obj):
|
||||||
"""加密认证参数"""
|
"""加密认证参数"""
|
||||||
@@ -324,8 +323,8 @@ if (auths != null) {
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
server:
|
server:
|
||||||
# auth参数加密密钥(16、24 或 32 字节)
|
# auth参数加密密钥(16位AES密钥)
|
||||||
# authEncryptKey: "" # 仅在可信客户端或多实例需共享密钥时显式配置
|
authEncryptKey: 'your_custom_key16'
|
||||||
|
|
||||||
# 捐赠账号失败计数token签名密钥(HMAC)
|
# 捐赠账号失败计数token签名密钥(HMAC)
|
||||||
# 建议使用较长随机字符串,并与 authEncryptKey 不同
|
# 建议使用较长随机字符串,并与 authEncryptKey 不同
|
||||||
|
|||||||
@@ -72,7 +72,7 @@
|
|||||||
## 使用说明
|
## 使用说明
|
||||||
|
|
||||||
1. **编码流程**: JSON对象 → AES加密 → Base64编码 → URL编码
|
1. **编码流程**: JSON对象 → AES加密 → Base64编码 → URL编码
|
||||||
2. **加密配置**: AES/ECB/PKCS5Padding, 密钥: 自建服务配置值(无公共默认值)
|
2. **加密配置**: AES/ECB/PKCS5Padding, 密钥: `nfd_auth_key2026` (16位)
|
||||||
3. **接口调用**: `GET /parser?url={分享链接}&pwd={提取码}&auth={加密认证参数}`
|
3. **接口调用**: `GET /parser?url={分享链接}&pwd={提取码}&auth={加密认证参数}`
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,145 +0,0 @@
|
|||||||
package cn.qaiu.parser;
|
|
||||||
|
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 目录列表分页约定(解析器与 API 共用)。
|
|
||||||
* <p>
|
|
||||||
* 入参写在 {@link ShareLinkInfo#getOtherParam()}:
|
|
||||||
* <ul>
|
|
||||||
* <li>{@link #PAGE}:从 1 开始的页码;不传时解析器按原逻辑只取第一页</li>
|
|
||||||
* <li>{@link #CURSOR}:上一页返回的 {@code nextCursor},可选,只是加速,不可信</li>
|
|
||||||
* </ul>
|
|
||||||
* 解析器取完一页后写回 {@link #PAGE_INFO},见 {@link #pageInfo}。
|
|
||||||
* 没写 {@link #PAGE_INFO} 的解析器视为不分页,整份列表就是第 1 页。
|
|
||||||
*/
|
|
||||||
public final class FolderPaging {
|
|
||||||
|
|
||||||
public static final String PAGE = "page";
|
|
||||||
public static final String CURSOR = "pageCursor";
|
|
||||||
public static final String PAGE_INFO = "pageInfo";
|
|
||||||
|
|
||||||
/** 页码上限。蓝奏无游标时要从第 1 页顺序翻到目标页,必须有界。 */
|
|
||||||
public static final int MAX_PAGE = 500;
|
|
||||||
|
|
||||||
private static final Set<String> PAGED_TYPES = Set.of("lz", "fj", "iz");
|
|
||||||
|
|
||||||
private FolderPaging() {
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 该网盘的目录解析是否支持按页取。 */
|
|
||||||
public static boolean supports(String type) {
|
|
||||||
return type != null && PAGED_TYPES.contains(type.toLowerCase(Locale.ROOT));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 解析页码参数。空值返回 null(保持旧行为);非法值抛 IllegalArgumentException。
|
|
||||||
*/
|
|
||||||
public static Integer parsePage(String raw) {
|
|
||||||
if (raw == null || raw.isBlank()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
int page;
|
|
||||||
try {
|
|
||||||
page = Integer.parseInt(raw.trim());
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
throw new IllegalArgumentException("page 必须是正整数: " + raw);
|
|
||||||
}
|
|
||||||
if (page < 1 || page > MAX_PAGE) {
|
|
||||||
throw new IllegalArgumentException("page 超出范围 1-" + MAX_PAGE + ": " + raw);
|
|
||||||
}
|
|
||||||
return page;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 本次请求的页码;没传返回 null。 */
|
|
||||||
public static Integer requestedPage(ShareLinkInfo info) {
|
|
||||||
Object v = info.getOtherParam().get(PAGE);
|
|
||||||
if (v instanceof Number n) {
|
|
||||||
return n.intValue();
|
|
||||||
}
|
|
||||||
return v == null ? null : parsePage(v.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 本次请求的页码;没传按第 1 页。 */
|
|
||||||
public static int pageOrFirst(ShareLinkInfo info) {
|
|
||||||
Integer page = requestedPage(info);
|
|
||||||
return page == null ? 1 : page;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String cursor(ShareLinkInfo info) {
|
|
||||||
Object v = info.getOtherParam().get(CURSOR);
|
|
||||||
return v == null || v.toString().isBlank() ? null : v.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 写回分页结果。
|
|
||||||
*
|
|
||||||
* @param pageSize 上游每页条数(原始条数口径,含被过滤的占位项)
|
|
||||||
* @param hasMore 上游明确还有下一页
|
|
||||||
* @param total 上游给出的总条数,未知传 null
|
|
||||||
* @param totalPage 上游给出的总页数,未知传 null
|
|
||||||
* @param nextCursor 取下一页可直接复用的游标,没有传 null
|
|
||||||
*/
|
|
||||||
public static JsonObject pageInfo(ShareLinkInfo info, int page, int pageSize, boolean hasMore,
|
|
||||||
Integer total, Integer totalPage, String nextCursor) {
|
|
||||||
JsonObject json = new JsonObject()
|
|
||||||
.put("paged", true)
|
|
||||||
.put("page", page)
|
|
||||||
.put("pageSize", pageSize)
|
|
||||||
.put("hasMore", hasMore)
|
|
||||||
.put("nextPage", hasMore ? page + 1 : null)
|
|
||||||
.put("total", total)
|
|
||||||
.put("totalPage", totalPage)
|
|
||||||
.put("nextCursor", hasMore ? nextCursor : null);
|
|
||||||
info.getOtherParam().put(PAGE_INFO, json);
|
|
||||||
return json;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 上游给了总页数就以它为准;没给时整页满才认为可能还有。空页一律结束,避免无限翻页。
|
|
||||||
*/
|
|
||||||
public static boolean hasMore(int page, int rawCount, int pageSize, Integer totalPage) {
|
|
||||||
if (rawCount <= 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (totalPage != null && totalPage > 0) {
|
|
||||||
return page < totalPage;
|
|
||||||
}
|
|
||||||
return rawCount >= pageSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 小飞机 / 蓝奏优享 share/list 响应:offset 为页码,带 total / totalPage。 */
|
|
||||||
public static JsonObject offsetListPage(ShareLinkInfo info, JsonObject resp, int rawCount, int pageSize) {
|
|
||||||
int page = pageOrFirst(info);
|
|
||||||
Integer total = intOrNull(resp, "total");
|
|
||||||
Integer totalPage = intOrNull(resp, "totalPage");
|
|
||||||
return pageInfo(info, page, pageSize, hasMore(page, rawCount, pageSize, totalPage), total, totalPage, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Integer intOrNull(JsonObject json, String key) {
|
|
||||||
if (json == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
Object v = json.getValue(key);
|
|
||||||
if (v instanceof Number n) {
|
|
||||||
return n.intValue();
|
|
||||||
}
|
|
||||||
if (v instanceof CharSequence s) {
|
|
||||||
try {
|
|
||||||
return Integer.parseInt(s.toString().trim());
|
|
||||||
} catch (NumberFormatException ignored) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static JsonObject pageInfo(ShareLinkInfo info) {
|
|
||||||
Object v = info.getOtherParam().get(PAGE_INFO);
|
|
||||||
return v instanceof JsonObject json ? json : null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,6 @@ package cn.qaiu.parser.impl;
|
|||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.FolderPaging;
|
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.util.*;
|
import cn.qaiu.util.*;
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
@@ -61,10 +60,7 @@ public class FjTool extends PanBase {
|
|||||||
|
|
||||||
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
||||||
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
||||||
"={folderId}&offset={offset}&limit={limit}";
|
"={folderId}&offset=1&limit=60";
|
||||||
|
|
||||||
/** share/list 每页条数;offset 是从 1 开始的页码。 */
|
|
||||||
static final int LIST_LIMIT = 60;
|
|
||||||
|
|
||||||
private static final MultiMap header;
|
private static final MultiMap header;
|
||||||
private static final MultiMap header0;
|
private static final MultiMap header0;
|
||||||
@@ -496,11 +492,7 @@ public class FjTool extends PanBase {
|
|||||||
.setParserUrl(id)
|
.setParserUrl(id)
|
||||||
.setPanType(shareLinkInfo.getType());
|
.setPanType(shareLinkInfo.getType());
|
||||||
List<FileInfo> result = new ArrayList<>();
|
List<FileInfo> result = new ArrayList<>();
|
||||||
int page = FolderPaging.pageOrFirst(shareLinkInfo);
|
result.add(fileInfo);
|
||||||
if (page == 1) {
|
|
||||||
result.add(fileInfo);
|
|
||||||
}
|
|
||||||
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
|
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -514,101 +506,86 @@ public class FjTool extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
|
||||||
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
JsonArray list;
|
JsonArray list;
|
||||||
JsonObject jsonObject;
|
|
||||||
try {
|
try {
|
||||||
jsonObject = asJson(res);
|
JsonObject jsonObject = asJson(res);
|
||||||
log.debug("目录列表: {}", jsonObject.encodePrettily());
|
log.debug("目录列表: {}", jsonObject.encodePrettily());
|
||||||
list = jsonObject.getJsonArray("list");
|
list = jsonObject.getJsonArray("list");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("解析目录失败: {}", res.bodyAsString());
|
log.error("解析目录失败: {}", res.bodyAsString());
|
||||||
promise.tryFail("目录解析失败: 响应不是 JSON");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (list == null) {
|
|
||||||
promise.tryFail("目录解析失败: 响应缺少 list 字段: " + jsonObject);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ArrayList<FileInfo> result = new ArrayList<>();
|
ArrayList<FileInfo> result = new ArrayList<>();
|
||||||
try {
|
list.forEach(item->{
|
||||||
list.forEach(item->{
|
JsonObject fileJson = (JsonObject) item;
|
||||||
JsonObject fileJson = (JsonObject) item;
|
FileInfo fileInfo = new FileInfo();
|
||||||
FileInfo fileInfo = new FileInfo();
|
|
||||||
|
|
||||||
// 映射已知字段fileInfo
|
// 映射已知字段fileInfo
|
||||||
String fileId = fileJson.getString("fileId");
|
String fileId = fileJson.getString("fileId");
|
||||||
String userId = fileJson.getString("userId");
|
String userId = fileJson.getString("userId");
|
||||||
|
|
||||||
// 其他参数
|
// 其他参数
|
||||||
long nowTs2 = System.currentTimeMillis();
|
long nowTs2 = System.currentTimeMillis();
|
||||||
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
||||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
||||||
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
||||||
|
|
||||||
// 回传用到的参数
|
// 回传用到的参数
|
||||||
//"fidEncode", paramJson.getString("fidEncode"))
|
//"fidEncode", paramJson.getString("fidEncode"))
|
||||||
//"uuid", paramJson.getString("uuid"))
|
//"uuid", paramJson.getString("uuid"))
|
||||||
//"ts", paramJson.getString("ts"))
|
//"ts", paramJson.getString("ts"))
|
||||||
//"auth", paramJson.getString("auth"))
|
//"auth", paramJson.getString("auth"))
|
||||||
//"shareId", paramJson.getString("shareId"))
|
//"shareId", paramJson.getString("shareId"))
|
||||||
JsonObject entries = JsonObject.of(
|
JsonObject entries = JsonObject.of(
|
||||||
"fileId", fileId,
|
"fileId", fileId,
|
||||||
"userId", userId,
|
"userId", userId,
|
||||||
"fidEncode", fidEncode,
|
"fidEncode", fidEncode,
|
||||||
"uuid", uuid,
|
"uuid", uuid,
|
||||||
"ts", tsEncode2,
|
"ts", tsEncode2,
|
||||||
"auth", auth,
|
"auth", auth,
|
||||||
"shareId", shareId);
|
"shareId", shareId);
|
||||||
String param = CommonUtils.urlBase64Encode(entries.encode());
|
String param = CommonUtils.urlBase64Encode(entries.encode());
|
||||||
|
|
||||||
if (fileJson.getInteger("fileType") == 2) {
|
if (fileJson.getInteger("fileType") == 2) {
|
||||||
// 如果是目录
|
// 如果是目录
|
||||||
fileInfo.setFileName(fileJson.getString("name"))
|
fileInfo.setFileName(fileJson.getString("name"))
|
||||||
.setFileId(fileJson.getString("folderId"))
|
.setFileId(fileJson.getString("folderId"))
|
||||||
.setCreateTime(fileJson.getString("updTime"))
|
.setCreateTime(fileJson.getString("updTime"))
|
||||||
.setFileType("folder")
|
.setFileType("folder")
|
||||||
.setSize(0L)
|
.setSize(0L)
|
||||||
.setSizeStr("0B")
|
.setSizeStr("0B")
|
||||||
.setCreateBy(fileJson.getLong("userId").toString())
|
|
||||||
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
|
||||||
.setCreateTime(fileJson.getString("updTime"))
|
|
||||||
.setFileIcon(fileJson.getString("fileIcon"))
|
|
||||||
.setPanType(shareLinkInfo.getType())
|
|
||||||
// 设置目录解析的URL
|
|
||||||
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&uuid=%s", getDomainName(),
|
|
||||||
shareLinkInfo.getShareUrl(), fileJson.getString("folderId"), uuid));
|
|
||||||
result.add(fileInfo);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
long fileSize = fileJson.getLong("fileSize") * 1024;
|
|
||||||
fileInfo.setFileName(fileJson.getString("fileName"))
|
|
||||||
.setFileId(fileJson.getString("fileId"))
|
|
||||||
.setCreateTime(fileJson.getString("createTime"))
|
|
||||||
.setFileType("file")
|
|
||||||
.setSize(fileSize)
|
|
||||||
.setSizeStr(FileSizeConverter.convertToReadableSize(fileSize))
|
|
||||||
.setCreateBy(fileJson.getLong("userId").toString())
|
.setCreateBy(fileJson.getLong("userId").toString())
|
||||||
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
||||||
.setCreateTime(fileJson.getString("updTime"))
|
.setCreateTime(fileJson.getString("updTime"))
|
||||||
.setFileIcon(fileJson.getString("fileIcon"))
|
.setFileIcon(fileJson.getString("fileIcon"))
|
||||||
.setPanType(shareLinkInfo.getType())
|
.setPanType(shareLinkInfo.getType())
|
||||||
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(),
|
// 设置目录解析的URL
|
||||||
shareLinkInfo.getType(), param))
|
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&uuid=%s", getDomainName(),
|
||||||
.setPreviewUrl(String.format("%s/v2/viewUrl/%s/%s", getDomainName(),
|
shareLinkInfo.getShareUrl(), fileJson.getString("folderId"), uuid));
|
||||||
shareLinkInfo.getType(), param));
|
|
||||||
result.add(fileInfo);
|
result.add(fileInfo);
|
||||||
});
|
return;
|
||||||
} catch (Exception e) {
|
}
|
||||||
log.error("目录列表条目解析失败: {}", jsonObject, e);
|
long fileSize = fileJson.getLong("fileSize") * 1024;
|
||||||
promise.tryFail("目录解析失败: 列表条目格式异常 " + e);
|
fileInfo.setFileName(fileJson.getString("fileName"))
|
||||||
return;
|
.setFileId(fileJson.getString("fileId"))
|
||||||
}
|
.setCreateTime(fileJson.getString("createTime"))
|
||||||
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
|
.setFileType("file")
|
||||||
|
.setSize(fileSize)
|
||||||
|
.setSizeStr(FileSizeConverter.convertToReadableSize(fileSize))
|
||||||
|
.setCreateBy(fileJson.getLong("userId").toString())
|
||||||
|
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
||||||
|
.setCreateTime(fileJson.getString("updTime"))
|
||||||
|
.setFileIcon(fileJson.getString("fileIcon"))
|
||||||
|
.setPanType(shareLinkInfo.getType())
|
||||||
|
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(),
|
||||||
|
shareLinkInfo.getType(), param))
|
||||||
|
.setPreviewUrl(String.format("%s/v2/viewUrl/%s/%s", getDomainName(),
|
||||||
|
shareLinkInfo.getType(), param));
|
||||||
|
result.add(fileInfo);
|
||||||
|
});
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
}).onFailure(err -> promise.tryFail("目录解析失败: " + err.getMessage()));
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package cn.qaiu.parser.impl;
|
|||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.FolderPaging;
|
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.parser.TokenCache;
|
import cn.qaiu.parser.TokenCache;
|
||||||
import cn.qaiu.util.AESUtils;
|
import cn.qaiu.util.AESUtils;
|
||||||
@@ -57,10 +56,7 @@ public class IzTool extends PanBase {
|
|||||||
|
|
||||||
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
||||||
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
||||||
"={folderId}&offset={offset}&limit={limit}";
|
"={folderId}&offset=1&limit=60";
|
||||||
|
|
||||||
/** share/list 每页条数;offset 是从 1 开始的页码。 */
|
|
||||||
static final int LIST_LIMIT = 60;
|
|
||||||
|
|
||||||
|
|
||||||
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
||||||
@@ -573,11 +569,7 @@ public class IzTool extends PanBase {
|
|||||||
.setParserUrl(id)
|
.setParserUrl(id)
|
||||||
.setPanType(shareLinkInfo.getType());
|
.setPanType(shareLinkInfo.getType());
|
||||||
List<FileInfo> result = new ArrayList<>();
|
List<FileInfo> result = new ArrayList<>();
|
||||||
int page = FolderPaging.pageOrFirst(shareLinkInfo);
|
result.add(fileInfo);
|
||||||
if (page == 1) {
|
|
||||||
result.add(fileInfo);
|
|
||||||
}
|
|
||||||
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
|
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -594,8 +586,6 @@ public class IzTool extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
|
||||||
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
String resBody = asText(res);
|
String resBody = asText(res);
|
||||||
// 检查是否包含 cookie 验证
|
// 检查是否包含 cookie 验证
|
||||||
@@ -610,8 +600,6 @@ public class IzTool extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
|
||||||
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
|
||||||
.send().onSuccess(res2 -> {
|
.send().onSuccess(res2 -> {
|
||||||
processDirResponse(res2, shareId, promise);
|
processDirResponse(res2, shareId, promise);
|
||||||
}).onFailure(err -> {
|
}).onFailure(err -> {
|
||||||
@@ -703,7 +691,6 @@ public class IzTool extends PanBase {
|
|||||||
shareLinkInfo.getType(), param));
|
shareLinkInfo.getType(), param));
|
||||||
result.add(fileInfo);
|
result.add(fileInfo);
|
||||||
});
|
});
|
||||||
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
|
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package cn.qaiu.parser.impl;
|
|||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.FolderPaging;
|
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.util.AESUtils;
|
import cn.qaiu.util.AESUtils;
|
||||||
import cn.qaiu.util.AcwScV2Generator;
|
import cn.qaiu.util.AcwScV2Generator;
|
||||||
@@ -55,10 +54,7 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
|
|
||||||
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
||||||
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
||||||
"={folderId}&offset={offset}&limit={limit}";
|
"={folderId}&offset=1&limit=60";
|
||||||
|
|
||||||
/** share/list 每页条数;offset 是从 1 开始的页码。 */
|
|
||||||
static final int LIST_LIMIT = 60;
|
|
||||||
|
|
||||||
|
|
||||||
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
||||||
@@ -516,11 +512,7 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
.setParserUrl(id)
|
.setParserUrl(id)
|
||||||
.setPanType(shareLinkInfo.getType());
|
.setPanType(shareLinkInfo.getType());
|
||||||
List<FileInfo> result = new ArrayList<>();
|
List<FileInfo> result = new ArrayList<>();
|
||||||
int page = FolderPaging.pageOrFirst(shareLinkInfo);
|
result.add(fileInfo);
|
||||||
if (page == 1) {
|
|
||||||
result.add(fileInfo);
|
|
||||||
}
|
|
||||||
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
|
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -573,8 +565,6 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
|
||||||
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
String resBody = asText(res);
|
String resBody = asText(res);
|
||||||
// 检查是否包含 cookie 验证
|
// 检查是否包含 cookie 验证
|
||||||
@@ -589,8 +579,6 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
|
||||||
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
|
||||||
.send().onSuccess(res2 -> {
|
.send().onSuccess(res2 -> {
|
||||||
processDirResponse(res2, shareId, promise);
|
processDirResponse(res2, shareId, promise);
|
||||||
}).onFailure(err -> {
|
}).onFailure(err -> {
|
||||||
@@ -683,7 +671,6 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
shareLinkInfo.getType(), param));
|
shareLinkInfo.getType(), param));
|
||||||
result.add(fileInfo);
|
result.add(fileInfo);
|
||||||
});
|
});
|
||||||
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
|
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
||||||
|
|||||||
@@ -1,116 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import cn.qaiu.util.CommonUtils;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 蓝奏目录「下一页」游标。
|
|
||||||
* <p>
|
|
||||||
* filemoreajax 的 t/k 由分享页下发,上游按这组令牌记录已翻到第几页:同一组令牌可以取
|
|
||||||
* 「已取过的最大页 + 1」以内的任意页;换一组新令牌直接跳到第 N 页会返回 zt=4「请刷新,重试」。
|
|
||||||
* 所以加载更多时把上一页用过的表单(不含密码和页码)交还给客户端,下次直接续翻。
|
|
||||||
* <p>
|
|
||||||
* 游标来自客户端,不可信:只用于表单字段,POST 主机仍由服务端按分享链接决定;
|
|
||||||
* 分享 key、页码、路径对不上一律当作没有游标,回退到从第 1 页顺序翻。
|
|
||||||
*/
|
|
||||||
final class LzFolderCursor {
|
|
||||||
|
|
||||||
private static final int VERSION = 1;
|
|
||||||
private static final Pattern PATH = Pattern.compile("/filemoreajax\\.php\\?file=(\\d+)");
|
|
||||||
private static final Pattern KEY = Pattern.compile("\\w{1,32}");
|
|
||||||
private static final int MAX_VALUE_LENGTH = 256;
|
|
||||||
private static final int MAX_FIELDS = 32;
|
|
||||||
|
|
||||||
final String path;
|
|
||||||
final Map<String, String> form;
|
|
||||||
final String webpage;
|
|
||||||
|
|
||||||
private LzFolderCursor(String path, Map<String, String> form, String webpage) {
|
|
||||||
this.path = path;
|
|
||||||
this.form = form;
|
|
||||||
this.webpage = webpage;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String encode(String shareKey, String path, Map<String, String> form, int nextPage, String webpage) {
|
|
||||||
JsonObject f = new JsonObject();
|
|
||||||
form.forEach((k, v) -> {
|
|
||||||
if (!"pwd".equals(k) && !"pg".equals(k)) {
|
|
||||||
f.put(k, v);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
JsonObject json = new JsonObject()
|
|
||||||
.put("v", VERSION)
|
|
||||||
.put("s", shareKey)
|
|
||||||
.put("p", path)
|
|
||||||
.put("n", nextPage)
|
|
||||||
.put("f", f);
|
|
||||||
if (webpage != null && !webpage.isBlank()) {
|
|
||||||
json.put("w", webpage);
|
|
||||||
}
|
|
||||||
return CommonUtils.urlBase64Encode(json.encode());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return 校验通过的游标;任何不匹配或格式问题都返回 null
|
|
||||||
*/
|
|
||||||
static LzFolderCursor decode(String raw, String shareKey, int page) {
|
|
||||||
if (raw == null || raw.isBlank() || raw.length() > 4096) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
JsonObject json = new JsonObject(CommonUtils.urlBase64Decode(raw));
|
|
||||||
if (json.getInteger("v", 0) != VERSION) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (shareKey == null || !shareKey.equals(json.getString("s"))) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (json.getInteger("n", -1) != page) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String path = json.getString("p");
|
|
||||||
var m = path == null ? null : PATH.matcher(path);
|
|
||||||
if (m == null || !m.matches()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
JsonObject f = json.getJsonObject("f");
|
|
||||||
if (f == null || f.size() > MAX_FIELDS) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
Map<String, String> form = new LinkedHashMap<>();
|
|
||||||
for (String key : f.fieldNames()) {
|
|
||||||
Object v = f.getValue(key);
|
|
||||||
if (!KEY.matcher(key).matches() || v == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String s = String.valueOf(v);
|
|
||||||
if (s.length() > MAX_VALUE_LENGTH || s.chars().anyMatch(c -> c < 0x20)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
form.put(key, s);
|
|
||||||
}
|
|
||||||
if (!m.group(1).equals(form.get("fid")) || !form.containsKey("t") || !form.containsKey("k")) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String webpage = json.getString("w");
|
|
||||||
if (webpage != null && (webpage.length() > MAX_VALUE_LENGTH || !webpage.matches("[\\w\\-=.%]+"))) {
|
|
||||||
webpage = null;
|
|
||||||
}
|
|
||||||
return new LzFolderCursor(path, form, webpage);
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 本次请求用的表单:游标字段 + 当前密码 + 目标页。 */
|
|
||||||
Map<String, String> formFor(String pwd, int page) {
|
|
||||||
Map<String, String> out = new LinkedHashMap<>(form);
|
|
||||||
out.put("pg", String.valueOf(page));
|
|
||||||
out.put("pwd", pwd == null ? "" : pwd);
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,6 @@ package cn.qaiu.parser.impl;
|
|||||||
import cn.qaiu.WebClientVertxInit;
|
import cn.qaiu.WebClientVertxInit;
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
import cn.qaiu.parser.FolderPaging;
|
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.util.*;
|
import cn.qaiu.util.*;
|
||||||
import io.netty.handler.codec.http.cookie.DefaultCookie;
|
import io.netty.handler.codec.http.cookie.DefaultCookie;
|
||||||
@@ -12,7 +11,6 @@ import io.vertx.core.Handler;
|
|||||||
import io.vertx.core.MultiMap;
|
import io.vertx.core.MultiMap;
|
||||||
import io.vertx.core.Promise;
|
import io.vertx.core.Promise;
|
||||||
import io.vertx.core.buffer.Buffer;
|
import io.vertx.core.buffer.Buffer;
|
||||||
import io.vertx.core.json.JsonArray;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import io.vertx.core.net.ProxyOptions;
|
import io.vertx.core.net.ProxyOptions;
|
||||||
import io.vertx.core.net.ProxyType;
|
import io.vertx.core.net.ProxyType;
|
||||||
@@ -27,11 +25,9 @@ import java.io.ByteArrayInputStream;
|
|||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Set;
|
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
@@ -77,18 +73,6 @@ public class LzTool extends PanBase {
|
|||||||
"https://www.lanzoux.com",
|
"https://www.lanzoux.com",
|
||||||
"https://wwww.lanzoux.com"
|
"https://wwww.lanzoux.com"
|
||||||
);
|
);
|
||||||
/** filemoreajax.php 每页条数(含 id=-1 占位项),不足即最后一页。 */
|
|
||||||
static final int LZ_FOLDER_PAGE_SIZE = 50;
|
|
||||||
/** 目录页不渲染的占位项 id。 */
|
|
||||||
static final String LZ_PLACEHOLDER_ID = "-1";
|
|
||||||
/** 同一组 t/k 两次 filemoreajax 间隔不足约 1.5 秒时返回 zt=4「请刷新,重试」。 */
|
|
||||||
static final int LZ_ZT_REFRESH = 4;
|
|
||||||
static final long LZ_PAGE_INTERVAL_MS = 1500;
|
|
||||||
/** zt=4 时同页重试的等待时间:实测多数 2 秒内恢复,个别需要约 5 秒。 */
|
|
||||||
static final long[] LZ_REFRESH_RETRY_DELAYS_MS = {2000, 5000};
|
|
||||||
static final int LZ_REFRESH_RETRIES = LZ_REFRESH_RETRY_DELAYS_MS.length;
|
|
||||||
/** 无游标时从第 1 页顺序翻的最大页数,保证一次请求能在路由超时(默认 15 秒)内完成。 */
|
|
||||||
static final int LZ_MAX_WALK_PAGES = 6;
|
|
||||||
/** 分享页 / ajax 请求超时 */
|
/** 分享页 / ajax 请求超时 */
|
||||||
private static final long REQUEST_TIMEOUT = 8000;
|
private static final long REQUEST_TIMEOUT = 8000;
|
||||||
/** 下载域跳转与二次验证超时,链路更长 */
|
/** 下载域跳转与二次验证超时,链路更长 */
|
||||||
@@ -99,14 +83,11 @@ public class LzTool extends PanBase {
|
|||||||
private static final Pattern P_AJAXDATA = Pattern.compile("ajaxdata\\s*=\\s*'([^']+)'");
|
private static final Pattern P_AJAXDATA = Pattern.compile("ajaxdata\\s*=\\s*'([^']+)'");
|
||||||
private static final Pattern P_WEBSIGN = Pattern.compile("'websign'\\s*:\\s*'([^']*)'");
|
private static final Pattern P_WEBSIGN = Pattern.compile("'websign'\\s*:\\s*'([^']*)'");
|
||||||
private static final Pattern P_WEBPAGE = Pattern.compile("[?&]webpage=([^&\"'\\s#]+)");
|
private static final Pattern P_WEBPAGE = Pattern.compile("[?&]webpage=([^&\"'\\s#]+)");
|
||||||
/**
|
/** 页面脚本里的绝对 ajax,例如 https://apifile.lanzouw.com/ajaxfile.php?file=123 */
|
||||||
* 页面脚本里的绝对 ajax,例如 https://apifile.lanzouw.com/ajaxfile.php?file=123。
|
|
||||||
* 文件名有 ajaxm / ajaxfile / ajaxfiles 三种,2026-11 起文件页 iframe 改用 ajaxfiles.php。
|
|
||||||
*/
|
|
||||||
private static final Pattern P_AJAX_ABSOLUTE = Pattern.compile(
|
private static final Pattern P_AJAX_ABSOLUTE = Pattern.compile(
|
||||||
"['\"]((?:https?:)?//[^'\"\\s<>]+/ajax(?:m|files?)\\.php\\?file=\\d+)['\"]",
|
"['\"]((?:https?:)?//[^'\"\\s<>]+/ajax(?:m|file)\\.php\\?file=\\d+)['\"]",
|
||||||
Pattern.CASE_INSENSITIVE);
|
Pattern.CASE_INSENSITIVE);
|
||||||
private static final Pattern P_AJAX_PATH = Pattern.compile("(?:['\"/]|^)(ajax(?:m|files?)\\.php\\?file=\\d+)");
|
private static final Pattern P_AJAX_PATH = Pattern.compile("(?:['\"/]|^)(ajax(?:m|file)\\.php\\?file=\\d+)");
|
||||||
private static final Pattern P_SIGN = Pattern.compile("'sign'\\s*:\\s*'([^']+)'");
|
private static final Pattern P_SIGN = Pattern.compile("'sign'\\s*:\\s*'([^']+)'");
|
||||||
private static final Pattern P_ISNGIS = Pattern.compile("var\\s+isngis\\s*=\\s*'([^']+)'");
|
private static final Pattern P_ISNGIS = Pattern.compile("var\\s+isngis\\s*=\\s*'([^']+)'");
|
||||||
private static final Pattern P_VERIFY_FILE = Pattern.compile("'file'\\s*:\\s*'([^']+)'");
|
private static final Pattern P_VERIFY_FILE = Pattern.compile("'file'\\s*:\\s*'([^']+)'");
|
||||||
@@ -423,38 +404,6 @@ public class LzTool extends PanBase {
|
|||||||
return "/" + ajax.group(1);
|
return "/" + ajax.group(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 分享页 / iframe 里的文件 ajax 表单;提取不到时返回 null。 */
|
|
||||||
static Map<String, String> fileAjaxForm(String html, String pwd) {
|
|
||||||
AjaxCall call = extractAjaxFromHtml(html, pwd);
|
|
||||||
return call == null ? null : call.form();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 文件 ajax 头。官方页把下载 POST 打到 apifile / apifile2 等跨站主机,
|
|
||||||
* 浏览器会带 Origin 且 Sec-Fetch-Site=cross-site;写 same-origin 与 Referer 矛盾,部分出口会被 ESA 拦。
|
|
||||||
*/
|
|
||||||
static MultiMap fileAjaxHeaders(String pageUrl, String ajaxTarget) {
|
|
||||||
MultiMap headers = HeaderUtils.parseHeaders(DOWN_AJAX_HEADERS);
|
|
||||||
String page = pageUrl == null ? "" : pageUrl.trim();
|
|
||||||
if (!page.isEmpty()) {
|
|
||||||
headers.set("referer", page);
|
|
||||||
}
|
|
||||||
String pageOrigin = normalizeOrigin(originOf(page, ""));
|
|
||||||
String ajaxOrigin = originFromAjaxTarget(ajaxTarget);
|
|
||||||
if (ajaxOrigin.isEmpty()) {
|
|
||||||
ajaxOrigin = pageOrigin;
|
|
||||||
}
|
|
||||||
if (!pageOrigin.isEmpty()) {
|
|
||||||
headers.set("origin", pageOrigin);
|
|
||||||
}
|
|
||||||
if (!ajaxOrigin.isEmpty() && !ajaxOrigin.equalsIgnoreCase(pageOrigin)) {
|
|
||||||
headers.set("Sec-Fetch-Site", "cross-site");
|
|
||||||
} else {
|
|
||||||
headers.set("Sec-Fetch-Site", "same-origin");
|
|
||||||
}
|
|
||||||
return headers;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void addAjaxOrigin(List<String> origins, String origin) {
|
private static void addAjaxOrigin(List<String> origins, String origin) {
|
||||||
if (origin != null && origin.contains("://") && !origins.contains(origin)) {
|
if (origin != null && origin.contains("://") && !origins.contains(origin)) {
|
||||||
origins.add(origin);
|
origins.add(origin);
|
||||||
@@ -778,16 +727,6 @@ public class LzTool extends PanBase {
|
|||||||
return new AjaxCall(block.group(1), data);
|
return new AjaxCall(block.group(1), data);
|
||||||
}
|
}
|
||||||
|
|
||||||
static Map<String, String> folderAjaxForm(String html, String pwd) {
|
|
||||||
AjaxCall call = extractFolderAjax(html, pwd);
|
|
||||||
return call == null ? null : call.form();
|
|
||||||
}
|
|
||||||
|
|
||||||
static String folderAjaxPath(String html, String pwd) {
|
|
||||||
AjaxCall call = extractFolderAjax(html, pwd);
|
|
||||||
return call == null ? null : call.path();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String resolveJsValue(String html, String raw) {
|
private static String resolveJsValue(String html, String raw) {
|
||||||
if (raw == null) {
|
if (raw == null) {
|
||||||
return "";
|
return "";
|
||||||
@@ -846,12 +785,13 @@ public class LzTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void getDownURL(String referer, AjaxCall call) {
|
private void getDownURL(String referer, AjaxCall call) {
|
||||||
// 文件 ajax 优先用页面里的绝对地址(常见 apifile / apifile2)。
|
MultiMap headers = HeaderUtils.parseHeaders(DOWN_AJAX_HEADERS);
|
||||||
|
// 文件 ajax 优先用页面里的绝对地址(常见 apifile.lanzouw.com)。
|
||||||
// 页面源站空响应再换 FILE_AJAX_FALLBACK_ORIGINS,wwww 仍在最后。
|
// 页面源站空响应再换 FILE_AJAX_FALLBACK_ORIGINS,wwww 仍在最后。
|
||||||
// iframe / 分享页的 Referer 保持原主机,不把页面 GET 改写到 wwww。
|
// iframe / 分享页的 Referer 保持原主机,不把页面 GET 改写到 wwww。
|
||||||
String page = referer != null && !referer.isBlank() ? referer : resolveShareUrl();
|
String page = referer != null && !referer.isBlank() ? referer : resolveShareUrl();
|
||||||
|
headers.set("referer", page);
|
||||||
String target = call.absoluteUrl() != null ? call.absoluteUrl() : call.path();
|
String target = call.absoluteUrl() != null ? call.absoluteUrl() : call.path();
|
||||||
MultiMap headers = fileAjaxHeaders(page, target);
|
|
||||||
postAjaxAt(fileAjaxOrigins(page, target), 0, call, headers, this::handleAjaxDownResponse, null);
|
postAjaxAt(fileAjaxOrigins(page, target), 0, call, headers, this::handleAjaxDownResponse, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1135,7 +1075,7 @@ public class LzTool extends PanBase {
|
|||||||
private static String originOf(String url, String fallback) {
|
private static String originOf(String url, String fallback) {
|
||||||
try {
|
try {
|
||||||
URL u = new URL(url);
|
URL u = new URL(url);
|
||||||
return u.getProtocol() + "://" + u.getHost() + (u.getPort() == -1 ? "" : ":" + u.getPort());
|
return u.getProtocol() + "://" + u.getHost();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
@@ -1187,14 +1127,6 @@ public class LzTool extends PanBase {
|
|||||||
complete(downloadUrl);
|
complete(downloadUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 目录分享页和 filemoreajax.php 都用移动端 UA。文件页仍走桌面 UA,才能拿到 iframe。 */
|
|
||||||
private static MultiMap folderPageHeaders(String referer) {
|
|
||||||
MultiMap headers = folderListHeaders(referer);
|
|
||||||
headers.set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
|
|
||||||
headers.set("Accept-Encoding", "identity");
|
|
||||||
return headers;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 目录列表 filemoreajax.php 用移动端 UA。 */
|
/** 目录列表 filemoreajax.php 用移动端 UA。 */
|
||||||
private static MultiMap folderListHeaders(String referer) {
|
private static MultiMap folderListHeaders(String referer) {
|
||||||
MultiMap headers = MultiMap.caseInsensitiveMultiMap();
|
MultiMap headers = MultiMap.caseInsensitiveMultiMap();
|
||||||
@@ -1214,77 +1146,18 @@ public class LzTool extends PanBase {
|
|||||||
|
|
||||||
final String sUrl = resolveShareUrl();
|
final String sUrl = resolveShareUrl();
|
||||||
final String pwd = shareLinkInfo.getSharePassword();
|
final String pwd = shareLinkInfo.getSharePassword();
|
||||||
final int page;
|
|
||||||
try {
|
|
||||||
page = FolderPaging.pageOrFirst(shareLinkInfo);
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
listPromise.fail(baseMsg() + e.getMessage());
|
|
||||||
return listPromise.future();
|
|
||||||
}
|
|
||||||
|
|
||||||
LzFolderCursor cursor = page > 1
|
getWithArg1Retry(sUrl, PAGE_HEADERS)
|
||||||
? LzFolderCursor.decode(FolderPaging.cursor(shareLinkInfo), shareLinkInfo.getShareKey(), page)
|
.onSuccess(html -> handleFileListParse(html, pwd, sUrl, listPromise))
|
||||||
: null;
|
.onFailure(listPromise::fail);
|
||||||
if (cursor == null) {
|
|
||||||
if (page > LZ_MAX_WALK_PAGES) {
|
|
||||||
listPromise.fail(baseMsg() + walkLimitMessage(page));
|
|
||||||
return listPromise.future();
|
|
||||||
}
|
|
||||||
loadFolderPage(sUrl, pwd, page, listPromise);
|
|
||||||
return listPromise.future();
|
|
||||||
}
|
|
||||||
if (cursor.webpage != null) {
|
|
||||||
shareLinkInfo.getOtherParam().put("webpage", cursor.webpage);
|
|
||||||
}
|
|
||||||
AjaxCall call = new AjaxCall(cursor.path, cursor.formFor(pwd, page));
|
|
||||||
postFolderPage(sUrl, call, page, 0, reply -> {
|
|
||||||
if (reply.zt() == 1) {
|
|
||||||
finishFolderPage(call, page, reply, listPromise);
|
|
||||||
} else if (reply.zt() == 2) {
|
|
||||||
finishEmptyFolderPage(page, listPromise);
|
|
||||||
} else if (reply.zt() == LZ_ZT_REFRESH) {
|
|
||||||
fallbackFromCursor(sUrl, pwd, page, reply.info(), listPromise);
|
|
||||||
} else {
|
|
||||||
listPromise.tryFail(baseMsg() + "蓝奏云目录第 " + page + " 页获取失败: " + reply.info());
|
|
||||||
}
|
|
||||||
}, err -> fallbackFromCursor(sUrl, pwd, page, err.getMessage(), listPromise));
|
|
||||||
return listPromise.future();
|
return listPromise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 游标过期(令牌约 10 分钟)或被拒:页码不大时整段重翻,否则让调用方从第 1 页重新加载。 */
|
private void handleFileListParse(String html, String pwd, String sUrl, Promise<List<FileInfo>> listPromise) {
|
||||||
private void fallbackFromCursor(String sUrl, String pwd, int page, String reason,
|
|
||||||
Promise<List<FileInfo>> listPromise) {
|
|
||||||
log.debug("蓝奏目录游标不可用 page={} reason={}", page, reason);
|
|
||||||
if (page > LZ_MAX_WALK_PAGES) {
|
|
||||||
listPromise.tryFail(baseMsg() + "蓝奏云目录分页游标已失效(" + reason + "),请从第 1 页重新加载");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
loadFolderPage(sUrl, pwd, page, listPromise);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String walkLimitMessage(int page) {
|
|
||||||
return "蓝奏云目录需按顺序翻页:第 " + page + " 页请带上一页返回的 nextCursor 请求"
|
|
||||||
+ "(无游标最多直接取到第 " + LZ_MAX_WALK_PAGES + " 页)";
|
|
||||||
}
|
|
||||||
|
|
||||||
private void loadFolderPage(String sUrl, String pwd, int page, Promise<List<FileInfo>> listPromise) {
|
|
||||||
// 目录页用移动端 UA。桌面 Chrome 访问旧目录(如 /b66477)常返回空白风控页,
|
|
||||||
// 页面里没有 filemoreajax,随后会被误报成「获取失败1,可能分享已失效」。
|
|
||||||
getWithArg1Retry(sUrl, folderPageHeaders(sUrl))
|
|
||||||
.onSuccess(html -> handleFileListParse(html, pwd, sUrl, page, listPromise))
|
|
||||||
.onFailure(listPromise::fail);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void handleFileListParse(String html, String pwd, String sUrl, int page,
|
|
||||||
Promise<List<FileInfo>> listPromise) {
|
|
||||||
if (!isLzFolderShare(sUrl, html)) {
|
if (!isLzFolderShare(sUrl, html)) {
|
||||||
listPromise.fail(baseMsg() + "该链接为蓝奏云文件分享,请使用文件解析接口");
|
listPromise.fail(baseMsg() + "该链接为蓝奏云文件分享,请使用文件解析接口");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (isAccessRiskPage(html)) {
|
|
||||||
listPromise.fail(baseMsg() + "蓝奏云返回了访问风控页,不能据此判断分享已失效,请稍后重试");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
String webpage = extractWebpage(sUrl, html);
|
String webpage = extractWebpage(sUrl, html);
|
||||||
if (webpage != null) {
|
if (webpage != null) {
|
||||||
@@ -1296,106 +1169,14 @@ public class LzTool extends PanBase {
|
|||||||
}
|
}
|
||||||
log.debug("解析参数: {}", call.form());
|
log.debug("解析参数: {}", call.form());
|
||||||
|
|
||||||
walkFolderPages(sUrl, call, 1, page, listPromise);
|
postAjaxWithFallback(sUrl, call, folderListHeaders(sUrl),
|
||||||
|
body -> handleFileListResponse(body, listPromise),
|
||||||
|
listPromise::fail);
|
||||||
} catch (ScriptException | NoSuchMethodException | RuntimeException e) {
|
} catch (ScriptException | NoSuchMethodException | RuntimeException e) {
|
||||||
listPromise.fail(e);
|
listPromise.fail(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 同一组 t/k 从第 {@code pg} 页顺序翻到 {@code target} 页。新令牌不能跳页,
|
|
||||||
* 两次请求间隔不足约 1.5 秒会返回 zt=4,所以逐页间隔 {@link #LZ_PAGE_INTERVAL_MS};
|
|
||||||
* 次数受 {@link #LZ_MAX_WALK_PAGES} 限制。
|
|
||||||
*/
|
|
||||||
private void walkFolderPages(String sUrl, AjaxCall call, int pg, int target,
|
|
||||||
Promise<List<FileInfo>> listPromise) {
|
|
||||||
postFolderPage(sUrl, call, pg, 0, reply -> {
|
|
||||||
if (reply.zt() == 1) {
|
|
||||||
if (pg == target) {
|
|
||||||
finishFolderPage(call, target, reply, listPromise);
|
|
||||||
} else if (reply.rawCount() < LZ_FOLDER_PAGE_SIZE) {
|
|
||||||
finishEmptyFolderPage(target, listPromise);
|
|
||||||
} else {
|
|
||||||
WebClientVertxInit.get().setTimer(LZ_PAGE_INTERVAL_MS,
|
|
||||||
id -> walkFolderPages(sUrl, call, pg + 1, target, listPromise));
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (target == 1) {
|
|
||||||
listPromise.tryFail(baseMsg() + reply.info());
|
|
||||||
} else if (reply.zt() == 2) {
|
|
||||||
finishEmptyFolderPage(target, listPromise);
|
|
||||||
} else {
|
|
||||||
listPromise.tryFail(baseMsg() + "蓝奏云目录第 " + pg + " 页获取失败: " + reply.info()
|
|
||||||
+ ";未取到第 " + target + " 页,目录列表不完整,请稍后重试");
|
|
||||||
}
|
|
||||||
}, listPromise::tryFail);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 取一页;zt=4(请求过快)时同一令牌等一会儿重试,最多 {@link #LZ_REFRESH_RETRIES} 次。 */
|
|
||||||
private void postFolderPage(String sUrl, AjaxCall call, int pg, int attempt,
|
|
||||||
Handler<FolderReply> onReply, Handler<Throwable> onFailure) {
|
|
||||||
call.form().put("pg", String.valueOf(pg));
|
|
||||||
postAjaxWithFallback(sUrl, call, folderListHeaders(sUrl), body -> {
|
|
||||||
FolderReply reply = FolderReply.parse(body);
|
|
||||||
if (reply == null) {
|
|
||||||
onFailure.handle(new RuntimeException(baseMsg() + "目录列表返回非JSON"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (reply.zt() == LZ_ZT_REFRESH && attempt < LZ_REFRESH_RETRIES) {
|
|
||||||
long delay = LZ_REFRESH_RETRY_DELAYS_MS[attempt];
|
|
||||||
log.debug("蓝奏目录第 {} 页返回 {},{}ms 后重试", pg, reply.info(), delay);
|
|
||||||
WebClientVertxInit.get().setTimer(delay,
|
|
||||||
id -> postFolderPage(sUrl, call, pg, attempt + 1, onReply, onFailure));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
onReply.handle(reply);
|
|
||||||
}, onFailure);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void finishEmptyFolderPage(int page, Promise<List<FileInfo>> listPromise) {
|
|
||||||
FolderPaging.pageInfo(shareLinkInfo, page, LZ_FOLDER_PAGE_SIZE, false, null, null, null);
|
|
||||||
listPromise.tryComplete(new ArrayList<>());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void finishFolderPage(AjaxCall call, int page, FolderReply reply, Promise<List<FileInfo>> listPromise) {
|
|
||||||
try {
|
|
||||||
List<FileInfo> list = toFolderFileInfos(reply.items());
|
|
||||||
boolean hasMore = reply.rawCount() >= LZ_FOLDER_PAGE_SIZE;
|
|
||||||
String next = hasMore
|
|
||||||
? LzFolderCursor.encode(shareLinkInfo.getShareKey(), call.path(), call.form(), page + 1,
|
|
||||||
currentWebpage())
|
|
||||||
: null;
|
|
||||||
FolderPaging.pageInfo(shareLinkInfo, page, LZ_FOLDER_PAGE_SIZE, hasMore, null, null, next);
|
|
||||||
listPromise.tryComplete(list);
|
|
||||||
} catch (Exception e) {
|
|
||||||
listPromise.tryFail(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** filemoreajax.php 单页响应;text 不是数组时 items 为空。 */
|
|
||||||
record FolderReply(int zt, String info, List<JsonObject> items, int rawCount) {
|
|
||||||
static FolderReply parse(String body) {
|
|
||||||
JsonObject json = parseLzJson(body);
|
|
||||||
if (json == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
Integer zt = jsonInt(json, "zt");
|
|
||||||
Object info = json.getValue("info");
|
|
||||||
List<JsonObject> items = new ArrayList<>();
|
|
||||||
Object text = json.getValue("text");
|
|
||||||
if (text instanceof JsonArray arr) {
|
|
||||||
for (Object o : arr) {
|
|
||||||
if (o instanceof JsonObject item) {
|
|
||||||
items.add(item);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return new FolderReply(zt == null ? -1 : zt, info == null ? null : String.valueOf(info),
|
|
||||||
items, items.size());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 正则匹配不到 filemoreajax 块时,回退到执行页面 JS 取参数。 */
|
/** 正则匹配不到 filemoreajax 块时,回退到执行页面 JS 取参数。 */
|
||||||
private AjaxCall folderAjaxFromJs(String html, String pwd) throws ScriptException, NoSuchMethodException {
|
private AjaxCall folderAjaxFromJs(String html, String pwd) throws ScriptException, NoSuchMethodException {
|
||||||
String jsText = getJsByPwd(pwd, html, "var urls =window.location.href");
|
String jsText = getJsByPwd(pwd, html, "var urls =window.location.href");
|
||||||
@@ -1432,26 +1213,6 @@ public class LzTool extends PanBase {
|
|||||||
return path.charAt(0) == 'b' || path.charAt(0) == 'B';
|
return path.charAt(0) == 'b' || path.charAt(0) == 'B';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 桌面 UA 下的空白提示页:有 off1,隐藏块里是 folder 编号和访问 IP,没有取消分享文案,
|
|
||||||
* 也没有目录参数。这是访问风控,不是分享失效。
|
|
||||||
*/
|
|
||||||
static boolean isAccessRiskPage(String html) {
|
|
||||||
if (html == null || html.isBlank()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (html.contains("filemoreajax") || html.contains(ARG1_MARK)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!html.contains("off1")) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (html.contains("取消分享") || html.contains("不存在") || html.contains("地址错误")) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return html.contains("folder") && html.contains("ip");
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean isLzFolderHtml(String html) {
|
private static boolean isLzFolderHtml(String html) {
|
||||||
if (html == null || html.isBlank()) {
|
if (html == null || html.isBlank()) {
|
||||||
return false;
|
return false;
|
||||||
@@ -1488,59 +1249,66 @@ public class LzTool extends PanBase {
|
|||||||
return u;
|
return u;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private void handleFileListResponse(String responseBody, Promise<List<FileInfo>> listPromise) {
|
||||||
* 目录页 JS 不渲染 id 为 -1 的占位项(如「***.apk」),这里同样跳过;它仍计入每页 50 条。
|
try {
|
||||||
* 同一页里重复的 id 只保留第一条。
|
JsonObject fileListJson = parseLzJson(responseBody);
|
||||||
*/
|
if (fileListJson == null) {
|
||||||
private List<FileInfo> toFolderFileInfos(List<JsonObject> items) {
|
listPromise.fail(baseMsg() + "目录列表返回非JSON");
|
||||||
List<FileInfo> list = new ArrayList<>();
|
return;
|
||||||
Set<String> seen = new HashSet<>();
|
|
||||||
for (JsonObject fileJson : items) {
|
|
||||||
/*
|
|
||||||
{
|
|
||||||
"icon": "apk",
|
|
||||||
"t": 0,
|
|
||||||
"id": "iULV2n4361c",
|
|
||||||
"name_all": "xx.apk",
|
|
||||||
"size": "49.8 M",
|
|
||||||
"time": "2021-03-19",
|
|
||||||
"duan": "in4361",
|
|
||||||
"p_ico": 0
|
|
||||||
}
|
}
|
||||||
*/
|
Integer zt = fileListJson.getInteger("zt");
|
||||||
String id = fileJson.getString("id");
|
if (zt == null || zt != 1) {
|
||||||
if (id == null || id.isBlank() || LZ_PLACEHOLDER_ID.equals(id) || !seen.add(id)) {
|
listPromise.fail(baseMsg() + fileListJson.getString("info"));
|
||||||
continue;
|
return;
|
||||||
}
|
}
|
||||||
FileInfo fileInfo = new FileInfo();
|
List<FileInfo> list = new ArrayList<>();
|
||||||
String size = fileJson.getString("size");
|
fileListJson.getJsonArray("text").forEach(item -> {
|
||||||
Long sizeNum = FileSizeConverter.convertToBytes(size);
|
/*
|
||||||
String panType = shareLinkInfo.getType();
|
{
|
||||||
String fileName = fileJson.getString("name_all");
|
"icon": "apk",
|
||||||
// 构建 base64 参数,用于 /v2/redirectUrl 接口
|
"t": 0,
|
||||||
JsonObject paramJson = new JsonObject()
|
"id": "iULV2n4361c",
|
||||||
.put("id", id)
|
"name_all": "xx.apk",
|
||||||
.put("fileName", fileName)
|
"size": "49.8 M",
|
||||||
.put("shareKey", shareLinkInfo.getShareKey());
|
"time": "2021-03-19",
|
||||||
String webpage = currentWebpage();
|
"duan": "in4361",
|
||||||
if (webpage != null) {
|
"p_ico": 0
|
||||||
paramJson.put("webpage", webpage);
|
}
|
||||||
}
|
*/
|
||||||
String param = CommonUtils.urlBase64Encode(paramJson.encode());
|
JsonObject fileJson = (JsonObject) item;
|
||||||
fileInfo.setFileName(fileName)
|
FileInfo fileInfo = new FileInfo();
|
||||||
.setFileId(id)
|
String size = fileJson.getString("size");
|
||||||
.setCreateTime(fileJson.getString("time"))
|
Long sizeNum = FileSizeConverter.convertToBytes(size);
|
||||||
.setFileType(fileJson.getString("icon"))
|
String panType = shareLinkInfo.getType();
|
||||||
.setSizeStr(fileJson.getString("size"))
|
String id = fileJson.getString("id");
|
||||||
.setSize(sizeNum)
|
String fileName = fileJson.getString("name_all");
|
||||||
.setPanType(panType)
|
// 构建 base64 参数,用于 /v2/redirectUrl 接口
|
||||||
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(), panType, param))
|
JsonObject paramJson = new JsonObject()
|
||||||
.setPreviewUrl(String.format("%s/v2/view/%s/%s", getDomainName(),
|
.put("id", id)
|
||||||
shareLinkInfo.getType(), id));
|
.put("fileName", fileName)
|
||||||
log.debug("文件信息: {}", fileInfo);
|
.put("shareKey", shareLinkInfo.getShareKey());
|
||||||
list.add(fileInfo);
|
String webpage = currentWebpage();
|
||||||
|
if (webpage != null) {
|
||||||
|
paramJson.put("webpage", webpage);
|
||||||
|
}
|
||||||
|
String param = CommonUtils.urlBase64Encode(paramJson.encode());
|
||||||
|
fileInfo.setFileName(fileName)
|
||||||
|
.setFileId(id)
|
||||||
|
.setCreateTime(fileJson.getString("time"))
|
||||||
|
.setFileType(fileJson.getString("icon"))
|
||||||
|
.setSizeStr(fileJson.getString("size"))
|
||||||
|
.setSize(sizeNum)
|
||||||
|
.setPanType(panType)
|
||||||
|
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(), panType, param))
|
||||||
|
.setPreviewUrl(String.format("%s/v2/view/%s/%s", getDomainName(),
|
||||||
|
shareLinkInfo.getType(), id));
|
||||||
|
log.debug("文件信息: {}", fileInfo);
|
||||||
|
list.add(fileInfo);
|
||||||
|
});
|
||||||
|
listPromise.complete(list);
|
||||||
|
} catch (Exception e) {
|
||||||
|
listPromise.fail(e);
|
||||||
}
|
}
|
||||||
return list;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -32,12 +32,8 @@ import java.util.zip.CRC32;
|
|||||||
import static cn.qaiu.util.RandomStringGenerator.gen36String;
|
import static cn.qaiu.util.RandomStringGenerator.gen36String;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 123盘解析器。
|
* 123盘解析器 v2 - 使用Android平台API
|
||||||
* 分享单文件走分享域名:先 POST /api/share/download/traffic/check,
|
* 支持账号密码或token配置
|
||||||
* 再 POST /api/v2/share/download/info。platform web,App-Version 149。
|
|
||||||
* 域名只由 shareKey 解码出的数字 uid 组成,不使用调用方提供的任意 host。
|
|
||||||
* 文件夹打包下载仍走 App-Version 55 的 batch_download_share_info。
|
|
||||||
* 支持账号密码或 token 配置。
|
|
||||||
*
|
*
|
||||||
* @author <a href="https://qaiu.top">QAIU</a>
|
* @author <a href="https://qaiu.top">QAIU</a>
|
||||||
*/
|
*/
|
||||||
@@ -45,13 +41,9 @@ public class Ye2Tool extends PanBase {
|
|||||||
|
|
||||||
private static final String API_BASE = "https://api.123278.com";
|
private static final String API_BASE = "https://api.123278.com";
|
||||||
private static final String GET_SHARE_INFO_URL = API_BASE + "/b/api/share/get?limit=100&next=1&orderBy=share_id&orderDirection=desc&shareKey={shareKey}&SharePwd={pwd}&ParentFileId={ParentFileId}&Page=1";
|
private static final String GET_SHARE_INFO_URL = API_BASE + "/b/api/share/get?limit=100&next=1&orderBy=share_id&orderDirection=desc&shareKey={shareKey}&SharePwd={pwd}&ParentFileId={ParentFileId}&Page=1";
|
||||||
/** 分享页脚本把 /share/download/traffic/check 加上 /api 前缀,发到当前分享域名。 */
|
private static final String DOWNLOAD_API_URL = API_BASE + "/b/api/file/download_info";
|
||||||
static final String SHARE_TRAFFIC_CHECK_PATH = "/api/share/download/traffic/check";
|
private static final String DOWNLOAD_API_V2_BASE = "https://api.123278.com";
|
||||||
/** 分享页脚本把 /v2/share/download/info 加上 /api 前缀,不是 api.123278.com/b/api。 */
|
private static final String DOWNLOAD_API_V2_PATH = "/b/api/v2/share/download/info";
|
||||||
static final String SHARE_DOWNLOAD_INFO_PATH = "/api/v2/share/download/info";
|
|
||||||
static final String SHARE_PLATFORM = "web";
|
|
||||||
/** 当前分享页静态资源里的 App-Version。个人文件接口 App-Version 55 会返回 5066。 */
|
|
||||||
static final String SHARE_WEB_APP_VERSION = "149";
|
|
||||||
private static final String BATCH_DOWNLOAD_API_URL = API_BASE + "/b/api/file/batch_download_share_info";
|
private static final String BATCH_DOWNLOAD_API_URL = API_BASE + "/b/api/file/batch_download_share_info";
|
||||||
private static final String LOGIN_URL = "https://login.123pan.com/api/user/sign_in";
|
private static final String LOGIN_URL = "https://login.123pan.com/api/user/sign_in";
|
||||||
|
|
||||||
@@ -134,25 +126,28 @@ public class Ye2Tool extends PanBase {
|
|||||||
return TokenCache.isExpired(cacheKey);
|
return TokenCache.isExpired(cacheKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String crc32(String data) {
|
||||||
|
CRC32 crc32 = new CRC32();
|
||||||
|
crc32.update(data.getBytes());
|
||||||
|
long value = crc32.getValue();
|
||||||
|
return String.format("%08x", value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private long hexToInt(String hexStr) {
|
||||||
|
return Long.parseLong(hexStr, 16);
|
||||||
|
}
|
||||||
|
|
||||||
private String encode123(String url, String way, String version, String timestamp) {
|
private String encode123(String url, String way, String version, String timestamp) {
|
||||||
return signQuery(url, way, version, Long.parseLong(timestamp), nextSignRandom());
|
Random random = new Random();
|
||||||
}
|
int randomInt = random.nextInt(10000000) + 1;
|
||||||
|
long a = (10000000L * randomInt) / 10000;
|
||||||
|
|
||||||
private static long nextSignRandom() {
|
long timeLong = Long.parseLong(timestamp) / 1000;
|
||||||
int randomInt = new Random().nextInt(10000000) + 1;
|
|
||||||
return (10000000L * randomInt) / 10000;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 签名原文:unix秒|随机数|实际路径|platform|App-Version|时间混淆值。
|
|
||||||
* 分享下载的路径是 /api/...,platform 是 web,版本是 149。
|
|
||||||
*/
|
|
||||||
static String signMaterial(String url, String way, String version, long timeMillis, long randomA) {
|
|
||||||
long timeLong = timeMillis / 1000;
|
|
||||||
java.time.LocalDateTime dateTime = java.time.Instant.ofEpochSecond(timeLong)
|
java.time.LocalDateTime dateTime = java.time.Instant.ofEpochSecond(timeLong)
|
||||||
.atZone(java.time.ZoneId.systemDefault())
|
.atZone(java.time.ZoneId.systemDefault())
|
||||||
.toLocalDateTime();
|
.toLocalDateTime();
|
||||||
String timeStr = dateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
|
String timeStr = dateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
|
||||||
|
|
||||||
StringBuilder g = new StringBuilder();
|
StringBuilder g = new StringBuilder();
|
||||||
for (char c : timeStr.toCharArray()) {
|
for (char c : timeStr.toCharArray()) {
|
||||||
int digit = Character.getNumericValue(c);
|
int digit = Character.getNumericValue(c);
|
||||||
@@ -162,22 +157,11 @@ public class Ye2Tool extends PanBase {
|
|||||||
g.append(CHAR_MAP.charAt(digit - 1));
|
g.append(CHAR_MAP.charAt(digit - 1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
String y = String.valueOf(crc32Decimal(g.toString()));
|
|
||||||
return timeLong + "|" + randomA + "|" + url + "|" + way + "|" + version + "|" + y;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String signQuery(String url, String way, String version, long timeMillis, long randomA) {
|
String y = String.valueOf(hexToInt(crc32(g.toString())));
|
||||||
String material = signMaterial(url, way, version, timeMillis, randomA);
|
String finalCrcInput = String.format("%d|%d|%s|%s|%s|%s", timeLong, a, url, way, version, y);
|
||||||
String y = material.substring(material.lastIndexOf('|') + 1);
|
String finalCrc = String.valueOf(hexToInt(crc32(finalCrcInput)));
|
||||||
long timeLong = timeMillis / 1000;
|
return String.format("?%s=%d-%d-%s", y, timeLong, a, finalCrc);
|
||||||
String finalCrc = String.valueOf(crc32Decimal(material));
|
|
||||||
return "?" + y + "=" + timeLong + "-" + randomA + "-" + finalCrc;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static long crc32Decimal(String data) {
|
|
||||||
CRC32 crc32 = new CRC32();
|
|
||||||
crc32.update(data.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
|
||||||
return crc32.getValue();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
@@ -226,14 +210,15 @@ public class Ye2Tool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
JsonObject fileInfo = data.getJsonArray("InfoList").getJsonObject(0);
|
JsonObject fileInfo = data.getJsonArray("InfoList").getJsonObject(0);
|
||||||
|
if (token.equals("nologin")) {
|
||||||
|
fail(loginRequiredDownloadMessage(false, null));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (fileInfo.getInteger("Type", 0) == 1) {
|
if (fileInfo.getInteger("Type", 0) == 1) {
|
||||||
if (!hasUsableToken(token)) {
|
|
||||||
fail(loginRequiredDownloadMessage(false, null));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
getZipDownUrl(client, fileInfo);
|
getZipDownUrl(client, fileInfo);
|
||||||
} else {
|
} else {
|
||||||
getDownUrl(fileInfo, token);
|
getDownUrl(client, fileInfo);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.onFailure(this.handleFail(GET_SHARE_INFO_URL));
|
.onFailure(this.handleFail(GET_SHARE_INFO_URL));
|
||||||
@@ -332,55 +317,112 @@ public class Ye2Tool extends PanBase {
|
|||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private void getDownUrl(WebClient client, JsonObject fileInfo) {
|
||||||
* 分享单文件:流量预检通过后走分享域名 v2。不回退个人文件接口,也不创建订单。
|
|
||||||
*/
|
|
||||||
private void getDownUrl(JsonObject fileInfo, String token) {
|
|
||||||
setFileInfo(fileInfo);
|
setFileInfo(fileInfo);
|
||||||
|
|
||||||
String normalizedShareKey = YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey());
|
String normalizedShareKey = YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey());
|
||||||
applyResolvedShareKey(shareLinkInfo, normalizedShareKey);
|
if (StringUtils.isNotEmpty(normalizedShareKey)) {
|
||||||
Integer fileId = fileInfo.getInteger("FileId");
|
JsonObject v2Body = new JsonObject()
|
||||||
if (!usableShareKey(normalizedShareKey) || fileId == null) {
|
.put("ShareKey", normalizedShareKey)
|
||||||
fail("123网盘公开下载参数缺少分享标识");
|
.put("FileID", fileInfo.getInteger("FileId"))
|
||||||
|
.put("S3keyFlag", fileInfo.getString("S3KeyFlag"))
|
||||||
|
.put("Size", fileInfo.getLong("Size"))
|
||||||
|
.put("Etag", fileInfo.getString("Etag"));
|
||||||
|
requestShareV2Download(normalizedShareKey, v2Body).onSuccess(v2Url -> {
|
||||||
|
if (StringUtils.isNotEmpty(v2Url)) {
|
||||||
|
complete(v2Url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
requestLegacyDownUrl(client, fileInfo);
|
||||||
|
}).onFailure(err -> {
|
||||||
|
log.warn("Ye2 v2分享下载接口失败,回退旧接口: {}", err.getMessage());
|
||||||
|
requestLegacyDownUrl(client, fileInfo);
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
long size = fileInfo.getLong("Size") == null ? 0L : fileInfo.getLong("Size");
|
|
||||||
requestShareDownload(normalizedShareKey, fileId, fileInfo.getString("S3KeyFlag"), size,
|
requestLegacyDownUrl(client, fileInfo);
|
||||||
fileInfo.getString("Etag"), token).onSuccess(this::complete)
|
|
||||||
.onFailure(err -> fail(err.getMessage()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Future<String> requestShareDownload(String shareKey, long fileId, String s3keyFlag, long size,
|
private void requestLegacyDownUrl(WebClient client, JsonObject fileInfo) {
|
||||||
String etag, String token) {
|
JsonObject jsonObject = new JsonObject();
|
||||||
return executeShareFileDownload(this::postShareJson, new ShareFileRequest(
|
jsonObject.put("driveId", 0);
|
||||||
shareLinkInfo.getShareUrl(),
|
jsonObject.put("etag", fileInfo.getString("Etag"));
|
||||||
shareLinkInfo.getStandardUrl(),
|
jsonObject.put("fileId", fileInfo.getInteger("FileId"));
|
||||||
shareKey,
|
jsonObject.put("fileName", fileInfo.getString("FileName"));
|
||||||
shareLinkInfo.getSharePassword(),
|
jsonObject.put("s3keyFlag", fileInfo.getString("S3KeyFlag"));
|
||||||
fileId,
|
jsonObject.put("size", fileInfo.getLong("Size"));
|
||||||
s3keyFlag,
|
jsonObject.put("type", 0);
|
||||||
size,
|
|
||||||
etag,
|
String timestamp = String.valueOf(System.currentTimeMillis());
|
||||||
token,
|
String encryptedParams = encode123("/b/api/file/download_info", "android", "55", timestamp);
|
||||||
System.currentTimeMillis(),
|
String apiUrl = DOWNLOAD_API_URL + encryptedParams;
|
||||||
nextSignRandom()));
|
|
||||||
|
log.info("Ye2 API URL: {}", apiUrl);
|
||||||
|
|
||||||
|
HttpRequest<Buffer> bufferHttpRequest = client.postAbs(apiUrl);
|
||||||
|
bufferHttpRequest.putHeader("platform", "android");
|
||||||
|
bufferHttpRequest.putHeader("App-Version", "55");
|
||||||
|
bufferHttpRequest.putHeader("Authorization", "Bearer " + TokenCache.getToken(cacheKey));
|
||||||
|
bufferHttpRequest.putHeader("User-Agent", "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36");
|
||||||
|
bufferHttpRequest.putHeader("Content-Type", "application/json");
|
||||||
|
|
||||||
|
bufferHttpRequest
|
||||||
|
.sendJsonObject(jsonObject)
|
||||||
|
.onSuccess(res2 -> handleDownloadUrlResponse(client, asJson(res2), "Ye2"))
|
||||||
|
.onFailure(err -> fail("下载接口失败: " + err.getMessage()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Future<JsonObject> postShareJson(ShareHttpCall call) {
|
private Future<String> requestShareV2Download(String shareKey, JsonObject body) {
|
||||||
Promise<JsonObject> promise = Promise.promise();
|
Promise<String> promise = Promise.promise();
|
||||||
HttpRequest<Buffer> request = client.postAbs(call.url());
|
String timestamp = String.valueOf(System.currentTimeMillis());
|
||||||
call.headers.forEach(entry -> request.putHeader(entry.getKey(), entry.getValue()));
|
String encryptedParams = encode123(DOWNLOAD_API_V2_PATH, "web", "3", timestamp);
|
||||||
request.sendJsonObject(call.body)
|
String apiUrl = DOWNLOAD_API_V2_BASE + DOWNLOAD_API_V2_PATH + encryptedParams;
|
||||||
.onSuccess(resp -> promise.complete(asJson(resp)))
|
String shareOrigin = resolveYeShareOrigin(shareKey);
|
||||||
.onFailure(promise::fail);
|
String shareReferer = buildShareReferer(shareOrigin, shareKey, shareLinkInfo.getSharePassword());
|
||||||
|
|
||||||
|
HttpRequest<Buffer> request = client.postAbs(apiUrl);
|
||||||
|
request.putHeader("Accept", "*/*");
|
||||||
|
request.putHeader("Authorization", "Bearer " + TokenCache.getToken(cacheKey));
|
||||||
|
request.putHeader("App-Version", "3");
|
||||||
|
request.putHeader("platform", "web");
|
||||||
|
request.putHeader("Origin", shareOrigin);
|
||||||
|
request.putHeader("Referer", shareReferer);
|
||||||
|
request.putHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36");
|
||||||
|
request.putHeader("Content-Type", "application/json;charset=UTF-8");
|
||||||
|
|
||||||
|
request.sendJsonObject(body).onSuccess(resp -> {
|
||||||
|
JsonObject json = asJson(resp);
|
||||||
|
if (json == null || json.getInteger("code", -1) != 0) {
|
||||||
|
promise.fail("v2接口返回异常: " + (json == null ? "null" : json.encode()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JsonObject data = json.getJsonObject("data", new JsonObject());
|
||||||
|
JsonArray dispatchList = data.getJsonArray("dispatchList", new JsonArray());
|
||||||
|
String downloadPath = data.getString("downloadPath");
|
||||||
|
if (StringUtils.isBlank(downloadPath)) {
|
||||||
|
promise.complete("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String prefix = "";
|
||||||
|
if (dispatchList.size() > 0) {
|
||||||
|
JsonObject firstDispatch = dispatchList.getJsonObject(0);
|
||||||
|
if (firstDispatch != null) {
|
||||||
|
prefix = firstDispatch.getString("prefix", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (StringUtils.isBlank(prefix)) {
|
||||||
|
promise.complete(downloadPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String finalUrl = prefix.endsWith("/") ? prefix.substring(0, prefix.length() - 1) : prefix;
|
||||||
|
finalUrl += downloadPath.startsWith("/") ? downloadPath : "/" + downloadPath;
|
||||||
|
promise.complete(finalUrl);
|
||||||
|
}).onFailure(promise::fail);
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 文件夹打包下载仍使用 App-Version 55 的 /b/api/file/batch_download_share_info。
|
|
||||||
* 分享页脚本已改走 /v2/file/batch_download_share_info,这次不改这条路径。
|
|
||||||
*/
|
|
||||||
private void getZipDownUrl(WebClient client, JsonObject fileInfo) {
|
private void getZipDownUrl(WebClient client, JsonObject fileInfo) {
|
||||||
JsonObject jsonObject = new JsonObject();
|
JsonObject jsonObject = new JsonObject();
|
||||||
jsonObject.put("shareKey", YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey()));
|
jsonObject.put("shareKey", YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey()));
|
||||||
@@ -649,322 +691,76 @@ public class Ye2Tool extends PanBase {
|
|||||||
Future<String> tokenFuture = resolveTokenFuture();
|
Future<String> tokenFuture = resolveTokenFuture();
|
||||||
|
|
||||||
tokenFuture.onSuccess(token -> {
|
tokenFuture.onSuccess(token -> {
|
||||||
if (hasUsableToken(token)) {
|
if (token.equals("nologin")) {
|
||||||
TokenCache.putToken(cacheKey, token);
|
fail(loginRequiredDownloadMessage(false, null));
|
||||||
}
|
|
||||||
String normalizedShareKey = resolveDownloadShareKey(paramJson, shareLinkInfo.getShareKey());
|
|
||||||
applyResolvedShareKey(shareLinkInfo, normalizedShareKey);
|
|
||||||
if (!usableShareKey(normalizedShareKey)) {
|
|
||||||
fail("123网盘公开下载参数缺少分享标识");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
long fileId = paramJson.getLong("fileId", paramJson.getLong("FileID", 0L));
|
|
||||||
String s3keyFlag = firstNonBlank(paramJson, "s3keyFlag", "S3keyFlag", "S3KeyFlag");
|
String rawShareKey = paramJson.getString("shareKey");
|
||||||
long size = paramJson.getLong("size", paramJson.getLong("Size", 0L));
|
if (StringUtils.isBlank(rawShareKey)) {
|
||||||
String etag = firstNonBlank(paramJson, "etag", "Etag");
|
rawShareKey = paramJson.getString("ShareKey");
|
||||||
requestShareDownload(normalizedShareKey, fileId, s3keyFlag, size, etag, token)
|
}
|
||||||
.onSuccess(this::complete)
|
if (StringUtils.isBlank(rawShareKey)) {
|
||||||
.onFailure(err -> fail(err.getMessage()));
|
rawShareKey = shareLinkInfo.getShareKey();
|
||||||
|
}
|
||||||
|
String normalizedShareKey = YeShareHostUtil.normalizeShareKey(rawShareKey);
|
||||||
|
if (StringUtils.isNotEmpty(normalizedShareKey)) {
|
||||||
|
JsonObject v2Body = new JsonObject()
|
||||||
|
.put("ShareKey", normalizedShareKey)
|
||||||
|
.put("FileID", paramJson.getInteger("fileId", paramJson.getInteger("FileID", 0)))
|
||||||
|
.put("S3keyFlag", paramJson.getString("s3keyFlag", paramJson.getString("S3keyFlag", "")))
|
||||||
|
.put("Size", paramJson.getLong("size", paramJson.getLong("Size", 0L)))
|
||||||
|
.put("Etag", paramJson.getString("etag", paramJson.getString("Etag", "")));
|
||||||
|
requestShareV2Download(normalizedShareKey, v2Body).onSuccess(v2Url -> {
|
||||||
|
if (StringUtils.isNotEmpty(v2Url)) {
|
||||||
|
complete(v2Url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
parseByIdLegacy(token, paramJson);
|
||||||
|
}).onFailure(err -> {
|
||||||
|
log.warn("Ye2 parseById v2接口失败,回退旧接口: {}", err.getMessage());
|
||||||
|
parseByIdLegacy(token, paramJson);
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
parseByIdLegacy(token, paramJson);
|
||||||
}).onFailure(err -> fail("123盘解析异常: " + err.getMessage()));
|
}).onFailure(err -> fail("123盘解析异常: " + err.getMessage()));
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
static final class ShareFileRequest {
|
private void parseByIdLegacy(String token, JsonObject paramJson) {
|
||||||
final String shareUrl;
|
if (paramJson.containsKey("FileID") && !paramJson.containsKey("fileId")) {
|
||||||
final String standardUrl;
|
paramJson.put("fileId", paramJson.getValue("FileID"));
|
||||||
final String shareKey;
|
|
||||||
final String password;
|
|
||||||
final long fileId;
|
|
||||||
final String s3keyFlag;
|
|
||||||
final long size;
|
|
||||||
final String etag;
|
|
||||||
final String token;
|
|
||||||
final long timeMillis;
|
|
||||||
final long randomA;
|
|
||||||
|
|
||||||
ShareFileRequest(String shareUrl, String standardUrl, String shareKey, String password, long fileId,
|
|
||||||
String s3keyFlag, long size, String etag, String token, long timeMillis, long randomA) {
|
|
||||||
this.shareUrl = shareUrl;
|
|
||||||
this.standardUrl = standardUrl;
|
|
||||||
this.shareKey = shareKey;
|
|
||||||
this.password = password;
|
|
||||||
this.fileId = fileId;
|
|
||||||
this.s3keyFlag = s3keyFlag;
|
|
||||||
this.size = size;
|
|
||||||
this.etag = etag;
|
|
||||||
this.token = token;
|
|
||||||
this.timeMillis = timeMillis;
|
|
||||||
this.randomA = randomA;
|
|
||||||
}
|
}
|
||||||
}
|
if (paramJson.containsKey("S3keyFlag") && !paramJson.containsKey("s3keyFlag")) {
|
||||||
|
paramJson.put("s3keyFlag", paramJson.getValue("S3keyFlag"));
|
||||||
static final class ShareHttpCall {
|
}
|
||||||
final String origin;
|
if (paramJson.containsKey("Size") && !paramJson.containsKey("size")) {
|
||||||
final String path;
|
paramJson.put("size", paramJson.getValue("Size"));
|
||||||
final String query;
|
}
|
||||||
final JsonObject body;
|
if (paramJson.containsKey("Etag") && !paramJson.containsKey("etag")) {
|
||||||
final MultiMap headers;
|
paramJson.put("etag", paramJson.getValue("Etag"));
|
||||||
|
|
||||||
ShareHttpCall(String origin, String path, String query, JsonObject body, MultiMap headers) {
|
|
||||||
this.origin = origin;
|
|
||||||
this.path = path;
|
|
||||||
this.query = query;
|
|
||||||
this.body = body;
|
|
||||||
this.headers = headers;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String url() {
|
String timestamp = String.valueOf(System.currentTimeMillis());
|
||||||
return origin + path + query;
|
String encryptedParams = encode123("/b/api/file/download_info", "android", "55", timestamp);
|
||||||
}
|
String apiUrl = DOWNLOAD_API_URL + encryptedParams;
|
||||||
}
|
|
||||||
|
|
||||||
@FunctionalInterface
|
log.info("Ye2 parseById API URL: {}", apiUrl);
|
||||||
interface ShareJsonPost {
|
|
||||||
Future<JsonObject> post(ShareHttpCall call);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
HttpRequest<Buffer> bufferHttpRequest = client.postAbs(apiUrl);
|
||||||
* 分享接口只发到 key 解码出的 https://{uid}.share.123pan.cn。
|
bufferHttpRequest.putHeader("platform", "android");
|
||||||
* mshare、/s/ 和调用方写入的其它 host 都不能改变这个目标。
|
bufferHttpRequest.putHeader("App-Version", "55");
|
||||||
*/
|
bufferHttpRequest.putHeader("Authorization", "Bearer " + token);
|
||||||
static String shareApiOrigin(String shareUrl, String standardUrl, String shareKey) {
|
bufferHttpRequest.putHeader("User-Agent", "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36");
|
||||||
String uid = YeShareHostUtil.getNumericSubdomainIdByShareKey(shareKey);
|
bufferHttpRequest.putHeader("Content-Type", "application/json");
|
||||||
if (!uid.matches("\\d+")) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (hostileShareHost(shareUrl) || hostileShareHost(standardUrl)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return "https://" + uid + ".share.123pan.cn";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
bufferHttpRequest
|
||||||
* 调用方给出的地址如果带了 host,只允许空、普通网页,或与 shareKey 一致的数字分享域名。
|
.sendJsonObject(paramJson)
|
||||||
* 127.0.0.1、云元数据、以及伪装成 123 域名的其它 host 直接拒绝。
|
.onSuccess(res2 -> handleDownloadUrlResponse(client, asJson(res2), "Ye2"))
|
||||||
*/
|
.onFailure(err -> fail("下载接口失败: " + err.getMessage()));
|
||||||
static boolean hostileShareHost(String url) {
|
|
||||||
if (StringUtils.isBlank(url)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
java.net.URI uri;
|
|
||||||
try {
|
|
||||||
uri = java.net.URI.create(url.trim());
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String host = uri.getHost();
|
|
||||||
if (host == null) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String scheme = uri.getScheme();
|
|
||||||
if (!"https".equalsIgnoreCase(scheme) && !"http".equalsIgnoreCase(scheme)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (uri.getUserInfo() != null || uri.getPort() > 0) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (host.equalsIgnoreCase("www.123pan.com") || host.equalsIgnoreCase("yun.123pan.com")
|
|
||||||
|| host.equalsIgnoreCase("123pan.com")) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return !host.matches("(?i)\\d+\\.(?:mshare|share)\\.123pan\\.cn");
|
|
||||||
}
|
|
||||||
|
|
||||||
static JsonObject trafficCheckBody(String shareKey, long fileId) {
|
|
||||||
return new JsonObject()
|
|
||||||
.put("shareKey", shareKey)
|
|
||||||
.put("fileIds", new JsonArray().add(fileId));
|
|
||||||
}
|
|
||||||
|
|
||||||
static JsonObject downloadInfoBody(String shareKey, long fileId, String s3keyFlag, long size, String etag) {
|
|
||||||
return new JsonObject()
|
|
||||||
.put("ShareKey", shareKey)
|
|
||||||
.put("FileID", fileId)
|
|
||||||
.put("S3keyFlag", s3keyFlag == null ? "" : s3keyFlag)
|
|
||||||
.put("Size", size)
|
|
||||||
.put("Etag", etag == null ? "" : etag);
|
|
||||||
}
|
|
||||||
|
|
||||||
static String trafficStopMessage(JsonObject data) {
|
|
||||||
if (data == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (Boolean.TRUE.equals(data.getBoolean("isBlocked"))) {
|
|
||||||
return "123网盘限制了这个分享的下载。解析器不会自动下单或选择付费流量。";
|
|
||||||
}
|
|
||||||
if (Boolean.TRUE.equals(data.getBoolean("isPay"))) {
|
|
||||||
return "123网盘这个文件需要付费后下载。解析器不会自动下单或选择付费流量。";
|
|
||||||
}
|
|
||||||
if (Boolean.TRUE.equals(data.getBoolean("isTrafficExceeded"))) {
|
|
||||||
return "123网盘分享提取流量不足。解析器不会自动购买或选择付费流量。";
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String joinDownloadUrl(String downloadPath, String prefix) {
|
|
||||||
if (StringUtils.isBlank(downloadPath)) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String path = downloadPath.trim();
|
|
||||||
if (path.startsWith("//")) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
if (isAbsoluteHttp(path)) {
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
if (StringUtils.isBlank(prefix) || !isAbsoluteHttp(prefix.trim())) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String normalizedPrefix = prefix.trim();
|
|
||||||
if (normalizedPrefix.endsWith("/") && path.startsWith("/")) {
|
|
||||||
return normalizedPrefix.substring(0, normalizedPrefix.length() - 1) + path;
|
|
||||||
}
|
|
||||||
if (!normalizedPrefix.endsWith("/") && !path.startsWith("/")) {
|
|
||||||
return normalizedPrefix + "/" + path;
|
|
||||||
}
|
|
||||||
return normalizedPrefix + path;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean isAbsoluteHttp(String value) {
|
|
||||||
return value.startsWith("https://") || value.startsWith("http://");
|
|
||||||
}
|
|
||||||
|
|
||||||
static Future<String> executeShareFileDownload(ShareJsonPost post, ShareFileRequest request) {
|
|
||||||
String origin = shareApiOrigin(request.shareUrl, request.standardUrl, request.shareKey);
|
|
||||||
if (origin == null || !usableShareKey(request.shareKey)) {
|
|
||||||
return Future.failedFuture("123网盘公开下载参数缺少可识别的分享域名");
|
|
||||||
}
|
|
||||||
String referer = origin + "/123pan/" + YeShareHostUtil.normalizeShareKey(request.shareKey);
|
|
||||||
if (StringUtils.isNotBlank(request.password)) {
|
|
||||||
referer = referer + "?pwd=" + request.password;
|
|
||||||
}
|
|
||||||
MultiMap headers = shareHeaders(origin, referer, request.token);
|
|
||||||
ShareHttpCall traffic = new ShareHttpCall(
|
|
||||||
origin,
|
|
||||||
SHARE_TRAFFIC_CHECK_PATH,
|
|
||||||
signQuery(SHARE_TRAFFIC_CHECK_PATH, SHARE_PLATFORM, SHARE_WEB_APP_VERSION,
|
|
||||||
request.timeMillis, request.randomA),
|
|
||||||
trafficCheckBody(request.shareKey, request.fileId),
|
|
||||||
headers);
|
|
||||||
ShareHttpCall download = new ShareHttpCall(
|
|
||||||
origin,
|
|
||||||
SHARE_DOWNLOAD_INFO_PATH,
|
|
||||||
signQuery(SHARE_DOWNLOAD_INFO_PATH, SHARE_PLATFORM, SHARE_WEB_APP_VERSION,
|
|
||||||
request.timeMillis, request.randomA),
|
|
||||||
downloadInfoBody(request.shareKey, request.fileId, request.s3keyFlag, request.size, request.etag),
|
|
||||||
headers);
|
|
||||||
return post.post(traffic).compose(json -> {
|
|
||||||
if (json == null || json.getInteger("code", -1) != 0) {
|
|
||||||
return Future.failedFuture(shareV2FailureMessage(json, request.token));
|
|
||||||
}
|
|
||||||
String stop = trafficStopMessage(json.getJsonObject("data"));
|
|
||||||
if (stop != null) {
|
|
||||||
return Future.failedFuture(stop);
|
|
||||||
}
|
|
||||||
return post.post(download);
|
|
||||||
}).compose(json -> {
|
|
||||||
if (json == null || json.getInteger("code", -1) != 0) {
|
|
||||||
return Future.failedFuture(shareV2FailureMessage(json, request.token));
|
|
||||||
}
|
|
||||||
JsonObject data = json.getJsonObject("data", new JsonObject());
|
|
||||||
JsonArray dispatchList = data.getJsonArray("dispatchList", new JsonArray());
|
|
||||||
String prefix = "";
|
|
||||||
if (!dispatchList.isEmpty() && dispatchList.getJsonObject(0) != null) {
|
|
||||||
prefix = dispatchList.getJsonObject(0).getString("prefix", "");
|
|
||||||
}
|
|
||||||
String url = joinDownloadUrl(data.getString("downloadPath"), prefix);
|
|
||||||
if (StringUtils.isBlank(url)) {
|
|
||||||
return Future.failedFuture("123网盘公开下载接口未返回下载链接");
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(url);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private static MultiMap shareHeaders(String origin, String referer, String token) {
|
|
||||||
MultiMap headers = MultiMap.caseInsensitiveMultiMap();
|
|
||||||
headers.set("Accept", "*/*");
|
|
||||||
headers.set("App-Version", SHARE_WEB_APP_VERSION);
|
|
||||||
headers.set("platform", SHARE_PLATFORM);
|
|
||||||
headers.set("Origin", origin);
|
|
||||||
headers.set("Referer", referer);
|
|
||||||
headers.set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36");
|
|
||||||
headers.set("Content-Type", "application/json;charset=UTF-8");
|
|
||||||
String authorization = bearerAuthorization(token);
|
|
||||||
if (authorization != null) {
|
|
||||||
headers.set("Authorization", authorization);
|
|
||||||
}
|
|
||||||
return headers;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String firstNonBlank(JsonObject json, String... keys) {
|
|
||||||
if (json == null) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
for (String key : keys) {
|
|
||||||
String value = json.getString(key);
|
|
||||||
if (StringUtils.isNotBlank(value)) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
static String resolveDownloadShareKey(JsonObject paramJson, String fallbackShareKey) {
|
|
||||||
String shareKey = paramJson == null ? null : paramJson.getString("shareKey");
|
|
||||||
if (StringUtils.isBlank(shareKey) && paramJson != null) {
|
|
||||||
shareKey = paramJson.getString("ShareKey");
|
|
||||||
}
|
|
||||||
if (StringUtils.isBlank(shareKey)) {
|
|
||||||
shareKey = fallbackShareKey;
|
|
||||||
}
|
|
||||||
return YeShareHostUtil.normalizeShareKey(shareKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
static boolean usableShareKey(String shareKey) {
|
|
||||||
return StringUtils.isNotBlank(shareKey) && !"-".equals(shareKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* getFileDownInfo / redirectUrl 用 shareKey="-" 占位,错误文案会变成 /s/-。
|
|
||||||
* 目录参数里已有真实 shareKey 时,只替换这个占位地址。
|
|
||||||
*/
|
|
||||||
static void applyResolvedShareKey(ShareLinkInfo info, String shareKey) {
|
|
||||||
if (info == null || !usableShareKey(shareKey)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
info.setShareKey(shareKey);
|
|
||||||
String rebuilt = "https://www.123pan.com/s/" + shareKey;
|
|
||||||
if (isPlaceholderYeShareUrl(info.getShareUrl())) {
|
|
||||||
info.setShareUrl(rebuilt);
|
|
||||||
}
|
|
||||||
if (isPlaceholderYeShareUrl(info.getStandardUrl())) {
|
|
||||||
info.setStandardUrl(rebuilt);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static boolean isPlaceholderYeShareUrl(String url) {
|
|
||||||
return StringUtils.isNotBlank(url) && (url.endsWith("/s/-") || url.endsWith("/s/-.html"));
|
|
||||||
}
|
|
||||||
|
|
||||||
static String bearerAuthorization(String token) {
|
|
||||||
return hasUsableToken(token) ? "Bearer " + token : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* v2 非 0 的说明。5112 仍用现有登录提示;5113、5066 原样留在 v2 错误里,不再改写成个人文件接口的文案。
|
|
||||||
*/
|
|
||||||
static String shareV2FailureMessage(JsonObject json, String token) {
|
|
||||||
Integer code = json == null ? null : json.getInteger("code");
|
|
||||||
String message = json == null ? null : json.getString("message");
|
|
||||||
if (isYeLoginRequired(code, message)) {
|
|
||||||
return loginRequiredDownloadMessage(hasUsableToken(token), message);
|
|
||||||
}
|
|
||||||
return "v2接口返回异常: " + (json == null ? "null" : json.encode());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean hasUsableToken(String token) {
|
|
||||||
return StringUtils.isNotBlank(token) && !"nologin".equals(token);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setFileTimes(JsonObject item, FileInfo fileInfo) {
|
private void setFileTimes(JsonObject item, FileInfo fileInfo) {
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import io.vertx.ext.web.client.HttpRequest;
|
|||||||
import io.vertx.ext.web.client.HttpResponse;
|
import io.vertx.ext.web.client.HttpResponse;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -28,9 +27,6 @@ import java.util.regex.Pattern;
|
|||||||
* 永硕E盘(主 ysepan.com / ys168.com,备 cccpan.com / ysupan.com / uupan.net / ysok.net)
|
* 永硕E盘(主 ysepan.com / ys168.com,备 cccpan.com / ysupan.com / uupan.net / ysok.net)
|
||||||
* <p>
|
* <p>
|
||||||
* 空间分享形如 https://{space}.ysepan.com/ ,需空间访问密码时通过 sharePassword 传入。
|
* 空间分享形如 https://{space}.ysepan.com/ ,需空间访问密码时通过 sharePassword 传入。
|
||||||
* <p>
|
|
||||||
* 2026-11 起密码空间改为入口页:令牌在 {@code data-verification-token},登录名在 {@code data-dlmc}。
|
|
||||||
* {@code ys168.com} 会 302 到 {@code ysepan.com},密码验证必须发往跳转后的主机。
|
|
||||||
*/
|
*/
|
||||||
public class YsTool extends PanBase {
|
public class YsTool extends PanBase {
|
||||||
|
|
||||||
@@ -38,17 +34,10 @@ public class YsTool extends PanBase {
|
|||||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
||||||
+ "(KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36";
|
+ "(KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36";
|
||||||
|
|
||||||
/** 旧版入口脚本:{@code RequestVerificationToken': '...'} */
|
private static final Pattern ANTIFORGERY_PATTERN =
|
||||||
private static final Pattern ANTIFORGERY_LEGACY_PATTERN =
|
|
||||||
Pattern.compile("RequestVerificationToken'\\s*:\\s*'([^']+)'");
|
Pattern.compile("RequestVerificationToken'\\s*:\\s*'([^']+)'");
|
||||||
/** 新版入口页:{@code data-verification-token="..."} */
|
|
||||||
private static final Pattern ANTIFORGERY_ATTR_PATTERN =
|
|
||||||
Pattern.compile("data-verification-token\\s*=\\s*([\"'])([^\"']+)\\1");
|
|
||||||
private static final Pattern DLMC_ATTR_PATTERN =
|
|
||||||
Pattern.compile("data-dlmc\\s*=\\s*([\"'])([^\"']+)\\1");
|
|
||||||
private static final Pattern HTXX_PATTERN =
|
private static final Pattern HTXX_PATTERN =
|
||||||
Pattern.compile("window\\.htxx\\s*=\\s*(\\{.*?});", Pattern.DOTALL);
|
Pattern.compile("window\\.htxx\\s*=\\s*(\\{.*?});", Pattern.DOTALL);
|
||||||
private static final int MAX_HOME_REDIRECTS = 5;
|
|
||||||
private static final Pattern JWT_COOKIE_PATTERN =
|
private static final Pattern JWT_COOKIE_PATTERN =
|
||||||
Pattern.compile("jwttk_[^=]+=([^;\\s]+)");
|
Pattern.compile("jwttk_[^=]+=([^;\\s]+)");
|
||||||
|
|
||||||
@@ -152,49 +141,21 @@ public class YsTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Future<Session> ensureSession() {
|
private Future<Session> ensureSession() {
|
||||||
|
Promise<Session> p = Promise.promise();
|
||||||
String space = spaceName();
|
String space = spaceName();
|
||||||
if (StringUtils.isBlank(space)) {
|
if (StringUtils.isBlank(space)) {
|
||||||
return Future.failedFuture(baseMsg() + " - 空间名为空");
|
p.fail(baseMsg() + " - 空间名为空");
|
||||||
|
return p.future();
|
||||||
}
|
}
|
||||||
// 手动跟随跳转,才能把后续密码验证发到最终主机(ys168.com -> ysepan.com)
|
|
||||||
return fetchSpaceHome(spaceOrigin() + "/", 0)
|
|
||||||
.compose(home -> handleSpaceHome(home.origin(), space, home.response()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
String origin = spaceOrigin();
|
||||||
* 关闭自动重定向并逐跳记录最终地址。Cookie(含 .AspNetCore.Antiforgery.* 与 jwttk_*)
|
clientSession.getAbs(origin + "/")
|
||||||
* 仍由同一个 clientSession 保存,供密码验证和接口请求带上。
|
|
||||||
*/
|
|
||||||
private Future<FetchedHome> fetchSpaceHome(String url, int redirects) {
|
|
||||||
Promise<FetchedHome> p = Promise.promise();
|
|
||||||
clientSession.getAbs(url)
|
|
||||||
.followRedirects(false)
|
|
||||||
.putHeader("User-Agent", BROWSER_UA)
|
.putHeader("User-Agent", BROWSER_UA)
|
||||||
.putHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
.putHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||||
.send()
|
.send()
|
||||||
.onSuccess(res -> {
|
.compose(res -> handleSpaceHome(origin, space, res))
|
||||||
int status = res.statusCode();
|
.onSuccess(p::complete)
|
||||||
if (status >= 300 && status < 400 && status != 304) {
|
.onFailure(p::fail);
|
||||||
if (redirects >= MAX_HOME_REDIRECTS) {
|
|
||||||
p.fail(baseMsg() + " - 空间首页重定向次数过多");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
String next = resolveRedirect(url, res.getHeader("Location"));
|
|
||||||
if (next == null) {
|
|
||||||
p.fail(baseMsg() + " - 空间首页重定向无效");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
fetchSpaceHome(next, redirects + 1).onComplete(p);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
String origin = originOf(url);
|
|
||||||
if (origin == null) {
|
|
||||||
p.fail(baseMsg() + " - 空间地址无效");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
p.complete(new FetchedHome(origin, res));
|
|
||||||
})
|
|
||||||
.onFailure(t -> p.fail(baseMsg() + " - 打开空间失败: " + t.getMessage()));
|
|
||||||
return p.future();
|
return p.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,8 +172,8 @@ public class YsTool extends PanBase {
|
|||||||
return Future.succeededFuture(toSession(origin, space, jwt, htxx));
|
return Future.succeededFuture(toSession(origin, space, jwt, htxx));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 需要空间密码(新版入口页或旧版 loginPopup / VerifyPassword)
|
// 需要空间密码
|
||||||
if (isPasswordPage(html)) {
|
if (html.contains("VerifyPassword") || html.contains("loginPopup")) {
|
||||||
String pwd = shareLinkInfo.getSharePassword();
|
String pwd = shareLinkInfo.getSharePassword();
|
||||||
if (StringUtils.isBlank(pwd)) {
|
if (StringUtils.isBlank(pwd)) {
|
||||||
return Future.failedFuture(baseMsg() + " - 空间需要访问密码");
|
return Future.failedFuture(baseMsg() + " - 空间需要访问密码");
|
||||||
@@ -221,25 +182,21 @@ public class YsTool extends PanBase {
|
|||||||
if (StringUtils.isBlank(antiforgery)) {
|
if (StringUtils.isBlank(antiforgery)) {
|
||||||
return Future.failedFuture(baseMsg() + " - 无法获取防伪令牌");
|
return Future.failedFuture(baseMsg() + " - 无法获取防伪令牌");
|
||||||
}
|
}
|
||||||
String dlmc = StringUtils.defaultIfBlank(extractDlmc(html), space);
|
return verifyPassword(origin, space, pwd, antiforgery)
|
||||||
// 新版 VerifyPassword 只返回 {"success":true},jwttk 在入口页就已经下发
|
.compose(verifiedJwt -> reloadSpace(origin, space, verifiedJwt));
|
||||||
return verifyPassword(origin, dlmc, pwd, antiforgery)
|
|
||||||
.compose(verifiedJwt -> reloadSpace(origin, space,
|
|
||||||
StringUtils.defaultIfBlank(verifiedJwt, jwt)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return Future.failedFuture(baseMsg() + " - 无法解析空间信息");
|
return Future.failedFuture(baseMsg() + " - 无法解析空间信息");
|
||||||
}
|
}
|
||||||
|
|
||||||
private Future<String> verifyPassword(String origin, String dlmc, String pwd, String antiforgery) {
|
private Future<String> verifyPassword(String origin, String space, String pwd, String antiforgery) {
|
||||||
Promise<String> p = Promise.promise();
|
Promise<String> p = Promise.promise();
|
||||||
JsonObject body = new JsonObject()
|
JsonObject body = new JsonObject()
|
||||||
.put("password", pwd)
|
.put("password", pwd)
|
||||||
.put("dlmc", dlmc)
|
.put("dlmc", space)
|
||||||
.put("remember", false);
|
.put("remember", false);
|
||||||
|
|
||||||
clientSession.postAbs(verifyPasswordEndpoint(origin))
|
clientSession.postAbs(origin + "/?handler=VerifyPassword")
|
||||||
.followRedirects(false)
|
|
||||||
.putHeader("User-Agent", BROWSER_UA)
|
.putHeader("User-Agent", BROWSER_UA)
|
||||||
.putHeader("Content-Type", "application/json")
|
.putHeader("Content-Type", "application/json")
|
||||||
.putHeader("Origin", origin)
|
.putHeader("Origin", origin)
|
||||||
@@ -248,18 +205,18 @@ public class YsTool extends PanBase {
|
|||||||
.sendJsonObject(body)
|
.sendJsonObject(body)
|
||||||
.onSuccess(res -> {
|
.onSuccess(res -> {
|
||||||
try {
|
try {
|
||||||
if (res.statusCode() >= 400) {
|
|
||||||
p.fail(baseMsg() + " - " + passwordFailureMessage(res.statusCode(), res.bodyAsString()));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
JsonObject json = res.bodyAsJsonObject();
|
JsonObject json = res.bodyAsJsonObject();
|
||||||
if (json == null || !Boolean.TRUE.equals(json.getBoolean("success"))) {
|
if (json == null || !Boolean.TRUE.equals(json.getBoolean("success"))) {
|
||||||
String msg = json != null ? json.getString("message", "密码错误") : "密码验证失败";
|
String msg = json != null ? json.getString("message", "密码错误") : "密码验证失败";
|
||||||
p.fail(baseMsg() + " - " + msg);
|
p.fail(baseMsg() + " - " + msg);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// 响应里若刷新了 jwttk 就用新的;否则调用方回退到入口页令牌
|
String jwt = extractJwt(res);
|
||||||
p.complete(StringUtils.defaultString(extractJwt(res)));
|
if (StringUtils.isBlank(jwt)) {
|
||||||
|
p.fail(baseMsg() + " - 密码验证成功但未返回会话令牌");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
p.complete(jwt);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
p.fail(baseMsg() + " - 密码验证响应异常: " + e.getMessage());
|
p.fail(baseMsg() + " - 密码验证响应异常: " + e.getMessage());
|
||||||
}
|
}
|
||||||
@@ -269,18 +226,27 @@ public class YsTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Future<Session> reloadSpace(String origin, String space, String verifiedJwt) {
|
private Future<Session> reloadSpace(String origin, String space, String verifiedJwt) {
|
||||||
return fetchSpaceHome(origin + "/", 0).compose(home -> {
|
Promise<Session> p = Promise.promise();
|
||||||
String html = home.response().bodyAsString() != null ? home.response().bodyAsString() : "";
|
clientSession.getAbs(origin + "/")
|
||||||
JsonObject htxx = extractHtxx(html);
|
.putHeader("User-Agent", BROWSER_UA)
|
||||||
String jwt = StringUtils.defaultIfBlank(extractJwt(home.response()), verifiedJwt);
|
.putHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||||
if (htxx == null || StringUtils.isBlank(htxx.getString("qqdz"))) {
|
.send()
|
||||||
return Future.failedFuture(baseMsg() + " - 密码验证后仍无法进入空间");
|
.onSuccess(res -> {
|
||||||
}
|
String html = res.bodyAsString() != null ? res.bodyAsString() : "";
|
||||||
if (StringUtils.isBlank(jwt)) {
|
JsonObject htxx = extractHtxx(html);
|
||||||
return Future.failedFuture(baseMsg() + " - 密码验证后无法获取会话令牌");
|
String jwt = StringUtils.defaultIfBlank(extractJwt(res), verifiedJwt);
|
||||||
}
|
if (htxx == null || StringUtils.isBlank(htxx.getString("qqdz"))) {
|
||||||
return Future.succeededFuture(toSession(home.origin(), space, jwt, htxx));
|
p.fail(baseMsg() + " - 密码验证后仍无法进入空间");
|
||||||
});
|
return;
|
||||||
|
}
|
||||||
|
if (StringUtils.isBlank(jwt)) {
|
||||||
|
p.fail(baseMsg() + " - 密码验证后无法获取会话令牌");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
p.complete(toSession(origin, space, jwt, htxx));
|
||||||
|
})
|
||||||
|
.onFailure(t -> p.fail(baseMsg() + " - 重新加载空间失败: " + t.getMessage()));
|
||||||
|
return p.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
private Session toSession(String origin, String space, String jwt, JsonObject htxx) {
|
private Session toSession(String origin, String space, String jwt, JsonObject htxx) {
|
||||||
@@ -654,134 +620,24 @@ public class YsTool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private String spaceOrigin() {
|
private String spaceOrigin() {
|
||||||
String fromUrl = originOf(shareLinkInfo.getShareUrl());
|
String shareUrl = shareLinkInfo.getShareUrl();
|
||||||
if (fromUrl != null) {
|
if (StringUtils.isNotBlank(shareUrl)) {
|
||||||
return fromUrl;
|
try {
|
||||||
|
java.net.URI uri = java.net.URI.create(shareUrl);
|
||||||
|
String scheme = uri.getScheme() != null ? uri.getScheme() : "https";
|
||||||
|
return scheme + "://" + uri.getHost();
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return "https://" + spaceName() + ".ysepan.com";
|
return "https://" + spaceName() + ".ysepan.com";
|
||||||
}
|
}
|
||||||
|
|
||||||
static boolean isPasswordPage(String html) {
|
private static String extractAntiforgery(String html) {
|
||||||
if (StringUtils.isBlank(html)) {
|
Matcher m = ANTIFORGERY_PATTERN.matcher(html);
|
||||||
return false;
|
return m.find() ? m.group(1) : null;
|
||||||
}
|
|
||||||
return html.contains("VerifyPassword")
|
|
||||||
|| html.contains("loginPopup")
|
|
||||||
|| html.contains("data-verification-token")
|
|
||||||
|| html.contains("id=\"entryConfig\"")
|
|
||||||
|| html.contains("id=\"loginForm\"")
|
|
||||||
|| html.contains("id='entryConfig'")
|
|
||||||
|| html.contains("id='loginForm'");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private static JsonObject extractHtxx(String html) {
|
||||||
* 优先新版 data-verification-token,其次旧版脚本里的 RequestVerificationToken。
|
|
||||||
*/
|
|
||||||
static String extractAntiforgery(String html) {
|
|
||||||
if (html == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
Matcher attr = ANTIFORGERY_ATTR_PATTERN.matcher(html);
|
|
||||||
if (attr.find()) {
|
|
||||||
return attr.group(2);
|
|
||||||
}
|
|
||||||
Matcher legacy = ANTIFORGERY_LEGACY_PATTERN.matcher(html);
|
|
||||||
return legacy.find() ? legacy.group(1) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String extractDlmc(String html) {
|
|
||||||
if (html == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
Matcher matcher = DLMC_ATTR_PATTERN.matcher(html);
|
|
||||||
return matcher.find() ? matcher.group(2) : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把密码接口的失败响应转成可展示的短句。上游对错误密码返回 HTTP 400,
|
|
||||||
* 正文是 {@code code=invalid_password}。不回传响应原文,避免带上令牌。
|
|
||||||
*/
|
|
||||||
static String passwordFailureMessage(int statusCode, String body) {
|
|
||||||
try {
|
|
||||||
if (body != null && body.trim().startsWith("{")) {
|
|
||||||
JsonObject json = new JsonObject(body);
|
|
||||||
String code = StringUtils.defaultString(json.getString("code"));
|
|
||||||
String message = safePasswordMessage(json.getString("message"));
|
|
||||||
if ("invalid_password".equals(code)) {
|
|
||||||
return message != null ? message : "密码错误";
|
|
||||||
}
|
|
||||||
if (message != null) {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception ignored) {
|
|
||||||
}
|
|
||||||
return "密码验证失败 HTTP " + statusCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String safePasswordMessage(String message) {
|
|
||||||
if (StringUtils.isBlank(message)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String trimmed = message.trim();
|
|
||||||
if (trimmed.length() > 80) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String lower = trimmed.toLowerCase();
|
|
||||||
if (lower.contains("eyj") || trimmed.contains("CfDJ") || lower.contains("jwttk")
|
|
||||||
|| lower.contains("cookie") || lower.contains("token")) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return trimmed;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 密码验证地址。origin 必须是重定向结束后的主机,不能用 ys168.com 原站。 */
|
|
||||||
static String verifyPasswordEndpoint(String origin) {
|
|
||||||
return origin + "/?handler=VerifyPassword";
|
|
||||||
}
|
|
||||||
|
|
||||||
static String resolveRedirect(String currentUrl, String location) {
|
|
||||||
if (StringUtils.isBlank(currentUrl) || StringUtils.isBlank(location)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
URI resolved = URI.create(currentUrl.trim()).resolve(location.trim());
|
|
||||||
if (resolved.getScheme() == null || resolved.getHost() == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return resolved.toString();
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static String originOf(String url) {
|
|
||||||
if (StringUtils.isBlank(url)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
URI uri = URI.create(url.trim());
|
|
||||||
if (uri.getScheme() == null || uri.getHost() == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String scheme = uri.getScheme();
|
|
||||||
int port = uri.getPort();
|
|
||||||
boolean defaultPort = port < 0
|
|
||||||
|| ("https".equalsIgnoreCase(scheme) && port == 443)
|
|
||||||
|| ("http".equalsIgnoreCase(scheme) && port == 80);
|
|
||||||
if (defaultPort) {
|
|
||||||
return scheme + "://" + uri.getHost();
|
|
||||||
}
|
|
||||||
return scheme + "://" + uri.getHost() + ":" + port;
|
|
||||||
} catch (Exception e) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static JsonObject extractHtxx(String html) {
|
|
||||||
if (html == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
Matcher m = HTXX_PATTERN.matcher(html);
|
Matcher m = HTXX_PATTERN.matcher(html);
|
||||||
if (!m.find()) {
|
if (!m.find()) {
|
||||||
return null;
|
return null;
|
||||||
@@ -830,9 +686,6 @@ public class YsTool extends PanBase {
|
|||||||
return URLEncoder.encode(StringUtils.defaultString(value), StandardCharsets.UTF_8);
|
return URLEncoder.encode(StringUtils.defaultString(value), StandardCharsets.UTF_8);
|
||||||
}
|
}
|
||||||
|
|
||||||
private record FetchedHome(String origin, HttpResponse<Buffer> response) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private record Session(String origin, String space, String jwt, String apiBase) {
|
private record Session(String origin, String space, String jwt, String apiBase) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -92,17 +92,7 @@ public class HttpResponseHelper {
|
|||||||
|
|
||||||
// -------------------- Buffer 转换 --------------------
|
// -------------------- Buffer 转换 --------------------
|
||||||
private static Buffer toBuffer(HttpResponse<?> res) {
|
private static Buffer toBuffer(HttpResponse<?> res) {
|
||||||
Object raw = res.body();
|
return res.body() instanceof Buffer ? (Buffer) res.body() : Buffer.buffer(res.bodyAsString());
|
||||||
if (raw instanceof Buffer buf) {
|
|
||||||
return buf;
|
|
||||||
}
|
|
||||||
// 407/空 body 时 body() 与 bodyAsString() 都可能是 null,Buffer.buffer(null) 会 NPE,
|
|
||||||
// 最终被当成「ajax 返回非JSON: 空响应」。
|
|
||||||
if (raw == null) {
|
|
||||||
return Buffer.buffer();
|
|
||||||
}
|
|
||||||
String text = res.bodyAsString();
|
|
||||||
return text == null ? Buffer.buffer() : Buffer.buffer(text);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void ensureBodyLimit(Buffer body) {
|
private static void ensureBodyLimit(Buffer body) {
|
||||||
|
|||||||
@@ -1,79 +0,0 @@
|
|||||||
package cn.qaiu.parser;
|
|
||||||
|
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertThrows;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
public class FolderPagingTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void blankPageKeepsLegacyBehaviour() {
|
|
||||||
assertNull(FolderPaging.parsePage(null));
|
|
||||||
assertNull(FolderPaging.parsePage(" "));
|
|
||||||
assertEquals(1, FolderPaging.pageOrFirst(info()));
|
|
||||||
assertNull(FolderPaging.requestedPage(info()));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void invalidPagesAreRejected() {
|
|
||||||
assertEquals(Integer.valueOf(3), FolderPaging.parsePage(" 3 "));
|
|
||||||
assertThrows(IllegalArgumentException.class, () -> FolderPaging.parsePage("0"));
|
|
||||||
assertThrows(IllegalArgumentException.class, () -> FolderPaging.parsePage("-1"));
|
|
||||||
assertThrows(IllegalArgumentException.class, () -> FolderPaging.parsePage("abc"));
|
|
||||||
assertThrows(IllegalArgumentException.class, () -> FolderPaging.parsePage(String.valueOf(FolderPaging.MAX_PAGE + 1)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void onlyLzFjIzArePaged() {
|
|
||||||
assertTrue(FolderPaging.supports("lz"));
|
|
||||||
assertTrue(FolderPaging.supports("FJ"));
|
|
||||||
assertTrue(FolderPaging.supports("iz"));
|
|
||||||
assertFalse(FolderPaging.supports("qk"));
|
|
||||||
assertFalse(FolderPaging.supports(null));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void emptyPageAlwaysEnds() {
|
|
||||||
assertFalse(FolderPaging.hasMore(2, 0, 60, 9));
|
|
||||||
assertFalse(FolderPaging.hasMore(1, 0, 50, null));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void totalPageWinsOverFullPageHeuristic() {
|
|
||||||
assertFalse(FolderPaging.hasMore(2, 60, 60, 2));
|
|
||||||
assertTrue(FolderPaging.hasMore(1, 5, 60, 2));
|
|
||||||
assertTrue(FolderPaging.hasMore(1, 50, 50, null));
|
|
||||||
assertFalse(FolderPaging.hasMore(1, 49, 50, null));
|
|
||||||
assertTrue(FolderPaging.hasMore(1, 50, 50, 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void offsetListPageReadsTotals() {
|
|
||||||
ShareLinkInfo info = info();
|
|
||||||
info.getOtherParam().put(FolderPaging.PAGE, 2);
|
|
||||||
JsonObject resp = new JsonObject().put("total", "121").put("totalPage", 3).put("offset", 2).put("limit", 60);
|
|
||||||
JsonObject page = FolderPaging.offsetListPage(info, resp, 60, 60);
|
|
||||||
assertEquals(Integer.valueOf(121), page.getInteger("total"));
|
|
||||||
assertEquals(Integer.valueOf(3), page.getInteger("totalPage"));
|
|
||||||
assertTrue(page.getBoolean("hasMore"));
|
|
||||||
assertEquals(Integer.valueOf(3), page.getInteger("nextPage"));
|
|
||||||
assertEquals(page, FolderPaging.pageInfo(info));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void noMoreClearsNextPageAndCursor() {
|
|
||||||
JsonObject page = FolderPaging.pageInfo(info(), 4, 50, false, null, null, "cursor");
|
|
||||||
assertNull(page.getValue("nextPage"));
|
|
||||||
assertNull(page.getValue("nextCursor"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static ShareLinkInfo info() {
|
|
||||||
return ShareLinkInfo.newBuilder().type("lz").shareKey("b1").build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import cn.qaiu.WebClientVertxInit;
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
|
||||||
import cn.qaiu.parser.FolderPaging;
|
|
||||||
import io.vertx.core.Vertx;
|
|
||||||
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 io.vertx.uritemplate.UriTemplate;
|
|
||||||
import org.junit.After;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.lang.reflect.Proxy;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
|
||||||
import java.util.concurrent.ExecutionException;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
import static org.junit.Assert.fail;
|
|
||||||
|
|
||||||
/** 小飞机 share/list:offset 是从 1 开始的页码,limit 为每页条数。 */
|
|
||||||
public class FjToolFolderPagingTest {
|
|
||||||
|
|
||||||
private Vertx vertx;
|
|
||||||
private WebClient local;
|
|
||||||
private HttpServer server;
|
|
||||||
private final List<String> queries = new CopyOnWriteArrayList<>();
|
|
||||||
private volatile String override;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void setup() throws Exception {
|
|
||||||
vertx = Vertx.vertx();
|
|
||||||
WebClientVertxInit.init(vertx);
|
|
||||||
local = WebClient.create(vertx);
|
|
||||||
server = vertx.createHttpServer().requestHandler(req -> {
|
|
||||||
if (req.path().endsWith("/share/list")) {
|
|
||||||
queries.add(req.query());
|
|
||||||
if (override != null) {
|
|
||||||
req.response().end(override);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
int offset = Integer.parseInt(req.getParam("offset"));
|
|
||||||
int limit = Integer.parseInt(req.getParam("limit"));
|
|
||||||
int total = 125;
|
|
||||||
int totalPage = (total + limit - 1) / limit;
|
|
||||||
JsonArray list = new JsonArray();
|
|
||||||
for (int i = (offset - 1) * limit; i < Math.min(total, offset * limit); i++) {
|
|
||||||
list.add(new JsonObject().put("fileType", 1).put("fileId", String.valueOf(1000 + i)).put("fileName", "f" + i + ".txt")
|
|
||||||
.put("fileSize", 1).put("fileIcon", "txt").put("userId", 9).put("fileDownloads", 0)
|
|
||||||
.put("updTime", "2024-01-01 00:00:00"));
|
|
||||||
}
|
|
||||||
req.response().end(new JsonObject().put("code", 200).put("list", list).put("total", total)
|
|
||||||
.put("offset", offset).put("limit", limit).put("totalPage", totalPage).encode());
|
|
||||||
} 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void defaultRequestIsFirstPageWithLegacyLimit() throws Exception {
|
|
||||||
ShareLinkInfo info = info(null);
|
|
||||||
List<FileInfo> list = list(info);
|
|
||||||
assertEquals(60, list.size());
|
|
||||||
assertTrue(queries.get(0).contains("offset=1"));
|
|
||||||
assertTrue(queries.get(0).contains("limit=60"));
|
|
||||||
assertTrue(FolderPaging.pageInfo(info).getBoolean("hasMore"));
|
|
||||||
assertEquals(Integer.valueOf(125), FolderPaging.pageInfo(info).getInteger("total"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void pagesAreDistinctAndLastPageEnds() throws Exception {
|
|
||||||
java.util.Set<String> ids = new java.util.HashSet<>();
|
|
||||||
for (int page = 1; page <= 3; page++) {
|
|
||||||
ShareLinkInfo info = info(page);
|
|
||||||
for (FileInfo f : list(info)) {
|
|
||||||
assertTrue("重复 " + f.getFileId(), ids.add(f.getFileId()));
|
|
||||||
}
|
|
||||||
assertEquals(page < 3, FolderPaging.pageInfo(info).getBoolean("hasMore"));
|
|
||||||
assertTrue(queries.get(queries.size() - 1).contains("offset=" + page));
|
|
||||||
}
|
|
||||||
assertEquals(125, ids.size());
|
|
||||||
ShareLinkInfo beyond = info(4);
|
|
||||||
assertTrue(list(beyond).isEmpty());
|
|
||||||
assertFalse(FolderPaging.pageInfo(beyond).getBoolean("hasMore"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void nonJsonListFailsInsteadOfHanging() throws Exception {
|
|
||||||
override = "<html>busy</html>";
|
|
||||||
try {
|
|
||||||
list(info(null));
|
|
||||||
fail();
|
|
||||||
} catch (ExecutionException e) {
|
|
||||||
assertTrue(e.getCause().getMessage().contains("目录解析失败"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<FileInfo> list(ShareLinkInfo info) throws Exception {
|
|
||||||
return tool(info).parseFileList().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
private ShareLinkInfo info(Integer page) {
|
|
||||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("fj").shareKey("share")
|
|
||||||
.shareUrl("https://share.feijipan.com/s/share").build();
|
|
||||||
info.getOtherParam().put("dirId", "777");
|
|
||||||
info.getOtherParam().put("uuid", "test-uuid");
|
|
||||||
if (page != null) {
|
|
||||||
info.getOtherParam().put(FolderPaging.PAGE, page);
|
|
||||||
}
|
|
||||||
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; }};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import cn.qaiu.util.CommonUtils;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertNotNull;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
|
|
||||||
public class LzFolderCursorTest {
|
|
||||||
|
|
||||||
private static final String PATH = "/filemoreajax.php?file=66477";
|
|
||||||
|
|
||||||
private static Map<String, String> form() {
|
|
||||||
Map<String, String> form = new LinkedHashMap<>();
|
|
||||||
form.put("lx", "2");
|
|
||||||
form.put("fid", "66477");
|
|
||||||
form.put("uid", "234978");
|
|
||||||
form.put("pg", "1");
|
|
||||||
form.put("t", "1795564485");
|
|
||||||
form.put("k", "abc");
|
|
||||||
form.put("pwd", "secret");
|
|
||||||
return form;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void roundTripDropsPasswordAndUsesRequestedPage() {
|
|
||||||
String raw = LzFolderCursor.encode("b66477", PATH, form(), 2, "wp1");
|
|
||||||
assertFalse(CommonUtils.urlBase64Decode(raw).contains("secret"));
|
|
||||||
LzFolderCursor cursor = LzFolderCursor.decode(raw, "b66477", 2);
|
|
||||||
assertNotNull(cursor);
|
|
||||||
assertEquals(PATH, cursor.path);
|
|
||||||
assertEquals("wp1", cursor.webpage);
|
|
||||||
Map<String, String> next = cursor.formFor("newpwd", 2);
|
|
||||||
assertEquals("2", next.get("pg"));
|
|
||||||
assertEquals("newpwd", next.get("pwd"));
|
|
||||||
assertEquals("1795564485", next.get("t"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void mismatchedShareOrPageIsIgnored() {
|
|
||||||
String raw = LzFolderCursor.encode("b66477", PATH, form(), 2, null);
|
|
||||||
assertNull(LzFolderCursor.decode(raw, "b00000", 2));
|
|
||||||
assertNull(LzFolderCursor.decode(raw, "b66477", 3));
|
|
||||||
assertNull(LzFolderCursor.decode("not-base64!", "b66477", 2));
|
|
||||||
assertNull(LzFolderCursor.decode(null, "b66477", 2));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void tamperedPathOrFieldsAreIgnored() {
|
|
||||||
assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", "http://evil/x", form(), 2, null), "b1", 2));
|
|
||||||
assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", "/filemoreajax.php?file=1", form(), 2, null), "b1", 2));
|
|
||||||
Map<String, String> bad = form();
|
|
||||||
bad.put("x\ny", "1");
|
|
||||||
assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", PATH, bad, 2, null), "b1", 2));
|
|
||||||
Map<String, String> noToken = form();
|
|
||||||
noToken.remove("t");
|
|
||||||
assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", PATH, noToken, 2, null), "b1", 2));
|
|
||||||
JsonObject json = new JsonObject(CommonUtils.urlBase64Decode(LzFolderCursor.encode("b1", PATH, form(), 2, null)));
|
|
||||||
json.put("v", 99);
|
|
||||||
assertNull(LzFolderCursor.decode(CommonUtils.urlBase64Encode(json.encode()), "b1", 2));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void unsafeWebpageIsDropped() {
|
|
||||||
String raw = LzFolderCursor.encode("b1", PATH, form(), 2, "a/../../x?y");
|
|
||||||
LzFolderCursor cursor = LzFolderCursor.decode(raw, "b1", 2);
|
|
||||||
assertNotNull(cursor);
|
|
||||||
assertNull(cursor.webpage);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import cn.qaiu.WebClientVertxInit;
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
|
||||||
import cn.qaiu.parser.ParserCreate;
|
|
||||||
import io.vertx.core.Vertx;
|
|
||||||
import org.junit.AfterClass;
|
|
||||||
import org.junit.Assume;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.http.HttpClient;
|
|
||||||
import java.net.http.HttpRequest;
|
|
||||||
import java.net.http.HttpResponse;
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 蓝奏目录真实联调。默认不跑:
|
|
||||||
* mvn -pl parser -DskipTests=false -Dlz.live=true -Dtest=LzFolderLiveTest test
|
|
||||||
*/
|
|
||||||
public class LzFolderLiveTest {
|
|
||||||
|
|
||||||
private static Vertx vertx;
|
|
||||||
|
|
||||||
@AfterClass
|
|
||||||
public static void close() {
|
|
||||||
if (vertx != null) {
|
|
||||||
vertx.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void oldFolderListsOnBothDomainsAndOneFileDownloads() throws Exception {
|
|
||||||
liveOnly();
|
|
||||||
List<FileInfo> oui = list("https://pan.lanzoui.com/b66477");
|
|
||||||
List<FileInfo> oug = list("https://pan.lanzoug.com/b66477");
|
|
||||||
assertFalse(oui.isEmpty());
|
|
||||||
assertFalse(oug.isEmpty());
|
|
||||||
assertEquals(oui.get(0).getFileName(), oug.get(0).getFileName());
|
|
||||||
FileInfo small = smallest(oui);
|
|
||||||
String url = ParserCreate.fromShareUrl("https://pan.lanzoui.com/" + small.getFileId())
|
|
||||||
.createTool().parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
|
||||||
HttpResponse<byte[]> response = HttpClient.newBuilder()
|
|
||||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
|
||||||
.connectTimeout(Duration.ofSeconds(20))
|
|
||||||
.build()
|
|
||||||
.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(60)).GET().build(),
|
|
||||||
HttpResponse.BodyHandlers.ofByteArray());
|
|
||||||
assertEquals(200, response.statusCode());
|
|
||||||
assertTrue(response.body().length > 0);
|
|
||||||
if (small.getSize() != null && small.getSize() > 0 && small.getSize() < 8_000_000) {
|
|
||||||
assertEquals(small.getSize().longValue(), response.body().length);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void passwordFolderStillLists() throws Exception {
|
|
||||||
liveOnly();
|
|
||||||
List<FileInfo> files = ParserCreate.fromShareUrl("https://moteam.lanzoum.com/b00yaejvte")
|
|
||||||
.setShareLinkInfoPwd("1234")
|
|
||||||
.createTool().parseFileList()
|
|
||||||
.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
|
||||||
assertFalse(files.isEmpty());
|
|
||||||
assertTrue(files.stream().anyMatch(file -> file.getFileName() != null && !file.getFileName().isBlank()));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static List<FileInfo> list(String url) throws Exception {
|
|
||||||
return ParserCreate.fromShareUrl(url).createTool().parseFileList()
|
|
||||||
.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static FileInfo smallest(List<FileInfo> files) {
|
|
||||||
FileInfo best = files.get(0);
|
|
||||||
for (FileInfo file : files) {
|
|
||||||
if (file.getSize() != null && (best.getSize() == null || file.getSize() < best.getSize())) {
|
|
||||||
best = file;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return best;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void liveOnly() {
|
|
||||||
Assume.assumeTrue("set -Dlz.live=true to call lanzou", Boolean.getBoolean("lz.live"));
|
|
||||||
if (vertx == null) {
|
|
||||||
vertx = Vertx.vertx();
|
|
||||||
WebClientVertxInit.init(vertx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,175 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import cn.qaiu.WebClientVertxInit;
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
|
||||||
import cn.qaiu.parser.FolderPaging;
|
|
||||||
import cn.qaiu.parser.ParserCreate;
|
|
||||||
import io.vertx.core.Vertx;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
import org.junit.AfterClass;
|
|
||||||
import org.junit.Assume;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.http.HttpClient;
|
|
||||||
import java.net.http.HttpRequest;
|
|
||||||
import java.net.http.HttpResponse;
|
|
||||||
import java.time.Duration;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.concurrent.ExecutionException;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertNotNull;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 蓝奏目录分页真实联调(b66477 约 93 页,每页 50 条)。默认不跑:
|
|
||||||
* mvn -pl parser -DskipTests=false -Dlz.live=true -Dtest=LzFolderPagingLiveTest test
|
|
||||||
* 加 -Dlz.live.full=true 会顺序翻完整个目录(约 2 分钟)。
|
|
||||||
*/
|
|
||||||
public class LzFolderPagingLiveTest {
|
|
||||||
|
|
||||||
private static final String OUI = "https://pan.lanzoui.com/b66477";
|
|
||||||
private static final String OUG = "https://pan.lanzoug.com/b66477";
|
|
||||||
|
|
||||||
private static Vertx vertx;
|
|
||||||
|
|
||||||
@AfterClass
|
|
||||||
public static void close() {
|
|
||||||
if (vertx != null) {
|
|
||||||
vertx.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
record Page(List<FileInfo> list, JsonObject info) {
|
|
||||||
String cursor() {
|
|
||||||
return info.getString("nextCursor");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void pacedPagesOneToThreeAreFullAndDistinct() throws Exception {
|
|
||||||
liveOnly();
|
|
||||||
Set<String> ids = new HashSet<>();
|
|
||||||
Page page = page(OUI, null, 1, null);
|
|
||||||
for (int n = 1; n <= 3; n++) {
|
|
||||||
if (n > 1) {
|
|
||||||
Thread.sleep(5000);
|
|
||||||
page = page(OUI, null, n, page.cursor());
|
|
||||||
}
|
|
||||||
// 上游每页 50 条原始项,其中 id=-1 的占位项(如 ***.apk)已被过滤
|
|
||||||
assertTrue("第 " + n + " 页 " + page.list().size(), page.list().size() >= 45 && page.list().size() <= 50);
|
|
||||||
assertEquals(Integer.valueOf(50), page.info().getInteger("pageSize"));
|
|
||||||
assertTrue(page.info().getBoolean("hasMore"));
|
|
||||||
assertNotNull(page.cursor());
|
|
||||||
page.list().forEach(f -> assertTrue("重复 " + f.getFileId(), ids.add(f.getFileId())));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 上游对紧跟的下一页常回 zt=4「请刷新,重试0」:必须重试成功或明确报错,不能当末页。 */
|
|
||||||
@Test
|
|
||||||
public void immediateNextPageIsNeverReportedAsEnd() throws Exception {
|
|
||||||
liveOnly();
|
|
||||||
Page first = page(OUG, null, 1, null);
|
|
||||||
try {
|
|
||||||
Page second = page(OUG, null, 2, first.cursor());
|
|
||||||
assertFalse(second.list().isEmpty());
|
|
||||||
assertTrue(second.info().getBoolean("hasMore"));
|
|
||||||
} catch (ExecutionException e) {
|
|
||||||
String msg = e.getCause().getMessage();
|
|
||||||
assertTrue(msg, msg.contains("稍后重试") || msg.contains("重新加载"));
|
|
||||||
}
|
|
||||||
Page again = page(OUG, null, 2, null);
|
|
||||||
assertEquals(50, again.list().size());
|
|
||||||
assertTrue(again.info().getBoolean("hasMore"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void passwordFolderIsSinglePageAndPageTwoIsEmpty() throws Exception {
|
|
||||||
liveOnly();
|
|
||||||
Page first = page("https://moteam.lanzoum.com/b00yaejvte", "1234", 1, null);
|
|
||||||
assertFalse(first.list().isEmpty());
|
|
||||||
assertFalse(first.info().getBoolean("hasMore"));
|
|
||||||
assertNull(first.cursor());
|
|
||||||
Thread.sleep(2000);
|
|
||||||
Page second = page("https://moteam.lanzoum.com/b00yaejvte", "1234", 2, null);
|
|
||||||
assertTrue(second.list().isEmpty());
|
|
||||||
assertFalse(second.info().getBoolean("hasMore"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void fileFromSecondPageDownloads() throws Exception {
|
|
||||||
liveOnly();
|
|
||||||
Page first = page(OUI, null, 1, null);
|
|
||||||
Thread.sleep(2000);
|
|
||||||
Page second = page(OUI, null, 2, first.cursor());
|
|
||||||
FileInfo small = second.list().get(0);
|
|
||||||
for (FileInfo f : second.list()) {
|
|
||||||
if (f.getSize() != null && small.getSize() != null && f.getSize() < small.getSize()) {
|
|
||||||
small = f;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
String url = ParserCreate.fromShareUrl("https://pan.lanzoui.com/" + small.getFileId())
|
|
||||||
.createTool().parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
|
||||||
HttpResponse<byte[]> response = HttpClient.newBuilder()
|
|
||||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
|
||||||
.connectTimeout(Duration.ofSeconds(20))
|
|
||||||
.build()
|
|
||||||
.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(120)).GET().build(),
|
|
||||||
HttpResponse.BodyHandlers.ofByteArray());
|
|
||||||
assertEquals(200, response.statusCode());
|
|
||||||
assertTrue(response.body().length > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void wholeFolderWithCursorHasNoDuplicatesAndEnds() throws Exception {
|
|
||||||
liveOnly();
|
|
||||||
Assume.assumeTrue(Boolean.getBoolean("lz.live.full"));
|
|
||||||
Set<String> ids = new HashSet<>();
|
|
||||||
String cursor = null;
|
|
||||||
int pages = 0;
|
|
||||||
int lastSize = -1;
|
|
||||||
for (int n = 1; n <= FolderPaging.MAX_PAGE; n++) {
|
|
||||||
Page page = page(OUI, null, n, cursor);
|
|
||||||
pages = n;
|
|
||||||
lastSize = page.list().size();
|
|
||||||
page.list().forEach(f -> assertTrue("重复 " + f.getFileId(), ids.add(f.getFileId())));
|
|
||||||
if (!page.info().getBoolean("hasMore")) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
cursor = page.cursor();
|
|
||||||
assertNotNull(cursor);
|
|
||||||
Thread.sleep(800);
|
|
||||||
}
|
|
||||||
assertTrue("应有多页", pages > 2);
|
|
||||||
assertTrue("末页应不足 50 条", lastSize < 50);
|
|
||||||
assertTrue(ids.size() > (pages - 1) * 49);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Page page(String url, String pwd, int page, String cursor) throws Exception {
|
|
||||||
ParserCreate create = ParserCreate.fromShareUrl(url);
|
|
||||||
if (pwd != null) {
|
|
||||||
create.setShareLinkInfoPwd(pwd);
|
|
||||||
}
|
|
||||||
create.getShareLinkInfo().getOtherParam().put(FolderPaging.PAGE, page);
|
|
||||||
if (cursor != null) {
|
|
||||||
create.getShareLinkInfo().getOtherParam().put(FolderPaging.CURSOR, cursor);
|
|
||||||
}
|
|
||||||
List<FileInfo> list = create.createTool().parseFileList()
|
|
||||||
.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
|
||||||
return new Page(list, FolderPaging.pageInfo(create.getShareLinkInfo()));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void liveOnly() {
|
|
||||||
Assume.assumeTrue(Boolean.getBoolean("lz.live"));
|
|
||||||
if (vertx == null) {
|
|
||||||
vertx = Vertx.vertx();
|
|
||||||
WebClientVertxInit.init(vertx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import cn.qaiu.WebClientVertxInit;
|
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
|
||||||
import io.vertx.core.MultiMap;
|
|
||||||
import io.vertx.core.Vertx;
|
|
||||||
import io.vertx.core.http.HttpServer;
|
|
||||||
import org.junit.After;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 蓝奏文件页离线回归:2026-11 起文件页 iframe 的下载 ajax 改名为 ajaxfiles.php,
|
|
||||||
* 其余字段(wp_sign / ajaxdata / kd / ves)不变。本地模拟 分享页 → /fn iframe → ajaxfiles.php → 下载域 302。
|
|
||||||
*/
|
|
||||||
public class LzToolAjaxfilesTest {
|
|
||||||
|
|
||||||
private static final String SHARE_KEY = "winx123";
|
|
||||||
private static final String FILE_ID = "333017612";
|
|
||||||
|
|
||||||
private Vertx vertx;
|
|
||||||
private HttpServer server;
|
|
||||||
private final List<String> ajaxPaths = new CopyOnWriteArrayList<>();
|
|
||||||
private final List<MultiMap> ajaxForms = new CopyOnWriteArrayList<>();
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void setup() throws Exception {
|
|
||||||
vertx = Vertx.vertx();
|
|
||||||
WebClientVertxInit.init(vertx);
|
|
||||||
server = vertx.createHttpServer().requestHandler(req -> {
|
|
||||||
String path = req.path();
|
|
||||||
if ("GET".equals(req.method().name()) && path.equals("/" + SHARE_KEY)) {
|
|
||||||
html(req.response(), sharePage());
|
|
||||||
} else if ("GET".equals(req.method().name()) && path.equals("/fn")) {
|
|
||||||
html(req.response(), iframePage());
|
|
||||||
} else if ("POST".equals(req.method().name()) && path.startsWith("/ajax")) {
|
|
||||||
req.setExpectMultipart(true);
|
|
||||||
req.endHandler(v -> {
|
|
||||||
ajaxPaths.add(req.uri());
|
|
||||||
ajaxForms.add(MultiMap.caseInsensitiveMultiMap().addAll(req.formAttributes()));
|
|
||||||
String dom = "http://127.0.0.1:" + server.actualPort();
|
|
||||||
req.response().putHeader("Content-Type", "application/json")
|
|
||||||
.end("{\"zt\":1,\"dom\":\"" + dom + "\",\"url\":\"?mock-token\",\"inf\":0}");
|
|
||||||
});
|
|
||||||
} else if (path.equals("/file/")) {
|
|
||||||
req.response().setStatusCode(302)
|
|
||||||
.putHeader("Location", "http://cdn.test/2026/11/25/steam.zip")
|
|
||||||
.end();
|
|
||||||
} else {
|
|
||||||
req.response().setStatusCode(404).end();
|
|
||||||
}
|
|
||||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
@After
|
|
||||||
public void cleanup() throws Exception {
|
|
||||||
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
|
||||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void filePageWithAjaxfilesIframeResolvesDirectLink() throws Exception {
|
|
||||||
String url = "http://127.0.0.1:" + server.actualPort() + "/" + SHARE_KEY;
|
|
||||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("lz").panName("蓝奏云").shareKey(SHARE_KEY)
|
|
||||||
.shareUrl(url).standardUrl(url).build();
|
|
||||||
|
|
||||||
String link = new LzTool(info).parse().toCompletionStage().toCompletableFuture()
|
|
||||||
.get(30, TimeUnit.SECONDS);
|
|
||||||
|
|
||||||
assertEquals("http://cdn.test/2026/11/25/steam.zip", link);
|
|
||||||
assertEquals(List.of("/ajaxfiles.php?file=" + FILE_ID), ajaxPaths);
|
|
||||||
MultiMap form = ajaxForms.get(0);
|
|
||||||
assertEquals("downprocess", form.get("action"));
|
|
||||||
assertEquals("test-wp-sign", form.get("sign"));
|
|
||||||
assertEquals("test-ajaxdata", form.get("websignkey"));
|
|
||||||
assertEquals("test-ajaxdata", form.get("signs"));
|
|
||||||
assertEquals("1", form.get("ves"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void html(io.vertx.core.http.HttpServerResponse res, String body) {
|
|
||||||
res.putHeader("Content-Type", "text/html; charset=utf-8").end(body);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String sharePage() {
|
|
||||||
return """
|
|
||||||
<!DOCTYPE html><html><head><title>steam.zip - 蓝奏云</title>
|
|
||||||
<meta name="description" content="文件大小:1.1 M" /></head><body>
|
|
||||||
<div class="n_box_3fn" id="filenajax">steam.zip</div>
|
|
||||||
<div class="n_file"><div class="n_filesize">大小:1.1 M</div>
|
|
||||||
<iframe class="n_downlink" name="1795620352" src="/fn?mock-fn-query" frameborder="0" scrolling="no"></iframe></div>
|
|
||||||
</body></html>
|
|
||||||
""";
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String iframePage() {
|
|
||||||
return """
|
|
||||||
<html><body><div id="tourl"></div>
|
|
||||||
<script type="text/javascript">
|
|
||||||
var wsk_sign = 'c20230908';
|
|
||||||
var wp_sign = 'test-wp-sign';
|
|
||||||
var ajaxdata = 'test-ajaxdata';
|
|
||||||
var kdns =1;
|
|
||||||
$.ajax({
|
|
||||||
type : 'post',
|
|
||||||
url : '/ajaxfiles.php?file=%s',
|
|
||||||
data : { 'action':'downprocess','websignkey':ajaxdata,'signs':ajaxdata,'sign':wp_sign,'websign':'','kd':kdns,'ves':1 },
|
|
||||||
dataType : 'json'
|
|
||||||
});
|
|
||||||
</script></body></html>
|
|
||||||
""".formatted(FILE_ID);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,293 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import cn.qaiu.WebClientVertxInit;
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
|
||||||
import cn.qaiu.parser.FolderPaging;
|
|
||||||
import io.vertx.core.MultiMap;
|
|
||||||
import io.vertx.core.Vertx;
|
|
||||||
import io.vertx.core.http.HttpServer;
|
|
||||||
import io.vertx.core.json.JsonArray;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
import org.junit.After;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
|
||||||
import java.util.concurrent.ExecutionException;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
|
||||||
import java.util.function.BiFunction;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertNotNull;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
import static org.junit.Assert.fail;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 蓝奏目录分页离线回归:本地模拟分享页与 filemoreajax.php。
|
|
||||||
* 上游真实行为(b66477 实测):每页 50 条,不足 50 即末页;zt=2「没有了」;
|
|
||||||
* 同一组 t/k 请求过快返回 {@code {"zt":4,"info":"请刷新,重试0","text":0}},隔约 2 秒同页可正常取到。
|
|
||||||
*/
|
|
||||||
public class LzToolFolderPagingTest {
|
|
||||||
|
|
||||||
private static final String SHARE_KEY = "b66477";
|
|
||||||
private static final String TOKEN_T = "1700000000";
|
|
||||||
private static final String TOKEN_K = "test-k-token";
|
|
||||||
private static final String RATE_LIMITED = "{\"zt\":4,\"info\":\"请刷新,重试0\",\"text\":0}";
|
|
||||||
|
|
||||||
private Vertx vertx;
|
|
||||||
private HttpServer server;
|
|
||||||
private final AtomicInteger pageGets = new AtomicInteger();
|
|
||||||
private final List<MultiMap> ajaxForms = new CopyOnWriteArrayList<>();
|
|
||||||
private final Map<String, AtomicInteger> ajaxCountByPg = new ConcurrentHashMap<>();
|
|
||||||
/** (pg, 该页第几次请求 从 1 开始) -> 响应体;返回 null 用默认三页数据 */
|
|
||||||
private volatile BiFunction<Integer, Integer, String> ajax = (pg, n) -> null;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void setup() throws Exception {
|
|
||||||
vertx = Vertx.vertx();
|
|
||||||
WebClientVertxInit.init(vertx);
|
|
||||||
server = vertx.createHttpServer().requestHandler(req -> {
|
|
||||||
if ("GET".equals(req.method().name()) && req.path().equals("/" + SHARE_KEY)) {
|
|
||||||
pageGets.incrementAndGet();
|
|
||||||
req.response().putHeader("Content-Type", "text/html; charset=utf-8").end(folderHtml());
|
|
||||||
} else if (req.path().equals("/filemoreajax.php")) {
|
|
||||||
req.setExpectMultipart(true);
|
|
||||||
req.endHandler(v -> {
|
|
||||||
MultiMap form = MultiMap.caseInsensitiveMultiMap().addAll(req.formAttributes());
|
|
||||||
ajaxForms.add(form);
|
|
||||||
int pg = Integer.parseInt(form.get("pg"));
|
|
||||||
int n = ajaxCountByPg.computeIfAbsent(String.valueOf(pg), k -> new AtomicInteger()).incrementAndGet();
|
|
||||||
String body = ajax.apply(pg, n);
|
|
||||||
req.response().putHeader("Content-Type", "text/json; charset=utf-8")
|
|
||||||
.end(body != null ? body : defaultPage(pg));
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
req.response().setStatusCode(404).end();
|
|
||||||
}
|
|
||||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
@After
|
|
||||||
public void cleanup() throws Exception {
|
|
||||||
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
|
||||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void defaultRequestStillReturnsFirstPageWithoutPlaceholder() throws Exception {
|
|
||||||
ShareLinkInfo info = info(null, null);
|
|
||||||
List<FileInfo> list = list(info);
|
|
||||||
assertEquals(49, list.size());
|
|
||||||
assertTrue(list.stream().noneMatch(f -> "-1".equals(f.getFileId())));
|
|
||||||
assertEquals("p1-0", list.get(0).getFileId());
|
|
||||||
assertTrue(list.get(0).getParserUrl().startsWith("http://nfd.test/v2/redirectUrl/lz/"));
|
|
||||||
JsonObject pageInfo = FolderPaging.pageInfo(info);
|
|
||||||
assertTrue(pageInfo.getBoolean("hasMore"));
|
|
||||||
assertEquals(2, (int) pageInfo.getInteger("nextPage"));
|
|
||||||
assertNotNull(pageInfo.getString("nextCursor"));
|
|
||||||
assertEquals(1, pageGets.get());
|
|
||||||
assertEquals("1", ajaxForms.get(0).get("pg"));
|
|
||||||
assertEquals("secret", ajaxForms.get(0).get("pwd"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void rateLimitedNextPageIsRetriedNotTreatedAsLastPage() throws Exception {
|
|
||||||
ajax = (pg, n) -> pg == 2 && n == 1 ? RATE_LIMITED : null;
|
|
||||||
ShareLinkInfo info = info(2, null);
|
|
||||||
List<FileInfo> list = list(info);
|
|
||||||
assertEquals(50, list.size());
|
|
||||||
assertEquals("p2-0", list.get(0).getFileId());
|
|
||||||
JsonObject pageInfo = FolderPaging.pageInfo(info);
|
|
||||||
assertTrue("zt=4 不能被当作末页", pageInfo.getBoolean("hasMore"));
|
|
||||||
assertEquals(2, ajaxCountByPg.get("2").get());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void persistentRateLimitFailsWithRetryableErrorInsteadOfEmptyEnd() throws Exception {
|
|
||||||
ajax = (pg, n) -> pg == 2 ? RATE_LIMITED : null;
|
|
||||||
ShareLinkInfo info = info(2, null);
|
|
||||||
try {
|
|
||||||
list(info);
|
|
||||||
fail("zt=4 一直不恢复时必须报错,不能返回空列表或 hasMore=false");
|
|
||||||
} catch (ExecutionException e) {
|
|
||||||
String msg = e.getCause().getMessage();
|
|
||||||
assertTrue(msg, msg.contains("请刷新,重试0"));
|
|
||||||
assertTrue(msg, msg.contains("不完整"));
|
|
||||||
assertTrue(msg, msg.contains("稍后重试"));
|
|
||||||
}
|
|
||||||
assertNull(FolderPaging.pageInfo(info));
|
|
||||||
assertEquals(1 + LzTool.LZ_REFRESH_RETRIES, ajaxCountByPg.get("2").get());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void cursorContinuesWithSameTokenWithoutReloadingPage() throws Exception {
|
|
||||||
ShareLinkInfo first = info(1, null);
|
|
||||||
list(first);
|
|
||||||
String cursor = FolderPaging.pageInfo(first).getString("nextCursor");
|
|
||||||
|
|
||||||
ShareLinkInfo second = info(2, cursor);
|
|
||||||
List<FileInfo> page2 = list(second);
|
|
||||||
assertEquals(50, page2.size());
|
|
||||||
assertEquals(1, pageGets.get());
|
|
||||||
MultiMap last = ajaxForms.get(ajaxForms.size() - 1);
|
|
||||||
assertEquals("2", last.get("pg"));
|
|
||||||
assertEquals(TOKEN_T, last.get("t"));
|
|
||||||
assertEquals(TOKEN_K, last.get("k"));
|
|
||||||
assertEquals("secret", last.get("pwd"));
|
|
||||||
|
|
||||||
ShareLinkInfo third = info(3, FolderPaging.pageInfo(second).getString("nextCursor"));
|
|
||||||
List<FileInfo> page3 = list(third);
|
|
||||||
assertEquals(9, page3.size());
|
|
||||||
JsonObject end = FolderPaging.pageInfo(third);
|
|
||||||
assertFalse(end.getBoolean("hasMore"));
|
|
||||||
assertNull(end.getString("nextCursor"));
|
|
||||||
assertNull(end.getValue("nextPage"));
|
|
||||||
|
|
||||||
Set<String> ids = new HashSet<>();
|
|
||||||
for (List<FileInfo> page : List.of(list(info(1, null)), page2, page3)) {
|
|
||||||
page.forEach(f -> assertTrue("跨页重复 " + f.getFileId(), ids.add(f.getFileId())));
|
|
||||||
}
|
|
||||||
assertEquals(49 + 50 + 9, ids.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void rateLimitedCursorRequestRetriesSamePage() throws Exception {
|
|
||||||
ShareLinkInfo first = info(1, null);
|
|
||||||
list(first);
|
|
||||||
ajax = (pg, n) -> pg == 2 && n == 1 ? RATE_LIMITED : null;
|
|
||||||
ShareLinkInfo second = info(2, FolderPaging.pageInfo(first).getString("nextCursor"));
|
|
||||||
assertEquals(50, list(second).size());
|
|
||||||
assertTrue(FolderPaging.pageInfo(second).getBoolean("hasMore"));
|
|
||||||
assertEquals(1, pageGets.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void pastLastPageIsEmptyAndEnds() throws Exception {
|
|
||||||
ajax = (pg, n) -> pg == 3 ? page(pg, 50) : pg == 4 ? "{\"zt\":2,\"info\":\"没有了\",\"text\":\"no file\"}" : null;
|
|
||||||
ShareLinkInfo third = info(3, null);
|
|
||||||
list(third);
|
|
||||||
ShareLinkInfo fourth = info(4, FolderPaging.pageInfo(third).getString("nextCursor"));
|
|
||||||
List<FileInfo> list = list(fourth);
|
|
||||||
assertTrue(list.isEmpty());
|
|
||||||
assertFalse(FolderPaging.pageInfo(fourth).getBoolean("hasMore"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void walkStopsAtShortPageWhenTargetIsBeyondEnd() throws Exception {
|
|
||||||
ShareLinkInfo info = info(5, null);
|
|
||||||
assertTrue(list(info).isEmpty());
|
|
||||||
assertFalse(FolderPaging.pageInfo(info).getBoolean("hasMore"));
|
|
||||||
assertEquals(null, ajaxCountByPg.get("4"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void deepPageWithoutCursorFailsFastWithHint() throws Exception {
|
|
||||||
ShareLinkInfo info = info(LzTool.LZ_MAX_WALK_PAGES + 1, null);
|
|
||||||
try {
|
|
||||||
list(info);
|
|
||||||
fail();
|
|
||||||
} catch (ExecutionException e) {
|
|
||||||
assertTrue(e.getCause().getMessage().contains("nextCursor"));
|
|
||||||
}
|
|
||||||
assertEquals(0, pageGets.get());
|
|
||||||
assertTrue(ajaxForms.isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void foreignCursorIsIgnored() throws Exception {
|
|
||||||
String foreign = LzFolderCursor.encode("bOTHER", "/filemoreajax.php?file=66477",
|
|
||||||
Map.of("fid", "66477", "t", "x", "k", "y"), 2, null);
|
|
||||||
ShareLinkInfo info = info(2, foreign);
|
|
||||||
assertEquals(50, list(info).size());
|
|
||||||
assertEquals(1, pageGets.get());
|
|
||||||
assertTrue(ajaxForms.stream().noneMatch(f -> "x".equals(f.get("t"))));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void emptyFolderKeepsLegacyFailure() throws Exception {
|
|
||||||
ajax = (pg, n) -> "{\"zt\":2,\"info\":\"没有文件\",\"text\":\"no file\"}";
|
|
||||||
try {
|
|
||||||
list(info(null, null));
|
|
||||||
fail();
|
|
||||||
} catch (ExecutionException e) {
|
|
||||||
assertTrue(e.getCause().getMessage().contains("没有文件"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<FileInfo> list(ShareLinkInfo info) throws Exception {
|
|
||||||
return new LzTool(info).parseFileList().toCompletionStage().toCompletableFuture().get(30, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
private ShareLinkInfo info(Integer page, String cursor) {
|
|
||||||
String url = "http://127.0.0.1:" + server.actualPort() + "/" + SHARE_KEY;
|
|
||||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("lz").panName("蓝奏云").shareKey(SHARE_KEY)
|
|
||||||
.shareUrl(url).standardUrl(url).sharePassword("secret").build();
|
|
||||||
info.getOtherParam().put("domainName", "http://nfd.test");
|
|
||||||
if (page != null) {
|
|
||||||
info.getOtherParam().put(FolderPaging.PAGE, page);
|
|
||||||
}
|
|
||||||
if (cursor != null) {
|
|
||||||
info.getOtherParam().put(FolderPaging.CURSOR, cursor);
|
|
||||||
}
|
|
||||||
return info;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String folderHtml() {
|
|
||||||
return """
|
|
||||||
<html><body><div id="infos"></div>
|
|
||||||
<script type="text/javascript">
|
|
||||||
var pwd;
|
|
||||||
var pgs;
|
|
||||||
var ibb6kj = '%s';
|
|
||||||
var _h9imc = '%s';
|
|
||||||
pgs =1;
|
|
||||||
function file(){
|
|
||||||
$.ajax({
|
|
||||||
type : 'post',
|
|
||||||
url : '/filemoreajax.php?file=66477',
|
|
||||||
data : {
|
|
||||||
'lx':2,
|
|
||||||
'fid':66477,
|
|
||||||
'uid':'234978',
|
|
||||||
'pg':pgs,
|
|
||||||
'rep':'0',
|
|
||||||
't':ibb6kj,
|
|
||||||
'k':_h9imc,
|
|
||||||
'up':1,
|
|
||||||
'ls':1,
|
|
||||||
'pwd':pwd },
|
|
||||||
dataType : 'json'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
</script></body></html>
|
|
||||||
""".formatted(TOKEN_T, TOKEN_K);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 默认三页:50(含一个 -1 占位)、50、9。 */
|
|
||||||
private static String defaultPage(int pg) {
|
|
||||||
return switch (pg) {
|
|
||||||
case 1, 2 -> page(pg, 50);
|
|
||||||
case 3 -> page(pg, 9);
|
|
||||||
default -> "{\"zt\":2,\"info\":\"没有了\",\"text\":\"no file\"}";
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String page(int pg, int count) {
|
|
||||||
JsonArray text = new JsonArray();
|
|
||||||
for (int i = 0; i < count; i++) {
|
|
||||||
String id = pg == 1 && i == 10 ? "-1" : "p" + pg + "-" + i;
|
|
||||||
text.add(new JsonObject().put("icon", "apk").put("t", 0).put("id", id)
|
|
||||||
.put("name_all", id + ".apk").put("size", "1.0 M").put("time", "2023-03-08"));
|
|
||||||
}
|
|
||||||
return new JsonObject().put("zt", 1).put("info", "sucess").put("text", text).encode();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,11 +4,8 @@ import org.junit.Test;
|
|||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -156,16 +153,6 @@ public class LzToolShareUrlTest {
|
|||||||
assertEquals("https://apifile.lanzouw.com/ajaxm.php?file=42", LzTool.fileAjaxTarget(html));
|
assertEquals("https://apifile.lanzouw.com/ajaxm.php?file=42", LzTool.fileAjaxTarget(html));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void ajaxfilesEndpointIsRecognized() {
|
|
||||||
assertEquals("/ajaxfiles.php?file=333017612",
|
|
||||||
LzTool.fileAjaxTarget("url : '/ajaxfiles.php?file=333017612',"));
|
|
||||||
assertEquals("https://apifile.lanzouw.com/ajaxfiles.php?file=7",
|
|
||||||
LzTool.fileAjaxTarget("url : 'https://apifile.lanzouw.com/ajaxfiles.php?file=7',"));
|
|
||||||
assertEquals("/ajaxm.php?file=5", LzTool.fileAjaxTarget("url : '/ajaxm.php?file=5',"));
|
|
||||||
assertNull(LzTool.fileAjaxTarget("url : '/ajaxfilex.php?file=5',"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void relativeFileAjaxFallsThroughToApifileBeforeWwww() {
|
public void relativeFileAjaxFallsThroughToApifileBeforeWwww() {
|
||||||
String html = "url : '/ajaxfile.php?file=150233466',";
|
String html = "url : '/ajaxfile.php?file=150233466',";
|
||||||
@@ -180,55 +167,6 @@ public class LzToolShareUrlTest {
|
|||||||
assertFalse(LzTool.ajaxOrigins("https://a.lanzouw.com/xxx").contains("https://apifile.lanzouw.com"));
|
assertFalse(LzTool.ajaxOrigins("https://a.lanzouw.com/xxx").contains("https://apifile.lanzouw.com"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void oldFolderPageSuppliesFilemoreParameters() {
|
|
||||||
String html = """
|
|
||||||
<script type="text/javascript">
|
|
||||||
var ibb6kj = '111';
|
|
||||||
var demoKey = 'abc';
|
|
||||||
function file(){
|
|
||||||
$.ajax({
|
|
||||||
url : '/filemoreajax.php?file=66477',
|
|
||||||
data : {
|
|
||||||
'lx':2,
|
|
||||||
'fid':66477,
|
|
||||||
'uid':'11',
|
|
||||||
'pg':pgs,
|
|
||||||
't':ibb6kj,
|
|
||||||
'k':demoKey,
|
|
||||||
'up':1,
|
|
||||||
'pwd':pwd
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
""";
|
|
||||||
Map<String, String> form = LzTool.folderAjaxForm(html, "1234");
|
|
||||||
assertEquals("66477", form.get("fid"));
|
|
||||||
assertEquals("111", form.get("t"));
|
|
||||||
assertEquals("abc", form.get("k"));
|
|
||||||
assertEquals("1", form.get("pg"));
|
|
||||||
assertEquals("1234", form.get("pwd"));
|
|
||||||
assertEquals("/filemoreajax.php?file=66477", LzTool.folderAjaxPath(html, "1234"));
|
|
||||||
assertFalse(LzTool.isAccessRiskPage(html));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void blankOffPageIsRiskControlNotExpiry() {
|
|
||||||
String html = """
|
|
||||||
<div class="off"><div class="off0"><div class="off1"></div></div></div>
|
|
||||||
<div style="display:none ">folder66477ufolder66477ip203.0.113.8</div>
|
|
||||||
""";
|
|
||||||
assertTrue(LzTool.isAccessRiskPage(html));
|
|
||||||
assertNull(LzTool.folderAjaxForm(html, null));
|
|
||||||
|
|
||||||
String cancelled = """
|
|
||||||
<div class="off"><div class="off1"></div></div>
|
|
||||||
文件取消分享了
|
|
||||||
""";
|
|
||||||
assertFalse(LzTool.isAccessRiskPage(cancelled));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void missingAjaxTargetStillPutsApifileBeforeWwww() {
|
public void missingAjaxTargetStillPutsApifileBeforeWwww() {
|
||||||
List<String> origins = LzTool.fileAjaxOrigins("https://www.lanzoux.com/ihLkw1gezutg", null);
|
List<String> origins = LzTool.fileAjaxOrigins("https://www.lanzoux.com/ihLkw1gezutg", null);
|
||||||
@@ -237,51 +175,4 @@ public class LzToolShareUrlTest {
|
|||||||
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
|
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
|
||||||
assertFalse(origins.get(0).contains("wwww"));
|
assertFalse(origins.get(0).contains("wwww"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void passwordPageUsesApifile2AndIsngisSign() {
|
|
||||||
String html = """
|
|
||||||
<div class="passwddiv-btn" onclick="down_p();"></div>
|
|
||||||
<input id="pwd" />
|
|
||||||
<script type="text/javascript">
|
|
||||||
function down_p(){
|
|
||||||
var kdns =1;
|
|
||||||
var isngis = '';
|
|
||||||
var isngis = 'SIGNVALUEFROMISNGIS';
|
|
||||||
var pwd =document.getElementById('pwd').value;
|
|
||||||
$.ajax({
|
|
||||||
type : 'post',
|
|
||||||
url : 'https://apifile2.woozooo.com/ajaxfile.php?file=333149117',
|
|
||||||
data : { 'action':'downprocess','sign':isngis,'kd':kdns,'p':pwd, },
|
|
||||||
dataType : 'json'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
""";
|
|
||||||
String target = LzTool.fileAjaxTarget(html);
|
|
||||||
assertEquals("https://apifile2.woozooo.com/ajaxfile.php?file=333149117", target);
|
|
||||||
Map<String, String> form = LzTool.fileAjaxForm(html, "1t54");
|
|
||||||
assertEquals("downprocess", form.get("action"));
|
|
||||||
assertEquals("SIGNVALUEFROMISNGIS", form.get("sign"));
|
|
||||||
assertEquals("1", form.get("kd"));
|
|
||||||
assertEquals("1t54", form.get("p"));
|
|
||||||
List<String> origins = LzTool.fileAjaxOrigins("https://wwaov.lanzouw.com/iNUOu4hbih4h", target);
|
|
||||||
assertEquals("https://apifile2.woozooo.com", origins.get(0));
|
|
||||||
|
|
||||||
io.vertx.core.MultiMap headers = LzTool.fileAjaxHeaders(
|
|
||||||
"https://wwaov.lanzouw.com/iNUOu4hbih4h", target);
|
|
||||||
assertEquals("https://wwaov.lanzouw.com/iNUOu4hbih4h", headers.get("referer"));
|
|
||||||
assertEquals("https://wwaov.lanzouw.com", headers.get("origin"));
|
|
||||||
assertEquals("cross-site", headers.get("Sec-Fetch-Site"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void sameOriginFileAjaxKeepsSameSiteFetchMetadata() {
|
|
||||||
io.vertx.core.MultiMap headers = LzTool.fileAjaxHeaders(
|
|
||||||
"https://apifile.lanzouw.com/fn?x", "/ajaxfile.php?file=1");
|
|
||||||
assertEquals("same-origin", headers.get("Sec-Fetch-Site"));
|
|
||||||
assertEquals("https://apifile.lanzouw.com", headers.get("origin"));
|
|
||||||
assertEquals("https://apifile.lanzouw.com/fn?x", headers.get("referer"));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -18,8 +18,6 @@ public class Ye2LoginHintTest {
|
|||||||
assertTrue(Ye2Tool.isYeLoginRequired(0, "需要登录才能下载"));
|
assertTrue(Ye2Tool.isYeLoginRequired(0, "需要登录才能下载"));
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(0, "ok"));
|
assertFalse(Ye2Tool.isYeLoginRequired(0, "ok"));
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(null, null));
|
assertFalse(Ye2Tool.isYeLoginRequired(null, null));
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(5113, "分享方提取流量包不足"));
|
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(5066, "该文件暂不支持在当前版本下载"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -1,410 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
|
||||||
import io.vertx.core.Future;
|
|
||||||
import io.vertx.core.json.JsonArray;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 123 分享单文件下载规则。不访问网络。
|
|
||||||
* mvn -pl parser -DskipTests=false -Dtest=Ye2ToolTest,Ye2LoginHintTest test
|
|
||||||
*/
|
|
||||||
public class Ye2ToolTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void downloadUsesShareKeyEncodedInDirectoryFileParameter() {
|
|
||||||
JsonObject directoryFileParameter = new JsonObject()
|
|
||||||
.put("shareKey", "iaKtVv-6OECd.html?from=dir")
|
|
||||||
.put("fileId", 123);
|
|
||||||
|
|
||||||
assertEquals("iaKtVv-6OECd",
|
|
||||||
Ye2Tool.resolveDownloadShareKey(directoryFileParameter, "-"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void downloadFallsBackToParserShareKeyWhenParameterHasNone() {
|
|
||||||
assertEquals("iaKtVv-6OECd",
|
|
||||||
Ye2Tool.resolveDownloadShareKey(new JsonObject(), "iaKtVv-6OECd.html"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void downloadAcceptsCapitalShareKeyFromParameter() {
|
|
||||||
JsonObject directoryFileParameter = new JsonObject()
|
|
||||||
.put("ShareKey", "iaKtVv-r4aCd");
|
|
||||||
|
|
||||||
assertEquals("iaKtVv-r4aCd",
|
|
||||||
Ye2Tool.resolveDownloadShareKey(directoryFileParameter, "-"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void anonymous123RequestsDoNotSendFakeBearerTokens() {
|
|
||||||
assertNull(Ye2Tool.bearerAuthorization(null));
|
|
||||||
assertNull(Ye2Tool.bearerAuthorization(""));
|
|
||||||
assertNull(Ye2Tool.bearerAuthorization("nologin"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void configured123TokenKeepsExistingBearerAuthentication() {
|
|
||||||
assertEquals("Bearer configured-token",
|
|
||||||
Ye2Tool.bearerAuthorization("configured-token"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shareDownloadUsesCurrentWebAppVersion() {
|
|
||||||
assertEquals("149", Ye2Tool.SHARE_WEB_APP_VERSION);
|
|
||||||
assertTrue(Ye2Tool.usableShareKey("iaKtVv-r4aCd"));
|
|
||||||
assertFalse(Ye2Tool.usableShareKey("-"));
|
|
||||||
assertFalse(Ye2Tool.usableShareKey(""));
|
|
||||||
assertFalse(Ye2Tool.usableShareKey(null));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void placeholderShareUrlIsReplacedWithShareKeyFromFileParameter() {
|
|
||||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
|
||||||
.type("ye")
|
|
||||||
.shareKey("-")
|
|
||||||
.shareUrl("https://www.123pan.com/s/-")
|
|
||||||
.standardUrl("https://www.123pan.com/s/-")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
Ye2Tool.applyResolvedShareKey(info, "iaKtVv-r4aCd");
|
|
||||||
|
|
||||||
assertEquals("iaKtVv-r4aCd", info.getShareKey());
|
|
||||||
assertEquals("https://www.123pan.com/s/iaKtVv-r4aCd", info.getShareUrl());
|
|
||||||
assertEquals("https://www.123pan.com/s/iaKtVv-r4aCd", info.getStandardUrl());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void realShareUrlIsKeptWhenResolvingDirectoryFile() {
|
|
||||||
String original = "https://1815268665.mshare.123pan.cn/123pan/iaKtVv-r4aCd";
|
|
||||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
|
||||||
.type("ye")
|
|
||||||
.shareKey("iaKtVv-r4aCd")
|
|
||||||
.shareUrl(original)
|
|
||||||
.standardUrl("https://www.123pan.com/s/iaKtVv-r4aCd")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
Ye2Tool.applyResolvedShareKey(info, "iaKtVv-r4aCd");
|
|
||||||
|
|
||||||
assertEquals(original, info.getShareUrl());
|
|
||||||
assertEquals("https://www.123pan.com/s/iaKtVv-r4aCd", info.getStandardUrl());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void placeholderStandardUrlDoesNotReplaceOriginalShareUrl() {
|
|
||||||
String original = "https://1815268665.mshare.123pan.cn/123pan/iaKtVv-r4aCd";
|
|
||||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
|
||||||
.type("ye")
|
|
||||||
.shareKey("-")
|
|
||||||
.shareUrl(original)
|
|
||||||
.standardUrl("https://www.123pan.com/s/-")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
Ye2Tool.applyResolvedShareKey(info, "iaKtVv-r4aCd");
|
|
||||||
|
|
||||||
assertEquals(original, info.getShareUrl());
|
|
||||||
assertEquals("https://www.123pan.com/s/iaKtVv-r4aCd", info.getStandardUrl());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void anonymousV2LoginCodeUsesExistingLoginHint() {
|
|
||||||
JsonObject json = new JsonObject()
|
|
||||||
.put("code", 5112)
|
|
||||||
.put("message", "您需要注册登录或付费后下载");
|
|
||||||
|
|
||||||
String msg = Ye2Tool.shareV2FailureMessage(json, "nologin");
|
|
||||||
|
|
||||||
assertTrue(msg.contains("auths.ye.authorization"));
|
|
||||||
assertTrue(msg.contains("上游信息: 您需要注册登录或付费后下载"));
|
|
||||||
assertFalse(msg.contains("downURLJson"));
|
|
||||||
assertFalse(msg.contains("download_info"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void loggedInV2TrafficShortageStaysOnV2Error() {
|
|
||||||
JsonObject json = new JsonObject()
|
|
||||||
.put("code", 5113)
|
|
||||||
.put("message", "分享方提取流量包不足");
|
|
||||||
|
|
||||||
String msg = Ye2Tool.shareV2FailureMessage(json, "configured-token");
|
|
||||||
|
|
||||||
assertTrue(msg.startsWith("v2接口返回异常:"));
|
|
||||||
assertTrue(msg.contains("5113"));
|
|
||||||
assertTrue(msg.contains("分享方提取流量包不足"));
|
|
||||||
assertFalse(msg.contains("downURLJson"));
|
|
||||||
assertFalse(msg.contains("download_info"));
|
|
||||||
assertFalse(msg.contains("auths.ye.authorization"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void oldClientErrorIsNotRewrittenAsPersonalFileApiFailure() {
|
|
||||||
JsonObject json = new JsonObject()
|
|
||||||
.put("code", 5066)
|
|
||||||
.put("message", "该文件暂不支持在当前版本下载");
|
|
||||||
|
|
||||||
String msg = Ye2Tool.shareV2FailureMessage(json, "configured-token");
|
|
||||||
|
|
||||||
assertTrue(msg.startsWith("v2接口返回异常:"));
|
|
||||||
assertTrue(msg.contains("5066"));
|
|
||||||
assertFalse(msg.contains("downURLJson"));
|
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(5066, "该文件暂不支持在当前版本下载"));
|
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(5113, "分享方提取流量包不足"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void signatureUsesActualSharePathPlatformAndVersion() {
|
|
||||||
long time = 1_700_000_000_000L;
|
|
||||||
long randomA = 42L;
|
|
||||||
String traffic = Ye2Tool.signMaterial(
|
|
||||||
Ye2Tool.SHARE_TRAFFIC_CHECK_PATH, Ye2Tool.SHARE_PLATFORM, Ye2Tool.SHARE_WEB_APP_VERSION, time, randomA);
|
|
||||||
String download = Ye2Tool.signMaterial(
|
|
||||||
Ye2Tool.SHARE_DOWNLOAD_INFO_PATH, Ye2Tool.SHARE_PLATFORM, Ye2Tool.SHARE_WEB_APP_VERSION, time, randomA);
|
|
||||||
|
|
||||||
assertTrue(traffic.contains("|/api/share/download/traffic/check|web|149|"));
|
|
||||||
assertTrue(download.contains("|/api/v2/share/download/info|web|149|"));
|
|
||||||
assertFalse(traffic.contains("/b/api/"));
|
|
||||||
assertFalse(download.contains("/b/api/"));
|
|
||||||
assertEquals(Ye2Tool.signQuery(
|
|
||||||
Ye2Tool.SHARE_DOWNLOAD_INFO_PATH, "web", "149", time, randomA),
|
|
||||||
Ye2Tool.signQuery(Ye2Tool.SHARE_DOWNLOAD_INFO_PATH, Ye2Tool.SHARE_PLATFORM,
|
|
||||||
Ye2Tool.SHARE_WEB_APP_VERSION, time, randomA));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void mshareAndPlainSharePageUseDecodedShareHost() {
|
|
||||||
String host = "https://1815268665.share.123pan.cn";
|
|
||||||
assertEquals(host, Ye2Tool.shareApiOrigin(
|
|
||||||
"https://1815268665.mshare.123pan.cn/123pan/iaKtVv-r4aCd",
|
|
||||||
"https://www.123pan.com/s/iaKtVv-r4aCd",
|
|
||||||
"iaKtVv-r4aCd"));
|
|
||||||
assertEquals(host, Ye2Tool.shareApiOrigin(
|
|
||||||
"https://1815268665.share.123pan.cn/123pan/iaKtVv-r4aCd?notoken=1",
|
|
||||||
null,
|
|
||||||
"iaKtVv-r4aCd"));
|
|
||||||
assertEquals(host, Ye2Tool.shareApiOrigin(
|
|
||||||
"https://www.123pan.com/s/iaKtVv-r4aCd",
|
|
||||||
"https://yun.123pan.com/s/iaKtVv-r4aCd",
|
|
||||||
"iaKtVv-r4aCd"));
|
|
||||||
assertFalse(host.contains("mshare"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void maliciousHostIsNotCalled() {
|
|
||||||
AtomicInteger calls = new AtomicInteger();
|
|
||||||
Future<String> blocked = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
return Future.succeededFuture(new JsonObject().put("code", 0));
|
|
||||||
}, sampleRequest("http://127.0.0.1/latest/meta-data", "iaKtVv-r4aCd", "configured-token"));
|
|
||||||
Future<String> disguised = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
return Future.succeededFuture(new JsonObject().put("code", 0));
|
|
||||||
}, sampleRequest("https://1815268665.share.123pan.cn.evil.com/123pan/iaKtVv-r4aCd",
|
|
||||||
"iaKtVv-r4aCd", "configured-token"));
|
|
||||||
Future<String> unknownKey = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
return Future.succeededFuture(new JsonObject().put("code", 0));
|
|
||||||
}, sampleRequest("https://evil.example/123pan/not-a-real-key", "not-a-real-key", "configured-token"));
|
|
||||||
|
|
||||||
assertEquals(0, calls.get());
|
|
||||||
assertTrue(blocked.failed());
|
|
||||||
assertTrue(disguised.failed());
|
|
||||||
assertTrue(unknownKey.failed());
|
|
||||||
assertTrue(blocked.cause().getMessage().contains("分享域名"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void successChecksTrafficThenDownloadsOnShareHost() {
|
|
||||||
List<Ye2Tool.ShareHttpCall> seen = new ArrayList<>();
|
|
||||||
Future<String> result = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
seen.add(call);
|
|
||||||
if (seen.size() == 1) {
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject()
|
|
||||||
.put("isBlocked", false)
|
|
||||||
.put("isTrafficExceeded", false)
|
|
||||||
.put("isPay", false)));
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject()
|
|
||||||
.put("downloadPath", "/123/file.zip")
|
|
||||||
.put("dispatchList", new JsonArray()
|
|
||||||
.add(new JsonObject().put("prefix", "https://cdn-a.example/"))
|
|
||||||
.add(new JsonObject().put("prefix", "https://cdn-b.example/")))));
|
|
||||||
}, sampleRequest("https://1815268665.mshare.123pan.cn/123pan/iaKtVv-r4aCd",
|
|
||||||
"iaKtVv-r4aCd", "configured-token"));
|
|
||||||
|
|
||||||
assertTrue(result.succeeded());
|
|
||||||
assertEquals("https://cdn-a.example/123/file.zip", result.result());
|
|
||||||
assertEquals(2, seen.size());
|
|
||||||
|
|
||||||
Ye2Tool.ShareHttpCall traffic = seen.get(0);
|
|
||||||
Ye2Tool.ShareHttpCall download = seen.get(1);
|
|
||||||
assertEquals("https://1815268665.share.123pan.cn", traffic.origin);
|
|
||||||
assertEquals(Ye2Tool.SHARE_TRAFFIC_CHECK_PATH, traffic.path);
|
|
||||||
assertEquals(Ye2Tool.SHARE_DOWNLOAD_INFO_PATH, download.path);
|
|
||||||
assertEquals(traffic.origin, download.origin);
|
|
||||||
assertFalse(traffic.url().contains("api.123278.com"));
|
|
||||||
assertFalse(traffic.url().contains("/b/api/"));
|
|
||||||
assertEquals(Ye2Tool.signQuery(traffic.path, "web", "149", 1_700_000_000_000L, 42L), traffic.query);
|
|
||||||
assertEquals(Ye2Tool.signQuery(download.path, "web", "149", 1_700_000_000_000L, 42L), download.query);
|
|
||||||
|
|
||||||
assertEquals("149", traffic.headers.get("App-Version"));
|
|
||||||
assertEquals("web", traffic.headers.get("platform"));
|
|
||||||
assertEquals("Bearer configured-token", traffic.headers.get("Authorization"));
|
|
||||||
assertEquals("application/json;charset=UTF-8", traffic.headers.get("Content-Type"));
|
|
||||||
assertEquals("https://1815268665.share.123pan.cn", traffic.headers.get("Origin"));
|
|
||||||
assertEquals("https://1815268665.share.123pan.cn/123pan/iaKtVv-r4aCd", traffic.headers.get("Referer"));
|
|
||||||
assertEquals("iaKtVv-r4aCd", traffic.body.getString("shareKey"));
|
|
||||||
assertEquals(Long.valueOf(2468L), traffic.body.getJsonArray("fileIds").getLong(0));
|
|
||||||
assertFalse(traffic.body.containsKey("payType"));
|
|
||||||
|
|
||||||
assertEquals("iaKtVv-r4aCd", download.body.getString("ShareKey"));
|
|
||||||
assertEquals(Long.valueOf(2468L), download.body.getLong("FileID"));
|
|
||||||
assertEquals("etag-flag", download.body.getString("S3keyFlag"));
|
|
||||||
assertEquals(Long.valueOf(6915371L), download.body.getLong("Size"));
|
|
||||||
assertEquals("abcetag", download.body.getString("Etag"));
|
|
||||||
assertFalse(download.body.containsKey("OrderId"));
|
|
||||||
assertFalse(download.body.containsKey("payType"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void directoryDownloadUsesShareKeyHostNotPlaceholderPage() {
|
|
||||||
List<Ye2Tool.ShareHttpCall> seen = new ArrayList<>();
|
|
||||||
Ye2Tool.ShareFileRequest request = sampleRequest(
|
|
||||||
"https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "configured-token");
|
|
||||||
Future<String> result = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
seen.add(call);
|
|
||||||
if (seen.size() == 1) {
|
|
||||||
return Future.succeededFuture(openTraffic());
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject()
|
|
||||||
.put("downloadPath", "folder/file.bin")
|
|
||||||
.put("dispatchList", new JsonArray().add(
|
|
||||||
new JsonObject().put("prefix", "https://cdn.example/root")))));
|
|
||||||
}, request);
|
|
||||||
|
|
||||||
assertTrue(result.succeeded());
|
|
||||||
assertEquals("https://cdn.example/root/folder/file.bin", result.result());
|
|
||||||
assertEquals("https://1815268665.share.123pan.cn", seen.get(0).origin);
|
|
||||||
assertFalse(seen.get(0).url().contains("www.123pan.com"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void absoluteDownloadPathIsKept() {
|
|
||||||
Future<String> result = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
if (call.path.equals(Ye2Tool.SHARE_TRAFFIC_CHECK_PATH)) {
|
|
||||||
return Future.succeededFuture(openTraffic());
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject()
|
|
||||||
.put("downloadPath", "https://cdn.example/already.zip")
|
|
||||||
.put("dispatchList", new JsonArray().add(
|
|
||||||
new JsonObject().put("prefix", "https://ignored.example/")))));
|
|
||||||
}, sampleRequest("https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "configured-token"));
|
|
||||||
|
|
||||||
assertEquals("https://cdn.example/already.zip", result.result());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void blockedPayAndMissingLinkDoNotContinue() {
|
|
||||||
Future<String> blocked = downloadAfterTraffic(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject().put("isBlocked", true).put("isPay", false)));
|
|
||||||
Future<String> pay = downloadAfterTraffic(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject().put("isPay", true)));
|
|
||||||
Future<String> missing = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
if (call.path.equals(Ye2Tool.SHARE_TRAFFIC_CHECK_PATH)) {
|
|
||||||
return Future.succeededFuture(openTraffic());
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(new JsonObject().put("code", 0).put("data", new JsonObject()));
|
|
||||||
}, sampleRequest("https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "configured-token"));
|
|
||||||
|
|
||||||
Future<String> exceeded = downloadAfterTraffic(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject().put("isTrafficExceeded", true)));
|
|
||||||
|
|
||||||
assertTrue(blocked.cause().getMessage().contains("不会自动下单"));
|
|
||||||
assertTrue(pay.cause().getMessage().contains("不会自动下单"));
|
|
||||||
assertTrue(exceeded.cause().getMessage().contains("不会自动购买"));
|
|
||||||
assertTrue(missing.cause().getMessage().contains("未返回下载链接"));
|
|
||||||
assertFalse(blocked.cause().getMessage().contains("OrderId"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void loginAndTrafficErrorsStayOnTheStepThatReturnedThem() {
|
|
||||||
AtomicInteger calls = new AtomicInteger();
|
|
||||||
Future<String> login = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 5112)
|
|
||||||
.put("message", "您需要注册登录或付费后下载"));
|
|
||||||
}, sampleRequest("https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "nologin"));
|
|
||||||
Future<String> traffic = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
if (call.path.equals(Ye2Tool.SHARE_TRAFFIC_CHECK_PATH)) {
|
|
||||||
assertNull(call.headers.get("Authorization"));
|
|
||||||
return Future.succeededFuture(openTraffic());
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 5113)
|
|
||||||
.put("message", "分享方提取流量包不足"));
|
|
||||||
}, sampleRequest("https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "nologin"));
|
|
||||||
|
|
||||||
assertEquals(3, calls.get());
|
|
||||||
assertTrue(login.cause().getMessage().contains("auths.ye.authorization"));
|
|
||||||
assertTrue(traffic.cause().getMessage().contains("5113"));
|
|
||||||
assertFalse(traffic.cause().getMessage().contains("downURLJson"));
|
|
||||||
assertFalse(traffic.cause().getMessage().contains("download_info"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Future<String> downloadAfterTraffic(JsonObject trafficJson) {
|
|
||||||
AtomicInteger calls = new AtomicInteger();
|
|
||||||
Future<String> result = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
return Future.succeededFuture(trafficJson);
|
|
||||||
}, sampleRequest("https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "configured-token"));
|
|
||||||
assertEquals(1, calls.get());
|
|
||||||
assertTrue(result.failed());
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static JsonObject openTraffic() {
|
|
||||||
return new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject()
|
|
||||||
.put("isBlocked", false)
|
|
||||||
.put("isTrafficExceeded", false)
|
|
||||||
.put("isPay", false));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Ye2Tool.ShareFileRequest sampleRequest(String shareUrl, String shareKey, String token) {
|
|
||||||
return new Ye2Tool.ShareFileRequest(
|
|
||||||
shareUrl,
|
|
||||||
"https://www.123pan.com/s/" + shareKey,
|
|
||||||
shareKey,
|
|
||||||
"",
|
|
||||||
2468L,
|
|
||||||
"etag-flag",
|
|
||||||
6915371L,
|
|
||||||
"abcetag",
|
|
||||||
token,
|
|
||||||
1_700_000_000_000L,
|
|
||||||
42L);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 永硕入口页解析与重定向的离线测试,不访问网络。
|
|
||||||
*/
|
|
||||||
public class YsToolPasswordPageTest {
|
|
||||||
|
|
||||||
private static final String NEW_GATE = ""
|
|
||||||
+ "<div id=\"entryConfig\" style=\"display:none\" data-dlmc=\"qaiu\"\n"
|
|
||||||
+ " data-verification-token=\"new-token_value.1\"></div>\n"
|
|
||||||
+ "<form id=\"loginForm\"></form>\n";
|
|
||||||
|
|
||||||
private static final String OLD_GATE = ""
|
|
||||||
+ "<script>var cfg = { RequestVerificationToken': 'legacy-token' };</script>\n"
|
|
||||||
+ "<div id=\"loginPopup\"></div>\n"
|
|
||||||
+ "<form action=\"/?handler=VerifyPassword\"></form>\n";
|
|
||||||
|
|
||||||
private static final String OPEN_SPACE = ""
|
|
||||||
+ "<script>window.htxx = {\"dlmc\":\"fufu1\",\"qqdz\":\"https://c6.ysepan.com/api/\","
|
|
||||||
+ "\"yh\":{\"isgly\":false},\"ym\":\"ysepan.com\"};</script>";
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testNewPasswordPageTokenAndDlmc() {
|
|
||||||
assertTrue(YsTool.isPasswordPage(NEW_GATE));
|
|
||||||
assertEquals("new-token_value.1", YsTool.extractAntiforgery(NEW_GATE));
|
|
||||||
assertEquals("qaiu", YsTool.extractDlmc(NEW_GATE));
|
|
||||||
assertNull(YsTool.extractHtxx(NEW_GATE));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testLegacyPasswordPageStillParsed() {
|
|
||||||
assertTrue(YsTool.isPasswordPage(OLD_GATE));
|
|
||||||
assertEquals("legacy-token", YsTool.extractAntiforgery(OLD_GATE));
|
|
||||||
assertNull(YsTool.extractDlmc(OLD_GATE));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testNewTokenWinsWhenBothFormatsExist() {
|
|
||||||
String mixed = NEW_GATE + OLD_GATE;
|
|
||||||
assertEquals("new-token_value.1", YsTool.extractAntiforgery(mixed));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testSingleQuotedAttributes() {
|
|
||||||
String html = "<div id='entryConfig' data-dlmc='sohehe4' "
|
|
||||||
+ "data-verification-token='quoted-token'></div>";
|
|
||||||
assertTrue(YsTool.isPasswordPage(html));
|
|
||||||
assertEquals("quoted-token", YsTool.extractAntiforgery(html));
|
|
||||||
assertEquals("sohehe4", YsTool.extractDlmc(html));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testOpenSpaceIsNotPasswordPageAndKeepsNestedHtxx() {
|
|
||||||
assertFalse(YsTool.isPasswordPage(OPEN_SPACE));
|
|
||||||
JsonObject htxx = YsTool.extractHtxx(OPEN_SPACE);
|
|
||||||
assertEquals("fufu1", htxx.getString("dlmc"));
|
|
||||||
assertEquals("https://c6.ysepan.com/api/", htxx.getString("qqdz"));
|
|
||||||
assertFalse(htxx.getJsonObject("yh").getBoolean("isgly"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testYs168RedirectTargetsYsepanPasswordEndpoint() {
|
|
||||||
String next = YsTool.resolveRedirect("https://qaiu.ys168.com/", "https://qaiu.ysepan.com");
|
|
||||||
assertEquals("https://qaiu.ysepan.com", next);
|
|
||||||
assertEquals("https://qaiu.ysepan.com", YsTool.originOf(next));
|
|
||||||
assertEquals("https://qaiu.ysepan.com/?handler=VerifyPassword",
|
|
||||||
YsTool.verifyPasswordEndpoint(YsTool.originOf(next)));
|
|
||||||
assertFalse(YsTool.verifyPasswordEndpoint(YsTool.originOf(next)).contains("ys168.com"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testProtocolRelativeAndRelativeRedirects() {
|
|
||||||
String protocolRelative = YsTool.resolveRedirect(
|
|
||||||
"https://qaiu.ys168.com/", "//qaiu.ysepan.com/");
|
|
||||||
assertEquals("https://qaiu.ysepan.com/", protocolRelative);
|
|
||||||
assertEquals("https://qaiu.ysepan.com", YsTool.originOf(protocolRelative));
|
|
||||||
|
|
||||||
String relative = YsTool.resolveRedirect(
|
|
||||||
"https://qaiu.ysupan.com/", "/login.aspx?d=qaiu");
|
|
||||||
assertEquals("https://qaiu.ysupan.com/login.aspx?d=qaiu", relative);
|
|
||||||
assertEquals("https://qaiu.ysupan.com", YsTool.originOf(relative));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testNonDefaultPortKeptInOrigin() {
|
|
||||||
assertEquals("https://y.ys168.com:8100", YsTool.originOf("https://y.ys168.com:8100/"));
|
|
||||||
assertEquals("https://qaiu.ysepan.com", YsTool.originOf("https://qaiu.ysepan.com:443/"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testWrongPasswordUsesUpstreamMessageWithoutSecrets() {
|
|
||||||
String body = "{\"success\":false,\"code\":\"invalid_password\",\"message\":\"密码错误\"}";
|
|
||||||
assertEquals("密码错误", YsTool.passwordFailureMessage(400, body));
|
|
||||||
|
|
||||||
String leaked = "{\"success\":false,\"code\":\"invalid_password\",\"message\":\"eyJhbGciOiJIUzI1NiJ9.secret\"}";
|
|
||||||
assertEquals("密码错误", YsTool.passwordFailureMessage(400, leaked));
|
|
||||||
|
|
||||||
String other = "{\"success\":false,\"message\":\"空间已关闭\"}";
|
|
||||||
assertEquals("空间已关闭", YsTool.passwordFailureMessage(400, other));
|
|
||||||
|
|
||||||
assertEquals("密码验证失败 HTTP 500", YsTool.passwordFailureMessage(500, "<html>CfDJ8secret</html>"));
|
|
||||||
assertEquals("密码验证失败 HTTP 400", YsTool.passwordFailureMessage(400, ""));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testBlankRedirectIsRejected() {
|
|
||||||
assertNull(YsTool.resolveRedirect("https://qaiu.ys168.com/", " "));
|
|
||||||
assertNull(YsTool.resolveRedirect("https://qaiu.ys168.com/", null));
|
|
||||||
assertNull(YsTool.originOf("not a url"));
|
|
||||||
assertFalse(YsTool.isPasswordPage(null));
|
|
||||||
assertNull(YsTool.extractAntiforgery(null));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -97,13 +97,23 @@ public class YsToolTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testYsslOpenSpaceRealDownload() throws Exception {
|
public void testOfficialSampleUrlRealDownload() throws Exception {
|
||||||
// 旧样例 lu20.jpg 已从示例空间删除(直链 404)。改为现场列出示例空间里的小文件再下载。
|
String official = "https://ys-l.ysepan.com/wap/yssl/A95UIe495EkSKE/Bc8hF8Nsbl2I4Ec6vAm5EGe9HU36iC/lu20.jpg";
|
||||||
FileInfo file = firstSmallFile("https://yssl.ysepan.com/", null, 2_000_000);
|
String withForcePrefix = "https://ys-l.ysepan.com/wap/yssl/_A95UIe495EkSKE/Bc8hF8Nsbl2I4Ec6vAm5EGe9HU36iC/lu20.jpg";
|
||||||
assertNotNull("示例空间应至少有一个可下载的小文件", file);
|
|
||||||
Buffer body = downloadParsedFile(file, "https://yssl.ysepan.com/");
|
Buffer ok = download(official, "https://yssl.ysepan.com/");
|
||||||
assertEquals(file.getSize().longValue(), body.length());
|
assertTrue("官方直链应能下载到 JPEG", ok.length() > 1000);
|
||||||
System.out.println("yssl real download ok, file=" + file.getFileName() + ", size=" + body.length());
|
assertEquals((byte) 0xFF, ok.getByte(0));
|
||||||
|
assertEquals((byte) 0xD8, ok.getByte(1));
|
||||||
|
|
||||||
|
int forceStatus = webClient.getAbs(withForcePrefix)
|
||||||
|
.putHeader("User-Agent", "Mozilla/5.0")
|
||||||
|
.putHeader("Referer", "https://yssl.ysepan.com/")
|
||||||
|
.send()
|
||||||
|
.toCompletionStage().toCompletableFuture()
|
||||||
|
.get(30, TimeUnit.SECONDS)
|
||||||
|
.statusCode();
|
||||||
|
assertNotEquals("带 _ 前缀的直链应失败(文件不存在)", 200, forceStatus);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -239,173 +249,44 @@ public class YsToolTest {
|
|||||||
assertTrue("sohehe4 应有多个目录", dirs.size() >= 3);
|
assertTrue("sohehe4 应有多个目录", dirs.size() >= 3);
|
||||||
assertTrue(dirs.stream().allMatch(d -> "folder".equals(d.getFileType())));
|
assertTrue(dirs.stream().allMatch(d -> "folder".equals(d.getFileType())));
|
||||||
|
|
||||||
FileInfo file = null;
|
String dirId = dirs.stream()
|
||||||
for (FileInfo dir : dirs) {
|
.filter(d -> d.getFileName() != null && d.getFileName().contains("留言"))
|
||||||
if (!"folder".equals(dir.getFileType())) {
|
.map(FileInfo::getFileId)
|
||||||
continue;
|
|
||||||
}
|
|
||||||
file = firstSmallFileInDir("https://sohehe4.ysepan.com/", "1234", dir.getFileId(), 5_000_000);
|
|
||||||
if (file != null) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assertNotNull("sohehe4 应能找到可下载的小文件", file);
|
|
||||||
Buffer body = downloadParsedFile(file, "https://sohehe4.ysepan.com/");
|
|
||||||
assertEquals(file.getSize().longValue(), body.length());
|
|
||||||
System.out.println("sohehe4 real download ok, file=" + file.getFileName()
|
|
||||||
+ ", size=" + body.length());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testQaiuRequiresPassword() throws Exception {
|
|
||||||
ParserCreate create = ParserCreate.fromShareUrl("https://qaiu.ysepan.com/");
|
|
||||||
create.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
|
|
||||||
try {
|
|
||||||
create.createTool().parseFileList()
|
|
||||||
.toCompletionStage().toCompletableFuture()
|
|
||||||
.get(60, TimeUnit.SECONDS);
|
|
||||||
fail("未提供密码时应拒绝进入");
|
|
||||||
} catch (java.util.concurrent.ExecutionException e) {
|
|
||||||
assertTrue(e.getCause().getMessage(), e.getCause().getMessage().contains("空间需要访问密码"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testFufu1Ys168RedirectOpenSpace() throws Exception {
|
|
||||||
List<FileInfo> roots = fileList("https://fufu1.ys168.com/", null);
|
|
||||||
assertNotNull(roots);
|
|
||||||
assertTrue(roots.stream().anyMatch(f -> "游戏3".equals(f.getFileName())));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testQaiuYs168PasswordRedirectAndRealDownload() throws Exception {
|
|
||||||
List<FileInfo> dirs = fileList("https://qaiu.ys168.com/", "qaiuys168");
|
|
||||||
assertNotNull(dirs);
|
|
||||||
assertFalse(dirs.isEmpty());
|
|
||||||
FileInfo app = dirs.stream()
|
|
||||||
.filter(d -> d.getFileName() != null && d.getFileName().contains("app"))
|
|
||||||
.findFirst()
|
.findFirst()
|
||||||
.orElse(dirs.get(0));
|
.orElse(dirs.get(0).getFileId());
|
||||||
|
|
||||||
List<FileInfo> files = fileList("https://qaiu.ys168.com/", "qaiuys168", app.getFileId());
|
ParserCreate filesCreate = ParserCreate.fromShareUrl("https://sohehe4.ysepan.com/");
|
||||||
FileInfo zip = files.stream()
|
filesCreate.getShareLinkInfo().setSharePassword("1234");
|
||||||
.filter(f -> "file".equals(f.getFileType()))
|
filesCreate.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
|
||||||
.filter(f -> f.getFileName() != null && f.getFileName().contains("Pycharm"))
|
filesCreate.getShareLinkInfo().getOtherParam().put("dirId", dirId);
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
assertNotNull("ys168 重定向后应能列出 Pycharm 压缩包", zip);
|
|
||||||
|
|
||||||
String param = zip.getParserUrl().substring(zip.getParserUrl().lastIndexOf('/') + 1);
|
List<FileInfo> files = filesCreate.createTool().parseFileList()
|
||||||
JsonObject paramJson = new JsonObject(CommonUtils.urlBase64Decode(param));
|
|
||||||
String downloadUrl = paramJson.getString("downloadUrl");
|
|
||||||
assertNotNull(downloadUrl);
|
|
||||||
assertTrue(downloadUrl.contains("ysepan.com"));
|
|
||||||
assertFalse(downloadUrl.contains("ys168.com"));
|
|
||||||
assertFalse(downloadUrl.contains("/_"));
|
|
||||||
|
|
||||||
Buffer body = download(downloadUrl, "https://qaiu.ysepan.com/");
|
|
||||||
assertEquals(zip.getSize().longValue(), body.length());
|
|
||||||
assertEquals('P', (char) body.getByte(0));
|
|
||||||
assertEquals('K', (char) body.getByte(1));
|
|
||||||
System.out.println("qaiu ys168 redirect download ok, size=" + body.length());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testBackupDomainsOpenAndPasswordSpaces() throws Exception {
|
|
||||||
for (String host : new String[]{"cccpan.com", "uupan.net", "ysok.net"}) {
|
|
||||||
List<FileInfo> openDirs = fileList("https://fufu1." + host + "/", null);
|
|
||||||
assertNotNull(host, openDirs);
|
|
||||||
assertFalse(host + " 无密码空间目录为空", openDirs.isEmpty());
|
|
||||||
assertTrue(host, openDirs.stream().anyMatch(d -> "游戏3".equals(d.getFileName())));
|
|
||||||
|
|
||||||
List<FileInfo> lockedDirs = fileList("https://qaiu." + host + "/", "qaiuys168");
|
|
||||||
assertNotNull(host, lockedDirs);
|
|
||||||
assertFalse(host + " 密码空间目录为空", lockedDirs.isEmpty());
|
|
||||||
assertTrue(host + " " + lockedDirs.stream().map(FileInfo::getFileName).toList(),
|
|
||||||
lockedDirs.stream().anyMatch(d -> d.getFileName() != null && d.getFileName().contains("app")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static List<FileInfo> fileList(String url, String pwd) throws Exception {
|
|
||||||
return fileList(url, pwd, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static List<FileInfo> fileList(String url, String pwd, String dirId) throws Exception {
|
|
||||||
return fileList(url, pwd, dirId, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static List<FileInfo> fileList(String url, String pwd, String dirId, String zml) throws Exception {
|
|
||||||
ParserCreate create = ParserCreate.fromShareUrl(url);
|
|
||||||
if (pwd != null) {
|
|
||||||
create.getShareLinkInfo().setSharePassword(pwd);
|
|
||||||
}
|
|
||||||
create.getShareLinkInfo().getOtherParam().put("domainName", "http://localhost");
|
|
||||||
if (dirId != null) {
|
|
||||||
create.getShareLinkInfo().getOtherParam().put("dirId", dirId);
|
|
||||||
}
|
|
||||||
if (zml != null) {
|
|
||||||
create.getShareLinkInfo().getOtherParam().put("zml", zml);
|
|
||||||
}
|
|
||||||
return create.createTool().parseFileList()
|
|
||||||
.toCompletionStage().toCompletableFuture()
|
.toCompletionStage().toCompletableFuture()
|
||||||
.get(60, TimeUnit.SECONDS);
|
.get(60, TimeUnit.SECONDS);
|
||||||
}
|
|
||||||
|
|
||||||
/** 在目录及其 zml 子目录中找一个体积合适的真实文件。 */
|
assertNotNull(files);
|
||||||
private static FileInfo firstSmallFile(String url, String pwd, long maxSize) throws Exception {
|
assertFalse(files.isEmpty());
|
||||||
List<FileInfo> dirs = fileList(url, pwd);
|
|
||||||
assertNotNull(dirs);
|
|
||||||
assertFalse(url + " 目录为空", dirs.isEmpty());
|
|
||||||
for (FileInfo dir : dirs) {
|
|
||||||
if (!"folder".equals(dir.getFileType())) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
FileInfo file = firstSmallFileInDir(url, pwd, dir.getFileId(), maxSize);
|
|
||||||
if (file != null) {
|
|
||||||
return file;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static FileInfo firstSmallFileInDir(String url, String pwd, String dirId, long maxSize) throws Exception {
|
FileInfo file = files.stream()
|
||||||
List<FileInfo> entries = fileList(url, pwd, dirId);
|
|
||||||
FileInfo direct = smallFile(entries, maxSize);
|
|
||||||
if (direct != null) {
|
|
||||||
return direct;
|
|
||||||
}
|
|
||||||
for (FileInfo entry : entries) {
|
|
||||||
if (!"folder".equals(entry.getFileType()) || entry.getFileId() == null
|
|
||||||
|| !entry.getFileId().contains(":")) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
FileInfo nested = smallFile(fileList(url, pwd, dirId, entry.getFileName()), maxSize);
|
|
||||||
if (nested != null) {
|
|
||||||
return nested;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static FileInfo smallFile(List<FileInfo> entries, long maxSize) {
|
|
||||||
if (entries == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return entries.stream()
|
|
||||||
.filter(f -> "file".equals(f.getFileType()))
|
.filter(f -> "file".equals(f.getFileType()))
|
||||||
.filter(f -> f.getSize() != null && f.getSize() > 0 && f.getSize() < maxSize)
|
.filter(f -> f.getSize() != null && f.getSize() > 0 && f.getSize() < 5_000_000)
|
||||||
.findFirst()
|
.findFirst()
|
||||||
.orElse(null);
|
.orElse(null);
|
||||||
}
|
if (file != null) {
|
||||||
|
String param = file.getParserUrl().substring(file.getParserUrl().lastIndexOf('/') + 1);
|
||||||
|
JsonObject paramJson = new JsonObject(CommonUtils.urlBase64Decode(param));
|
||||||
|
String downloadUrl = paramJson.getString("downloadUrl");
|
||||||
|
assertNotNull(downloadUrl);
|
||||||
|
assertFalse(downloadUrl.contains("/_"));
|
||||||
|
|
||||||
private static Buffer downloadParsedFile(FileInfo file, String referer) throws Exception {
|
Buffer body = download(downloadUrl, "https://sohehe4.ysepan.com/");
|
||||||
assertNotNull(file.getParserUrl());
|
assertEquals(file.getSize().longValue(), body.length());
|
||||||
String param = file.getParserUrl().substring(file.getParserUrl().lastIndexOf('/') + 1);
|
System.out.println("sohehe4 real download ok, file=" + file.getFileName()
|
||||||
JsonObject paramJson = new JsonObject(CommonUtils.urlBase64Decode(param));
|
+ ", size=" + body.length());
|
||||||
String downloadUrl = paramJson.getString("downloadUrl");
|
} else {
|
||||||
assertNotNull(downloadUrl);
|
System.out.println("sohehe4 dir=" + dirId + " entries=" + files.size()
|
||||||
assertFalse(downloadUrl.contains("/_"));
|
+ " (no small file for real download sample)");
|
||||||
return download(downloadUrl, referer);
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Buffer download(String url, String referer) throws Exception {
|
private static Buffer download(String url, String referer) throws Exception {
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<revision>0.4.15</revision>
|
<revision>0.4.10</revision>
|
||||||
<java.version>17</java.version>
|
<java.version>17</java.version>
|
||||||
<maven.compiler.source>17</maven.compiler.source>
|
<maven.compiler.source>17</maven.compiler.source>
|
||||||
<maven.compiler.target>17</maven.compiler.target>
|
<maven.compiler.target>17</maven.compiler.target>
|
||||||
@@ -32,7 +32,7 @@
|
|||||||
<slf4j.version>2.0.16</slf4j.version>
|
<slf4j.version>2.0.16</slf4j.version>
|
||||||
<commons-lang3.version>3.18.0</commons-lang3.version>
|
<commons-lang3.version>3.18.0</commons-lang3.version>
|
||||||
<commons-beanutils2.version>2.0.0</commons-beanutils2.version>
|
<commons-beanutils2.version>2.0.0</commons-beanutils2.version>
|
||||||
<parserVersion>10.2.7</parserVersion>
|
<parserVersion>10.2.5</parserVersion>
|
||||||
<jackson.version>2.18.9</jackson.version>
|
<jackson.version>2.18.9</jackson.version>
|
||||||
<!-- Logback 最新稳定版 -->
|
<!-- Logback 最新稳定版 -->
|
||||||
<logback.version>1.5.34</logback.version>
|
<logback.version>1.5.34</logback.version>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "nfd-web",
|
"name": "nfd-web",
|
||||||
"version": "0.4.15",
|
"version": "0.4.10",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"serve": "vue-cli-service serve",
|
"serve": "vue-cli-service serve",
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
"build": "node scripts/sync-version.js && vue-cli-service build && node scripts/compress-vs.js",
|
"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",
|
"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 src/utils/folderPaging.spec.js src/utils/nameFilter.spec.js"
|
"test": "node --test src/utils/batchTreeCollect.spec.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@element-plus/icons-vue": "^2.3.1",
|
"@element-plus/icons-vue": "^2.3.1",
|
||||||
|
|||||||
+35
-277
@@ -292,96 +292,6 @@
|
|||||||
gap: 10px;
|
gap: 10px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.load-more {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
gap: 10px;
|
|
||||||
padding: 12px 0 4px;
|
|
||||||
font-size: 13px;
|
|
||||||
color: #7f8c8d;
|
|
||||||
}
|
|
||||||
|
|
||||||
.load-more button {
|
|
||||||
padding: 6px 14px;
|
|
||||||
border: 1px solid #3498db;
|
|
||||||
background: #fff;
|
|
||||||
color: #3498db;
|
|
||||||
border-radius: 4px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.load-more button:disabled {
|
|
||||||
opacity: .6;
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
|
|
||||||
.name-filter-bar {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 10px 14px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
padding: 12px 24px;
|
|
||||||
background: #fff;
|
|
||||||
border-bottom: 1px solid #eaeaea;
|
|
||||||
}
|
|
||||||
|
|
||||||
.name-filter-input {
|
|
||||||
flex: 1 1 220px;
|
|
||||||
max-width: 420px;
|
|
||||||
min-width: 0;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
border: 1px solid #dcdfe6;
|
|
||||||
border-radius: 6px;
|
|
||||||
padding: 0 10px;
|
|
||||||
min-height: 36px;
|
|
||||||
background: #fff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.name-filter-input i {
|
|
||||||
color: #909399;
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.name-filter-input input {
|
|
||||||
flex: 1;
|
|
||||||
min-width: 0;
|
|
||||||
border: 0;
|
|
||||||
outline: none;
|
|
||||||
font-size: 14px;
|
|
||||||
line-height: 1.4;
|
|
||||||
padding: 8px 0;
|
|
||||||
background: transparent;
|
|
||||||
color: #303133;
|
|
||||||
}
|
|
||||||
|
|
||||||
.filter-hint {
|
|
||||||
flex: 1 1 200px;
|
|
||||||
min-width: 0;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.45;
|
|
||||||
color: #909399;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
|
||||||
.name-filter-bar {
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: stretch;
|
|
||||||
padding: 10px 12px;
|
|
||||||
gap: 6px;
|
|
||||||
}
|
|
||||||
.name-filter-input,
|
|
||||||
.filter-hint {
|
|
||||||
flex: 0 0 auto;
|
|
||||||
max-width: none;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
.name-filter-input {
|
|
||||||
min-height: 40px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -395,14 +305,6 @@
|
|||||||
<div class="breadcrumb" id="breadcrumb">
|
<div class="breadcrumb" id="breadcrumb">
|
||||||
<!-- 面包屑导航会通过JS动态生成 -->
|
<!-- 面包屑导航会通过JS动态生成 -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="name-filter-bar">
|
|
||||||
<label class="name-filter-input">
|
|
||||||
<i class="fas fa-search" aria-hidden="true"></i>
|
|
||||||
<input id="name-filter" type="search" placeholder="按文件名筛选" autocomplete="off" autocorrect="off" spellcheck="false" aria-label="按文件名筛选" />
|
|
||||||
</label>
|
|
||||||
<span id="filter-hint" class="filter-hint" hidden></span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="content">
|
<div class="content">
|
||||||
<div class="grid-view" id="file-grid">
|
<div class="grid-view" id="file-grid">
|
||||||
@@ -507,113 +409,6 @@
|
|||||||
};
|
};
|
||||||
const pathStack = [currentDir];
|
const pathStack = [currentDir];
|
||||||
|
|
||||||
// 目录分页:/v2/getFileList 链接换成 /v2/getFileListPage 并带 page / pageCursor
|
|
||||||
let more = null;
|
|
||||||
let loadSeq = 0;
|
|
||||||
let seenKeys = new Set();
|
|
||||||
let folderCount = 0;
|
|
||||||
let fileCount = 0;
|
|
||||||
// 已加载的完整列表。筛选只看这里,规则与 src/utils/nameFilter.js 一致。
|
|
||||||
let loadedFiles = [];
|
|
||||||
let nameFilter = '';
|
|
||||||
const moreEl = document.createElement('div');
|
|
||||||
moreEl.className = 'load-more';
|
|
||||||
moreEl.style.display = 'none';
|
|
||||||
|
|
||||||
function toPageUrl(listUrl, page, cursor) {
|
|
||||||
const m = String(listUrl || '').match(/^(.*?\/v2\/getFileList)(\?.*)?$/);
|
|
||||||
if (!m) return null;
|
|
||||||
let url = `${m[1]}Page${m[2] || ''}`;
|
|
||||||
url += (url.includes('?') ? '&' : '?') + `page=${encodeURIComponent(page)}`;
|
|
||||||
if (cursor) url += `&pageCursor=${encodeURIComponent(cursor)}`;
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readPage(data) {
|
|
||||||
if (Array.isArray(data)) return { list: data, hasMore: false };
|
|
||||||
const d = data || {};
|
|
||||||
const hasMore = !!d.hasMore && Number.isInteger(d.nextPage);
|
|
||||||
return { list: Array.isArray(d.list) ? d.list : [], hasMore, nextPage: d.nextPage, nextCursor: d.nextCursor || null };
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchJson(url) {
|
|
||||||
const response = await fetch(url);
|
|
||||||
let data = null;
|
|
||||||
try {
|
|
||||||
data = await response.json();
|
|
||||||
} catch (e) {
|
|
||||||
throw new Error(`HTTP error! status: ${response.status}`);
|
|
||||||
}
|
|
||||||
if (data && data.code === 200 && data.success) return data;
|
|
||||||
throw new Error((data && data.msg) || `获取文件列表失败 (HTTP ${response.status})`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function fileKey(file) {
|
|
||||||
return `${file.parserUrl || ''}::${file.fileName || ''}::${file.fileId || file.id || ''}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeQuery(keyword) {
|
|
||||||
return String(keyword == null ? '' : keyword).trim().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
function filterByFileName(list, keyword) {
|
|
||||||
const rows = list || [];
|
|
||||||
const query = normalizeQuery(keyword);
|
|
||||||
if (!query) return rows.slice();
|
|
||||||
return rows.filter(file => String((file && file.fileName) || '').toLowerCase().includes(query));
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderMore() {
|
|
||||||
if (!more) {
|
|
||||||
moreEl.style.display = 'none';
|
|
||||||
moreEl.innerHTML = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
moreEl.style.display = '';
|
|
||||||
const total = folderCount + fileCount;
|
|
||||||
const label = more.loading ? '加载中…' : (more.error ? '加载失败,点击重试' : '加载更多');
|
|
||||||
const hint = more.error ? `已加载 ${total} 项:${more.error}` : `已加载 ${total} 项,滚动到底部自动加载`;
|
|
||||||
moreEl.innerHTML = '';
|
|
||||||
const btn = document.createElement('button');
|
|
||||||
btn.textContent = label;
|
|
||||||
btn.disabled = !!more.loading;
|
|
||||||
btn.addEventListener('click', loadMore);
|
|
||||||
const span = document.createElement('span');
|
|
||||||
span.textContent = hint;
|
|
||||||
moreEl.appendChild(btn);
|
|
||||||
moreEl.appendChild(span);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 加载失败只提示重试,已加载的条目保留;失败后暂停滚动自动加载
|
|
||||||
async function loadMore() {
|
|
||||||
const state = more;
|
|
||||||
if (!state || state.loading) return;
|
|
||||||
const seq = loadSeq;
|
|
||||||
state.loading = true;
|
|
||||||
state.error = '';
|
|
||||||
renderMore();
|
|
||||||
try {
|
|
||||||
const data = await fetchJson(toPageUrl(state.listUrl, state.nextPage, state.nextCursor));
|
|
||||||
if (seq !== loadSeq || more !== state) return;
|
|
||||||
const page = readPage(data.data);
|
|
||||||
renderFileList(page.list, true);
|
|
||||||
more = page.hasMore ? { listUrl: state.listUrl, nextPage: page.nextPage, nextCursor: page.nextCursor } : null;
|
|
||||||
} catch (error) {
|
|
||||||
if (seq !== loadSeq || more !== state) return;
|
|
||||||
state.error = error.message || '加载下一页失败';
|
|
||||||
} finally {
|
|
||||||
state.loading = false;
|
|
||||||
renderMore();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof IntersectionObserver !== 'undefined') {
|
|
||||||
new IntersectionObserver(entries => {
|
|
||||||
// 有关键字时不自动翻页,避免筛选结果变短后把后续页一次拉完
|
|
||||||
if (more && !more.loading && !more.error && !normalizeQuery(nameFilter) && entries.some(e => e.isIntersecting)) loadMore();
|
|
||||||
}).observe(moreEl);
|
|
||||||
}
|
|
||||||
|
|
||||||
// DOM 元素
|
// DOM 元素
|
||||||
const breadcrumbEl = document.getElementById('breadcrumb');
|
const breadcrumbEl = document.getElementById('breadcrumb');
|
||||||
const fileGridEl = document.getElementById('file-grid');
|
const fileGridEl = document.getElementById('file-grid');
|
||||||
@@ -623,14 +418,6 @@
|
|||||||
|
|
||||||
// 初始化
|
// 初始化
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
fileGridEl.insertAdjacentElement('afterend', moreEl);
|
|
||||||
const nameInput = document.getElementById('name-filter');
|
|
||||||
if (nameInput) {
|
|
||||||
nameInput.addEventListener('input', () => {
|
|
||||||
nameFilter = nameInput.value;
|
|
||||||
renderLoadedFiles();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
renderBreadcrumb();
|
renderBreadcrumb();
|
||||||
fetchFileList(currentDir.url);
|
fetchFileList(currentDir.url);
|
||||||
|
|
||||||
@@ -671,9 +458,6 @@
|
|||||||
|
|
||||||
// 获取文件列表
|
// 获取文件列表
|
||||||
async function fetchFileList(url) {
|
async function fetchFileList(url) {
|
||||||
const seq = ++loadSeq;
|
|
||||||
more = null;
|
|
||||||
renderMore();
|
|
||||||
try {
|
try {
|
||||||
// 显示加载状态
|
// 显示加载状态
|
||||||
fileGridEl.innerHTML = `
|
fileGridEl.innerHTML = `
|
||||||
@@ -682,15 +466,18 @@
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const pageUrl = toPageUrl(url, 1);
|
const response = await fetch(url);
|
||||||
const data = await fetchJson(pageUrl || url);
|
if (!response.ok) {
|
||||||
if (seq !== loadSeq) return;
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
const page = readPage(data.data);
|
}
|
||||||
renderFileList(page.list);
|
const data = await response.json();
|
||||||
more = pageUrl && page.hasMore ? { listUrl: url, nextPage: page.nextPage, nextCursor: page.nextCursor } : null;
|
|
||||||
renderMore();
|
if (data.code === 200 && data.success) {
|
||||||
|
renderFileList(data.data);
|
||||||
|
} else {
|
||||||
|
throw new Error(data.msg || '获取文件列表失败');
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (seq !== loadSeq) return;
|
|
||||||
console.error('获取文件列表失败:', error);
|
console.error('获取文件列表失败:', error);
|
||||||
fileGridEl.innerHTML = `
|
fileGridEl.innerHTML = `
|
||||||
<div class="empty-state">
|
<div class="empty-state">
|
||||||
@@ -702,50 +489,32 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateFilterHint(matchedCount) {
|
// 渲染文件列表
|
||||||
const hint = document.getElementById('filter-hint');
|
function renderFileList(files) {
|
||||||
if (!hint) return;
|
|
||||||
const query = normalizeQuery(nameFilter);
|
|
||||||
if (!query) {
|
|
||||||
hint.hidden = true;
|
|
||||||
hint.textContent = '';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
hint.hidden = false;
|
|
||||||
hint.textContent = `仅筛选已加载的 ${loadedFiles.length} 项,匹配 ${matchedCount} 项`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 按当前关键字重绘已加载列表。加载更多按钮在网格外面,无匹配时仍然在。
|
|
||||||
function renderLoadedFiles() {
|
|
||||||
const visible = filterByFileName(loadedFiles, nameFilter);
|
|
||||||
fileGridEl.innerHTML = '';
|
fileGridEl.innerHTML = '';
|
||||||
folderCount = 0;
|
|
||||||
fileCount = 0;
|
if (!files || files.length === 0) {
|
||||||
|
fileGridEl.innerHTML = `
|
||||||
if (!visible.length) {
|
<div class="empty-state">
|
||||||
const filtering = normalizeQuery(nameFilter) && loadedFiles.length;
|
|
||||||
fileGridEl.innerHTML = filtering
|
|
||||||
? `<div class="empty-state">
|
|
||||||
<i class="fas fa-search"></i>
|
|
||||||
<h3>没有匹配的文件</h3>
|
|
||||||
<p>换个关键字,或加载更多后再筛</p>
|
|
||||||
</div>`
|
|
||||||
: `<div class="empty-state">
|
|
||||||
<i class="fas fa-folder-open"></i>
|
<i class="fas fa-folder-open"></i>
|
||||||
<h3>此文件夹为空</h3>
|
<h3>此文件夹为空</h3>
|
||||||
<p>暂无文件或文件夹</p>
|
<p>暂无文件或文件夹</p>
|
||||||
</div>`;
|
</div>
|
||||||
|
`;
|
||||||
folderCountEl.textContent = '0';
|
folderCountEl.textContent = '0';
|
||||||
fileCountEl.textContent = '0';
|
fileCountEl.textContent = '0';
|
||||||
updateFilterHint(0);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
visible.forEach(file => {
|
let folderCount = 0;
|
||||||
|
let fileCount = 0;
|
||||||
|
|
||||||
|
files.forEach(file => {
|
||||||
const item = document.createElement('div');
|
const item = document.createElement('div');
|
||||||
const metaText = fileMetaText(file);
|
const metaText = fileMetaText(file);
|
||||||
|
|
||||||
if (file.fileType === 'folder') {
|
if (file.fileType === 'folder') {
|
||||||
|
// 文件夹
|
||||||
item.className = 'item folder';
|
item.className = 'item folder';
|
||||||
item.innerHTML = `
|
item.innerHTML = `
|
||||||
<div class="item-icon">
|
<div class="item-icon">
|
||||||
@@ -755,12 +524,16 @@
|
|||||||
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
||||||
`;
|
`;
|
||||||
folderCount++;
|
folderCount++;
|
||||||
|
|
||||||
|
// 添加点击事件
|
||||||
item.addEventListener('click', () => {
|
item.addEventListener('click', () => {
|
||||||
enterFolder(file);
|
enterFolder(file);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
|
// 文件
|
||||||
const fileExt = getFileExtension(file.fileName);
|
const fileExt = getFileExtension(file.fileName);
|
||||||
const fileTypeInfo = fileTypeIcons[fileExt.toLowerCase()] || fileTypeIcons['default'];
|
const fileTypeInfo = fileTypeIcons[fileExt.toLowerCase()] || fileTypeIcons['default'];
|
||||||
|
|
||||||
item.className = `item ${fileTypeInfo.type}`;
|
item.className = `item ${fileTypeInfo.type}`;
|
||||||
item.innerHTML = `
|
item.innerHTML = `
|
||||||
<div class="item-icon">
|
<div class="item-icon">
|
||||||
@@ -770,34 +543,19 @@
|
|||||||
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
||||||
`;
|
`;
|
||||||
fileCount++;
|
fileCount++;
|
||||||
|
|
||||||
|
// 添加点击事件
|
||||||
item.addEventListener('click', () => {
|
item.addEventListener('click', () => {
|
||||||
handleFileClick(file);
|
handleFileClick(file);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fileGridEl.appendChild(item);
|
fileGridEl.appendChild(item);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 更新统计信息
|
||||||
folderCountEl.textContent = folderCount;
|
folderCountEl.textContent = folderCount;
|
||||||
fileCountEl.textContent = fileCount;
|
fileCountEl.textContent = fileCount;
|
||||||
updateFilterHint(visible.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 渲染文件列表
|
|
||||||
function renderFileList(files, append = false) {
|
|
||||||
if (!append) {
|
|
||||||
seenKeys = new Set();
|
|
||||||
loadedFiles = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
(files || []).forEach(file => {
|
|
||||||
const key = fileKey(file);
|
|
||||||
if (seenKeys.has(key)) return;
|
|
||||||
seenKeys.add(key);
|
|
||||||
loadedFiles.push(file);
|
|
||||||
});
|
|
||||||
|
|
||||||
renderLoadedFiles();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取文件扩展名
|
// 获取文件扩展名
|
||||||
|
|||||||
@@ -1,20 +1,6 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="main-container">
|
<div class="main-container">
|
||||||
<div class="directory-tree" :class="{ 'dark-theme': isDarkTheme }">
|
<div class="directory-tree" :class="{ 'dark-theme': isDarkTheme }">
|
||||||
<div class="dir-filter-bar">
|
|
||||||
<el-input
|
|
||||||
v-model="nameFilter"
|
|
||||||
class="dir-name-filter"
|
|
||||||
clearable
|
|
||||||
placeholder="按文件名筛选"
|
|
||||||
aria-label="按文件名筛选"
|
|
||||||
>
|
|
||||||
<template #prefix>
|
|
||||||
<i class="fas fa-search" aria-hidden="true"></i>
|
|
||||||
</template>
|
|
||||||
</el-input>
|
|
||||||
<p v-if="nameQuery" class="dir-filter-hint">仅筛选已加载的 {{ loadedCount }} 项,匹配 {{ matchedCount }} 项</p>
|
|
||||||
</div>
|
|
||||||
<template v-if="viewMode === 'pane'">
|
<template v-if="viewMode === 'pane'">
|
||||||
<!-- 窗格模式(原有) -->
|
<!-- 窗格模式(原有) -->
|
||||||
<div class="breadcrumb">
|
<div class="breadcrumb">
|
||||||
@@ -32,8 +18,8 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="file-grid" v-loading="loading">
|
<div class="file-grid" v-loading="loading">
|
||||||
<div
|
<div
|
||||||
v-for="file in visibleFileList"
|
v-for="file in currentFileList"
|
||||||
:key="fileKey(file)"
|
:key="file.fileName"
|
||||||
class="file-item"
|
class="file-item"
|
||||||
:class="[getFileTypeClass(file), { 'selected': batchMode && isFileSelected(file) }]"
|
:class="[getFileTypeClass(file), { 'selected': batchMode && isFileSelected(file) }]"
|
||||||
@click="batchMode ? onBatchClick(file) : handleFileClick(file)"
|
@click="batchMode ? onBatchClick(file) : handleFileClick(file)"
|
||||||
@@ -50,18 +36,12 @@
|
|||||||
{{ fileMetaText(file) }}
|
{{ fileMetaText(file) }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!loading && visibleFileList.length === 0" class="empty-state">
|
<div v-if="!loading && (!currentFileList || currentFileList.length === 0)" class="empty-state">
|
||||||
<i class="fas" :class="nameQuery && currentFileList.length ? 'fa-search' : 'fa-folder-open'"></i>
|
<i class="fas fa-folder-open"></i>
|
||||||
<h3>{{ nameQuery && currentFileList.length ? '没有匹配的文件' : '此文件夹为空' }}</h3>
|
<h3>此文件夹为空</h3>
|
||||||
<p>{{ nameQuery && currentFileList.length ? '换个关键字,或加载更多后再筛' : '暂无文件或文件夹' }}</p>
|
<p>暂无文件或文件夹</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="paneMore" ref="loadMoreBar" class="load-more-bar">
|
|
||||||
<el-button size="small" :loading="paneMore.loading" @click="loadMorePane">
|
|
||||||
{{ paneMore.error ? '加载失败,点击重试' : '加载更多' }}
|
|
||||||
</el-button>
|
|
||||||
<span class="load-more-hint">已加载 {{ currentFileList.length }} 项{{ paneMore.error ? `:${paneMore.error}` : ',滚动到底部自动加载' }}</span>
|
|
||||||
</div>
|
|
||||||
<!-- 批量模式 action-bar -->
|
<!-- 批量模式 action-bar -->
|
||||||
<div v-if="batchMode" class="action-bar batch-action-bar">
|
<div v-if="batchMode" class="action-bar batch-action-bar">
|
||||||
<div class="batch-left">
|
<div class="batch-left">
|
||||||
@@ -140,11 +120,6 @@
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
||||||
<div v-if="treeFilterEmpty" class="empty-state tree-filter-empty">
|
|
||||||
<i class="fas fa-search"></i>
|
|
||||||
<h3>没有匹配的文件</h3>
|
|
||||||
<p>换个关键字,或加载更多后再筛</p>
|
|
||||||
</div>
|
|
||||||
<el-tree
|
<el-tree
|
||||||
ref="fileTree"
|
ref="fileTree"
|
||||||
:data="treeData"
|
:data="treeData"
|
||||||
@@ -155,20 +130,16 @@
|
|||||||
:highlight-current="!batchMode"
|
:highlight-current="!batchMode"
|
||||||
:show-checkbox="batchMode"
|
:show-checkbox="batchMode"
|
||||||
:check-strictly="false"
|
:check-strictly="false"
|
||||||
:filter-node-method="filterTreeNode"
|
|
||||||
@node-click="onNodeClick"
|
@node-click="onNodeClick"
|
||||||
@check="onTreeCheck"
|
@check="onTreeCheck"
|
||||||
@check-change="onTreeCheckChange"
|
@check-change="onTreeCheckChange"
|
||||||
:default-expand-all="false"
|
:default-expand-all="false"
|
||||||
|
:default-expanded-keys="['root']"
|
||||||
:render-content="renderContent"
|
:render-content="renderContent"
|
||||||
style="background:transparent;"
|
style="background:transparent;"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="batchMode" class="tree-sidebar-footer">
|
<div v-if="batchMode" class="tree-sidebar-footer">
|
||||||
<div class="tree-select-row">
|
|
||||||
<el-button size="small" @click="selectAll">全选</el-button>
|
|
||||||
<el-button size="small" @click="deselectAll">取消全选</el-button>
|
|
||||||
</div>
|
|
||||||
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
||||||
<div class="tree-sidebar-actions">
|
<div class="tree-sidebar-actions">
|
||||||
<el-button
|
<el-button
|
||||||
@@ -299,11 +270,6 @@
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
||||||
<div v-if="treeFilterEmpty" class="empty-state tree-filter-empty">
|
|
||||||
<i class="fas fa-search"></i>
|
|
||||||
<h3>没有匹配的文件</h3>
|
|
||||||
<p>换个关键字,或加载更多后再筛</p>
|
|
||||||
</div>
|
|
||||||
<el-tree
|
<el-tree
|
||||||
ref="fileTree"
|
ref="fileTree"
|
||||||
:data="treeData"
|
:data="treeData"
|
||||||
@@ -314,11 +280,11 @@
|
|||||||
:highlight-current="!batchMode"
|
:highlight-current="!batchMode"
|
||||||
:show-checkbox="batchMode"
|
:show-checkbox="batchMode"
|
||||||
:check-strictly="false"
|
:check-strictly="false"
|
||||||
:filter-node-method="filterTreeNode"
|
|
||||||
@node-click="onNodeClick"
|
@node-click="onNodeClick"
|
||||||
@check="onTreeCheck"
|
@check="onTreeCheck"
|
||||||
@check-change="onTreeCheckChange"
|
@check-change="onTreeCheckChange"
|
||||||
:default-expand-all="false"
|
:default-expand-all="false"
|
||||||
|
:default-expanded-keys="['root']"
|
||||||
:render-content="renderContent"
|
:render-content="renderContent"
|
||||||
style="background:transparent;"
|
style="background:transparent;"
|
||||||
/>
|
/>
|
||||||
@@ -394,10 +360,6 @@
|
|||||||
</el-button>
|
</el-button>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="batchMode" class="mobile-batch-footer">
|
<div v-if="batchMode" class="mobile-batch-footer">
|
||||||
<div class="tree-select-row">
|
|
||||||
<el-button size="small" @click="selectAll">全选</el-button>
|
|
||||||
<el-button size="small" @click="deselectAll">取消全选</el-button>
|
|
||||||
</div>
|
|
||||||
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
||||||
<div class="tree-sidebar-actions">
|
<div class="tree-sidebar-actions">
|
||||||
<el-button type="primary" size="small" :disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding || batchBrowserDownloadDisabled" :loading="batchDownloading" @click="batchBrowserDownload" :title="batchBrowserDownloadDisabled ? '所选文件需使用下载器下载' : ''">浏览器下载</el-button>
|
<el-button type="primary" size="small" :disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding || batchBrowserDownloadDisabled" :loading="batchDownloading" @click="batchBrowserDownload" :title="batchBrowserDownloadDisabled ? '所选文件需使用下载器下载' : ''">浏览器下载</el-button>
|
||||||
@@ -493,27 +455,15 @@ import fileTypeUtils from '@/utils/fileTypeUtils'
|
|||||||
import DownloadDialog from '@/components/DownloadDialog.vue'
|
import DownloadDialog from '@/components/DownloadDialog.vue'
|
||||||
import { testConnection, autoDetect, addDownload, batchAddDownload, getConfig, saveConfig } from '@/utils/downloaderService'
|
import { testConnection, autoDetect, addDownload, batchAddDownload, getConfig, saveConfig } from '@/utils/downloaderService'
|
||||||
import batchTreeCollect from '@/utils/batchTreeCollect'
|
import batchTreeCollect from '@/utils/batchTreeCollect'
|
||||||
import folderPaging from '@/utils/folderPaging'
|
|
||||||
import nameFilter from '@/utils/nameFilter'
|
|
||||||
import { openNoReferrer } from '@/utils/openNoReferrer'
|
import { openNoReferrer } from '@/utils/openNoReferrer'
|
||||||
|
|
||||||
const {
|
const {
|
||||||
DEFAULT_BATCH_MAX_DEPTH,
|
DEFAULT_BATCH_MAX_DEPTH,
|
||||||
getTreeNodeId,
|
getTreeNodeId,
|
||||||
normalizeTreeItem,
|
normalizeTreeItem,
|
||||||
fileIdentity,
|
|
||||||
uniqueFiles,
|
uniqueFiles,
|
||||||
collectFolderFiles
|
collectFolderFiles
|
||||||
} = batchTreeCollect
|
} = batchTreeCollect
|
||||||
const { toPageUrl, readPage, appendUnique, nextState, makeMoreNode, isMoreNode } = folderPaging
|
|
||||||
const {
|
|
||||||
matchesFileName,
|
|
||||||
filterByFileName,
|
|
||||||
filterSummary,
|
|
||||||
selectMatching,
|
|
||||||
deselectMatching,
|
|
||||||
collectLoadedNodes
|
|
||||||
} = nameFilter
|
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'DirectoryTree',
|
name: 'DirectoryTree',
|
||||||
@@ -523,11 +473,6 @@ export default {
|
|||||||
type: Array,
|
type: Array,
|
||||||
default: () => []
|
default: () => []
|
||||||
},
|
},
|
||||||
// 根目录分页信息(/v2/getFileListPage 的返回),null 表示不分页
|
|
||||||
rootPageInfo: {
|
|
||||||
type: Object,
|
|
||||||
default: null
|
|
||||||
},
|
|
||||||
shareUrl: {
|
shareUrl: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true
|
required: true
|
||||||
@@ -556,13 +501,6 @@ export default {
|
|||||||
loading: false,
|
loading: false,
|
||||||
pathStack: [{ name: '全部文件', url: '' }],
|
pathStack: [{ name: '全部文件', url: '' }],
|
||||||
currentFileList: [],
|
currentFileList: [],
|
||||||
nameFilter: '',
|
|
||||||
rootLoadedFiles: [],
|
|
||||||
treeLoadVersion: 0,
|
|
||||||
// 当前窗格目录的下一页状态;null 表示已全部加载
|
|
||||||
paneMore: null,
|
|
||||||
rootMore: null,
|
|
||||||
rootExtra: [],
|
|
||||||
fileDialogVisible: false,
|
fileDialogVisible: false,
|
||||||
selectedFile: null,
|
selectedFile: null,
|
||||||
isDarkTheme: false,
|
isDarkTheme: false,
|
||||||
@@ -581,8 +519,7 @@ export default {
|
|||||||
treeProps: {
|
treeProps: {
|
||||||
label: 'fileName',
|
label: 'fileName',
|
||||||
children: 'children',
|
children: 'children',
|
||||||
isLeaf: 'isLeaf',
|
isLeaf: 'isLeaf'
|
||||||
disabled: 'disabled'
|
|
||||||
},
|
},
|
||||||
isMobile: false,
|
isMobile: false,
|
||||||
// 批量下载相关
|
// 批量下载相关
|
||||||
@@ -594,26 +531,11 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
nameQuery() {
|
|
||||||
return String(this.nameFilter || '').trim()
|
|
||||||
},
|
|
||||||
visibleFileList() {
|
|
||||||
return filterByFileName(this.currentFileList, this.nameFilter)
|
|
||||||
},
|
|
||||||
loadedCount() {
|
|
||||||
return filterSummary(this.entriesForCount(), this.nameFilter).loaded
|
|
||||||
},
|
|
||||||
matchedCount() {
|
|
||||||
return filterSummary(this.entriesForCount(), this.nameFilter).matched
|
|
||||||
},
|
|
||||||
treeFilterEmpty() {
|
|
||||||
return this.viewMode === 'tree' && !!this.nameQuery && this.matchedCount === 0 && this.loadedCount > 0
|
|
||||||
},
|
|
||||||
folderCount() {
|
folderCount() {
|
||||||
return this.visibleFileList.filter(file => file.fileType === 'folder').length
|
return this.currentFileList.filter(file => file.fileType === 'folder').length
|
||||||
},
|
},
|
||||||
fileCount() {
|
fileCount() {
|
||||||
return this.visibleFileList.filter(file => file.fileType !== 'folder').length
|
return this.currentFileList.filter(file => file.fileType !== 'folder').length
|
||||||
},
|
},
|
||||||
batchProgressPercent() {
|
batchProgressPercent() {
|
||||||
if (this.batchProgress.total === 0) return 0
|
if (this.batchProgress.total === 0) return 0
|
||||||
@@ -648,39 +570,24 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
paneMore() {
|
|
||||||
this.$nextTick(() => this.observeLoadMore())
|
|
||||||
},
|
|
||||||
viewMode(next, prev) {
|
|
||||||
if (prev === 'tree' && next !== 'tree') this.snapshotTreeRoot()
|
|
||||||
this.$nextTick(() => {
|
|
||||||
this.observeLoadMore()
|
|
||||||
if (next === 'tree') this.applyTreeFilter()
|
|
||||||
})
|
|
||||||
},
|
|
||||||
nameFilter() {
|
|
||||||
this.$nextTick(() => this.applyTreeFilter())
|
|
||||||
},
|
|
||||||
fileList: {
|
fileList: {
|
||||||
immediate: true,
|
immediate: true,
|
||||||
handler(newList) {
|
handler(newList) {
|
||||||
this.rootExtra = []
|
// 根节点children为当前目录下所有文件/文件夹
|
||||||
this.rootMore = nextState(this.buildApiUrl(), readPage(this.rootPageInfo || []))
|
this.treeData = [
|
||||||
this.treeMoreFolders = new Set()
|
{
|
||||||
this.rootLoadedFiles = (newList || []).slice()
|
id: 'root',
|
||||||
this.nameFilter = ''
|
fileName: '全部文件',
|
||||||
this.treeLoadVersion += 1
|
fileType: 'folder',
|
||||||
this.syncTreeDataChildren()
|
children: (newList || []).map(item => normalizeTreeItem(item)),
|
||||||
this.pathStack = [{ name: '全部文件', url: '' }]
|
isLeaf: false
|
||||||
this.currentFileList = newList || []
|
}
|
||||||
this.paneMore = this.rootMore
|
]
|
||||||
|
this.currentFileList = newList
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
this.treeMoreFolders = this.treeMoreFolders || new Set()
|
|
||||||
this._paneLoadSeq = 0
|
|
||||||
this._syncingChecks = false
|
|
||||||
this.resetTreeCollectState()
|
this.resetTreeCollectState()
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
@@ -710,124 +617,15 @@ export default {
|
|||||||
}
|
}
|
||||||
return this.withAuth(`${baseUrl}?${params.toString()}`)
|
return this.withAuth(`${baseUrl}?${params.toString()}`)
|
||||||
},
|
},
|
||||||
entriesForCount() {
|
|
||||||
// 树节点不是响应式数据,翻页后靠 treeLoadVersion 让「已加载 / 匹配」重新计算
|
|
||||||
void this.treeLoadVersion
|
|
||||||
return this.activeLoadedEntries()
|
|
||||||
},
|
|
||||||
activeLoadedEntries() {
|
|
||||||
if (this.viewMode !== 'tree') return this.currentFileList || []
|
|
||||||
const tree = this.getFileTree()
|
|
||||||
const storeRoot = tree && tree.store ? tree.store.root : null
|
|
||||||
if (storeRoot) return collectLoadedNodes(storeRoot)
|
|
||||||
return this.rootLoadedFiles || []
|
|
||||||
},
|
|
||||||
// 加载更多占位和虚拟根始终留下,否则无匹配时无法继续翻页
|
|
||||||
filterTreeNode(value, data) {
|
|
||||||
if (!data || data.id === 'root') return false
|
|
||||||
if (isMoreNode(data) || !value) return true
|
|
||||||
return matchesFileName(data, value)
|
|
||||||
},
|
|
||||||
displayRootNodes() {
|
|
||||||
const nodes = (this.rootLoadedFiles || []).map(item => normalizeTreeItem(item))
|
|
||||||
if (this.rootMore) nodes.push(makeMoreNode('root', { ...this.rootMore }))
|
|
||||||
return nodes
|
|
||||||
},
|
|
||||||
revealFilter() {
|
|
||||||
const tree = this.getFileTree()
|
|
||||||
if (tree && typeof tree.filter === 'function') tree.filter(this.nameQuery || '')
|
|
||||||
},
|
|
||||||
applyTreeFilter() {
|
|
||||||
this.revealFilter()
|
|
||||||
this.syncChecksFromSelection()
|
|
||||||
},
|
|
||||||
syncTreeDataChildren() {
|
|
||||||
const children = this.displayRootNodes()
|
|
||||||
if (this.rootMore) {
|
|
||||||
if (this.treeMoreFolders) this.treeMoreFolders.add('root')
|
|
||||||
} else if (this.treeMoreFolders) {
|
|
||||||
this.treeMoreFolders.delete('root')
|
|
||||||
}
|
|
||||||
// 树的数据就是当前已加载列表,不包一层「全部文件」,避免懒加载把根节点再插进列表
|
|
||||||
this.treeData = children
|
|
||||||
},
|
|
||||||
snapshotTreeRoot() {
|
|
||||||
const tree = this.getFileTree()
|
|
||||||
const root = tree && tree.store ? tree.store.root : null
|
|
||||||
if (!root) return
|
|
||||||
const files = []
|
|
||||||
let more = null
|
|
||||||
let sawMore = false
|
|
||||||
const pushNode = (child) => {
|
|
||||||
if (!child || !child.data || isMoreNode(child.data)) {
|
|
||||||
if (child && child.data && isMoreNode(child.data)) {
|
|
||||||
sawMore = true
|
|
||||||
more = child.data.paging || null
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (child.data.id === 'root') {
|
|
||||||
for (const grand of child.childNodes || []) pushNode(grand)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
files.push(child.data)
|
|
||||||
}
|
|
||||||
for (const child of root.childNodes || []) pushNode(child)
|
|
||||||
if (files.length || sawMore) {
|
|
||||||
this.rootLoadedFiles = appendUnique([], files)
|
|
||||||
this.rootMore = more
|
|
||||||
}
|
|
||||||
if (this.pathStack.length <= 1) {
|
|
||||||
this.currentFileList = (this.rootLoadedFiles || []).slice()
|
|
||||||
this.paneMore = this.rootMore
|
|
||||||
? { ...this.rootMore, loading: false, error: this.rootMore.error || '' }
|
|
||||||
: null
|
|
||||||
}
|
|
||||||
this.$nextTick(() => {
|
|
||||||
if (this.viewMode !== 'tree') this.syncTreeDataChildren()
|
|
||||||
})
|
|
||||||
},
|
|
||||||
syncChecksFromSelection() {
|
|
||||||
const tree = this.getFileTree()
|
|
||||||
if (!tree || !this.batchMode || typeof tree.setChecked !== 'function') return
|
|
||||||
const root = tree.store ? tree.store.root : null
|
|
||||||
if (!root) return
|
|
||||||
this._syncingChecks = true
|
|
||||||
try {
|
|
||||||
const selectedKeys = new Set(this.selectedFiles.map(fileIdentity))
|
|
||||||
for (const file of collectLoadedNodes(root)) {
|
|
||||||
if (!this.isDownloadableFile(file)) continue
|
|
||||||
if (this.nameQuery && !matchesFileName(file, this.nameQuery)) continue
|
|
||||||
tree.setChecked(getTreeNodeId(file), selectedKeys.has(fileIdentity(file)), false)
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
this._syncingChecks = false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
// 懒加载子节点(批量勾选文件夹时会通过 node.expand → store.load 复用此方法)
|
// 懒加载子节点(批量勾选文件夹时会通过 node.expand → store.load 复用此方法)
|
||||||
loadNode(node, resolve) {
|
loadNode(node, resolve) {
|
||||||
if (node.level === 0) {
|
if (node.level === 0) {
|
||||||
resolve(this.displayRootNodes())
|
resolve((this.treeData[0]?.children || []).map(item => normalizeTreeItem(item)))
|
||||||
this.treeLoadVersion += 1
|
|
||||||
this.$nextTick(() => this.revealFilter())
|
|
||||||
} else if (node.data.fileType === 'folder' && node.data.parserUrl) {
|
} else if (node.data.fileType === 'folder' && node.data.parserUrl) {
|
||||||
const listUrl = this.withAuth(node.data.parserUrl)
|
axios.get(this.withAuth(node.data.parserUrl), { headers: this.apiKeyHeaders() }).then(res => {
|
||||||
const pageUrl = toPageUrl(listUrl, 1)
|
|
||||||
axios.get(pageUrl || listUrl, { headers: this.apiKeyHeaders() }).then(res => {
|
|
||||||
if (res.data.code === 200) {
|
if (res.data.code === 200) {
|
||||||
const page = readPage(res.data.data)
|
const children = (res.data.data || []).map(item => normalizeTreeItem(item))
|
||||||
const children = page.list.map(item => normalizeTreeItem(item))
|
|
||||||
const more = pageUrl ? nextState(listUrl, page) : null
|
|
||||||
const folderKey = getTreeNodeId(node.data)
|
|
||||||
if (more) {
|
|
||||||
children.push(makeMoreNode(folderKey, more))
|
|
||||||
this.treeMoreFolders.add(folderKey)
|
|
||||||
} else {
|
|
||||||
this.treeMoreFolders.delete(folderKey)
|
|
||||||
}
|
|
||||||
resolve(children)
|
resolve(children)
|
||||||
this.treeLoadVersion += 1
|
|
||||||
this.$nextTick(() => this.revealFilter())
|
|
||||||
} else {
|
} else {
|
||||||
this.$message.error(res.data.msg || '获取子节点失败')
|
this.$message.error(res.data.msg || '获取子节点失败')
|
||||||
resolve([])
|
resolve([])
|
||||||
@@ -842,125 +640,8 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
onNodeClick(data) {
|
onNodeClick(data) {
|
||||||
if (isMoreNode(data)) {
|
|
||||||
this.loadMoreTreeNode(data)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
this.selectedNode = data
|
this.selectedNode = data
|
||||||
},
|
},
|
||||||
fileKey(file) {
|
|
||||||
return getTreeNodeId(file)
|
|
||||||
},
|
|
||||||
// 滚动到底部自动加载;失败后暂停,等用户点击重试
|
|
||||||
observeLoadMore() {
|
|
||||||
if (typeof IntersectionObserver === 'undefined') return
|
|
||||||
if (!this._moreObserver) {
|
|
||||||
this._moreObserver = new IntersectionObserver((entries) => {
|
|
||||||
const state = this.paneMore
|
|
||||||
// 有关键字时列表变短,哨兵会露出来;这时不自动翻页,避免把未加载页一次拉完
|
|
||||||
if (!state || state.loading || state.error || this.viewMode !== 'pane' || this.nameQuery) return
|
|
||||||
if (entries.some(e => e.isIntersecting)) this.loadMorePane()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
this._moreObserver.disconnect()
|
|
||||||
if (this.$refs.loadMoreBar) this._moreObserver.observe(this.$refs.loadMoreBar)
|
|
||||||
},
|
|
||||||
async fetchPage(state) {
|
|
||||||
const res = await axios.get(toPageUrl(state.listUrl, state.nextPage, state.nextCursor), {
|
|
||||||
headers: this.apiKeyHeaders()
|
|
||||||
})
|
|
||||||
if (res.data.code !== 200) {
|
|
||||||
throw new Error(res.data.msg || '加载下一页失败')
|
|
||||||
}
|
|
||||||
return readPage(res.data.data)
|
|
||||||
},
|
|
||||||
// 加载失败(如上游限流)只保留重试入口,已加载的条目不清除
|
|
||||||
async loadMorePane() {
|
|
||||||
const state = this.paneMore
|
|
||||||
if (!state || state.loading) return
|
|
||||||
const seq = this._paneLoadSeq
|
|
||||||
state.loading = true
|
|
||||||
state.error = ''
|
|
||||||
try {
|
|
||||||
const page = await this.fetchPage(state)
|
|
||||||
if (seq !== this._paneLoadSeq || this.paneMore !== state) return
|
|
||||||
const before = this.currentFileList.length
|
|
||||||
this.currentFileList = appendUnique(this.currentFileList, page.list)
|
|
||||||
const added = this.currentFileList.slice(before)
|
|
||||||
const next = nextState(state.listUrl, page)
|
|
||||||
if (this.pathStack.length === 1) {
|
|
||||||
this.rootExtra = appendUnique(this.rootExtra, added)
|
|
||||||
this.rootMore = next
|
|
||||||
this.rootLoadedFiles = appendUnique(this.rootLoadedFiles, added)
|
|
||||||
if (this.viewMode !== 'tree') this.syncTreeDataChildren()
|
|
||||||
}
|
|
||||||
this.paneMore = next
|
|
||||||
this.treeLoadVersion += 1
|
|
||||||
} catch (error) {
|
|
||||||
if (seq !== this._paneLoadSeq || this.paneMore !== state) return
|
|
||||||
state.error = error.response?.data?.msg || error.message || '加载下一页失败'
|
|
||||||
this.$message.error(state.error)
|
|
||||||
} finally {
|
|
||||||
state.loading = false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async loadMoreTreeNode(moreData) {
|
|
||||||
const state = moreData.paging
|
|
||||||
const tree = this.getFileTree()
|
|
||||||
if (!state || state.loading || !tree) return
|
|
||||||
const moreNode = tree.getNode(moreData.id)
|
|
||||||
const parent = moreNode?.parent
|
|
||||||
if (!parent) return
|
|
||||||
state.loading = true
|
|
||||||
state.error = ''
|
|
||||||
try {
|
|
||||||
const page = await this.fetchPage(state)
|
|
||||||
const parentKey = getTreeNodeId(parent.data) || 'root'
|
|
||||||
const parentIsRoot = parent.level === 0
|
|
||||||
const next = nextState(state.listUrl, page)
|
|
||||||
if (parentIsRoot) {
|
|
||||||
// 换一份根数据,而不是 append 到 el-tree 正在监听的数组上,避免根节点被插进两遍
|
|
||||||
this.rootLoadedFiles = appendUnique(this.rootLoadedFiles, page.list)
|
|
||||||
this.rootMore = next
|
|
||||||
if (next) this.treeMoreFolders.add('root')
|
|
||||||
else this.treeMoreFolders.delete('root')
|
|
||||||
this.treeData = this.displayRootNodes()
|
|
||||||
} else {
|
|
||||||
const existing = new Set((parent.childNodes || []).map(n => getTreeNodeId(n.data)))
|
|
||||||
const selectedKeys = new Set(this.selectedFiles.map(fileIdentity))
|
|
||||||
this._syncingChecks = true
|
|
||||||
try {
|
|
||||||
tree.remove(moreNode)
|
|
||||||
for (const item of page.list.map(normalizeTreeItem)) {
|
|
||||||
if (existing.has(item.id)) continue
|
|
||||||
existing.add(item.id)
|
|
||||||
tree.append(item, parent)
|
|
||||||
if (this.isDownloadableFile(item) && typeof tree.setChecked === 'function') {
|
|
||||||
tree.setChecked(item.id, selectedKeys.has(fileIdentity(item)), false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (next) {
|
|
||||||
tree.append(makeMoreNode(parentKey, next), parent)
|
|
||||||
this.treeMoreFolders.add(parentKey)
|
|
||||||
} else {
|
|
||||||
this.treeMoreFolders.delete(parentKey)
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
this._syncingChecks = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
state.loading = false
|
|
||||||
this.treeLoadVersion += 1
|
|
||||||
this.$nextTick(() => {
|
|
||||||
this.revealFilter()
|
|
||||||
this.syncChecksFromSelection()
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
state.loading = false
|
|
||||||
state.error = error.response?.data?.msg || error.message || '加载下一页失败'
|
|
||||||
this.$message.error(`${state.error},可再次点击「加载更多」重试`)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
// 处理文件点击
|
// 处理文件点击
|
||||||
handleFileClick(file) {
|
handleFileClick(file) {
|
||||||
if (file.fileType === 'folder') {
|
if (file.fileType === 'folder') {
|
||||||
@@ -981,19 +662,14 @@ export default {
|
|||||||
try {
|
try {
|
||||||
this.loading = true
|
this.loading = true
|
||||||
const folderUrl = this.withAuth(folder.parserUrl)
|
const folderUrl = this.withAuth(folder.parserUrl)
|
||||||
const seq = ++this._paneLoadSeq
|
const response = await axios.get(folderUrl, { headers: this.apiKeyHeaders() })
|
||||||
const pageUrl = toPageUrl(folderUrl, 1)
|
|
||||||
const response = await axios.get(pageUrl || folderUrl, { headers: this.apiKeyHeaders() })
|
|
||||||
if (seq !== this._paneLoadSeq) return
|
|
||||||
if (response.data.code === 200) {
|
if (response.data.code === 200) {
|
||||||
const newDir = {
|
const newDir = {
|
||||||
url: folderUrl,
|
url: folderUrl,
|
||||||
name: folder.fileName || '未命名文件夹'
|
name: folder.fileName || '未命名文件夹'
|
||||||
}
|
}
|
||||||
const page = readPage(response.data.data)
|
|
||||||
this.pathStack.push(newDir)
|
this.pathStack.push(newDir)
|
||||||
this.currentFileList = page.list
|
this.currentFileList = response.data.data || []
|
||||||
this.paneMore = pageUrl ? nextState(folderUrl, page) : null
|
|
||||||
} else {
|
} else {
|
||||||
this.$message.error(response.data.msg || '获取文件夹内容失败')
|
this.$message.error(response.data.msg || '获取文件夹内容失败')
|
||||||
}
|
}
|
||||||
@@ -1017,23 +693,15 @@ export default {
|
|||||||
},
|
},
|
||||||
async loadCurrentDirectory() {
|
async loadCurrentDirectory() {
|
||||||
const currentDir = this.pathStack[this.pathStack.length - 1]
|
const currentDir = this.pathStack[this.pathStack.length - 1]
|
||||||
const seq = ++this._paneLoadSeq
|
|
||||||
if (!currentDir.url) {
|
if (!currentDir.url) {
|
||||||
this.currentFileList = appendUnique(this.fileList, this.rootExtra)
|
this.currentFileList = this.fileList
|
||||||
this.paneMore = this.rootMore
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
this.paneMore = null
|
|
||||||
try {
|
try {
|
||||||
this.loading = true
|
this.loading = true
|
||||||
const listUrl = this.withAuth(currentDir.url)
|
const response = await axios.get(this.withAuth(currentDir.url), { headers: this.apiKeyHeaders() })
|
||||||
const pageUrl = toPageUrl(listUrl, 1)
|
|
||||||
const response = await axios.get(pageUrl || listUrl, { headers: this.apiKeyHeaders() })
|
|
||||||
if (seq !== this._paneLoadSeq) return
|
|
||||||
if (response.data.code === 200) {
|
if (response.data.code === 200) {
|
||||||
const page = readPage(response.data.data)
|
this.currentFileList = response.data.data || []
|
||||||
this.currentFileList = page.list
|
|
||||||
this.paneMore = pageUrl ? nextState(listUrl, page) : null
|
|
||||||
} else {
|
} else {
|
||||||
this.$message.error(response.data.msg || '加载目录失败')
|
this.$message.error(response.data.msg || '加载目录失败')
|
||||||
}
|
}
|
||||||
@@ -1430,21 +1098,7 @@ export default {
|
|||||||
const fromTree = tree
|
const fromTree = tree
|
||||||
? tree.getCheckedNodes().filter(n => this.isDownloadableFile(n))
|
? tree.getCheckedNodes().filter(n => this.isDownloadableFile(n))
|
||||||
: []
|
: []
|
||||||
const visibleKeys = new Set(
|
this.selectedFiles = uniqueFiles([...fromTree, ...extraFiles])
|
||||||
filterByFileName(this.activeLoadedEntries(), this.nameFilter)
|
|
||||||
.filter(file => this.isDownloadableFile(file))
|
|
||||||
.map(fileIdentity)
|
|
||||||
)
|
|
||||||
const extraKeys = new Set((extraFiles || []).map(fileIdentity))
|
|
||||||
const kept = this.selectedFiles.filter(file => {
|
|
||||||
const key = fileIdentity(file)
|
|
||||||
return !visibleKeys.has(key) && !extraKeys.has(key)
|
|
||||||
})
|
|
||||||
const checkedVisible = fromTree.filter(file => {
|
|
||||||
const key = fileIdentity(file)
|
|
||||||
return visibleKeys.has(key) || extraKeys.has(key)
|
|
||||||
})
|
|
||||||
this.selectedFiles = uniqueFiles([...kept, ...checkedVisible, ...(extraFiles || [])])
|
|
||||||
},
|
},
|
||||||
enqueueFolderCollect(folderData) {
|
enqueueFolderCollect(folderData) {
|
||||||
const key = getTreeNodeId(folderData)
|
const key = getTreeNodeId(folderData)
|
||||||
@@ -1481,9 +1135,6 @@ export default {
|
|||||||
visitedKeys: this._visitedInCollect
|
visitedKeys: this._visitedInCollect
|
||||||
})
|
})
|
||||||
this.syncSelectedFilesFromTree(ctx.files)
|
this.syncSelectedFilesFromTree(ctx.files)
|
||||||
if ([...this._visitedInCollect].some(key => this.treeMoreFolders.has(key))) {
|
|
||||||
this.$message.warning('部分文件夹还有未加载的分页,只勾选了已加载的文件;请先点击「加载更多」后再勾选')
|
|
||||||
}
|
|
||||||
if (ctx.depthExceeded) {
|
if (ctx.depthExceeded) {
|
||||||
this.$message.warning(
|
this.$message.warning(
|
||||||
`已达到最大展开深度(${this.effectiveBatchMaxDepth} 层),部分深层文件未勾选`
|
`已达到最大展开深度(${this.effectiveBatchMaxDepth} 层),部分深层文件未勾选`
|
||||||
@@ -1503,13 +1154,11 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
isFileSelected(file) {
|
isFileSelected(file) {
|
||||||
const key = fileIdentity(file)
|
return this.selectedFiles.some(f => f.fileName === file.fileName && f.parserUrl === file.parserUrl)
|
||||||
return this.selectedFiles.some(item => fileIdentity(item) === key)
|
|
||||||
},
|
},
|
||||||
toggleFileSelect(file) {
|
toggleFileSelect(file) {
|
||||||
if (!file || file.fileType === 'folder' || isMoreNode(file)) return
|
if (file.fileType === 'folder') return
|
||||||
const key = fileIdentity(file)
|
const idx = this.selectedFiles.findIndex(f => f.fileName === file.fileName && f.parserUrl === file.parserUrl)
|
||||||
const idx = this.selectedFiles.findIndex(item => fileIdentity(item) === key)
|
|
||||||
if (idx >= 0) {
|
if (idx >= 0) {
|
||||||
this.selectedFiles.splice(idx, 1)
|
this.selectedFiles.splice(idx, 1)
|
||||||
} else {
|
} else {
|
||||||
@@ -1526,32 +1175,13 @@ export default {
|
|||||||
this.toggleFileSelect(file)
|
this.toggleFileSelect(file)
|
||||||
},
|
},
|
||||||
selectAll() {
|
selectAll() {
|
||||||
const loaded = this.activeLoadedEntries()
|
this.selectedFiles = this.currentFileList.filter(f => this.isDownloadableFile(f))
|
||||||
this.selectedFiles = selectMatching(
|
|
||||||
this.selectedFiles,
|
|
||||||
loaded,
|
|
||||||
this.nameFilter,
|
|
||||||
file => this.isDownloadableFile(file)
|
|
||||||
)
|
|
||||||
const hasMore = this.viewMode === 'tree'
|
|
||||||
? !!(this.rootMore || (this.treeMoreFolders && this.treeMoreFolders.size))
|
|
||||||
: !!this.paneMore
|
|
||||||
if (hasMore) {
|
|
||||||
this.$message.warning('仅选中已加载且匹配筛选的文件,未继续拉取后续分页')
|
|
||||||
}
|
|
||||||
this.$nextTick(() => this.syncChecksFromSelection())
|
|
||||||
},
|
},
|
||||||
deselectAll() {
|
deselectAll() {
|
||||||
this.selectedFiles = deselectMatching(
|
this.selectedFiles = []
|
||||||
this.selectedFiles,
|
|
||||||
this.activeLoadedEntries(),
|
|
||||||
this.nameFilter,
|
|
||||||
file => this.isDownloadableFile(file)
|
|
||||||
)
|
|
||||||
this.$nextTick(() => this.syncChecksFromSelection())
|
|
||||||
},
|
},
|
||||||
onTreeCheckChange() {
|
onTreeCheckChange() {
|
||||||
if (!this.batchMode || this._treeCollecting || this._syncingChecks) return
|
if (!this.batchMode || this._treeCollecting) return
|
||||||
this.syncSelectedFilesFromTree()
|
this.syncSelectedFilesFromTree()
|
||||||
},
|
},
|
||||||
extractTypeParam(file) {
|
extractTypeParam(file) {
|
||||||
@@ -1661,12 +1291,6 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
renderContent(h, { node, data, store }) {
|
renderContent(h, { node, data, store }) {
|
||||||
if (isMoreNode(data)) {
|
|
||||||
return h('div', { class: 'custom-tree-node tree-load-more' }, [
|
|
||||||
h('i', { class: 'fas fa-angle-double-down' }),
|
|
||||||
h('span', { class: 'node-label' }, node.label)
|
|
||||||
])
|
|
||||||
}
|
|
||||||
const isFolder = data.fileType === 'folder'
|
const isFolder = data.fileType === 'folder'
|
||||||
const isUrl = data.fileType === 'url'
|
const isUrl = data.fileType === 'url'
|
||||||
return h('div', {
|
return h('div', {
|
||||||
@@ -1704,9 +1328,6 @@ export default {
|
|||||||
if (this._observer) {
|
if (this._observer) {
|
||||||
this._observer.disconnect()
|
this._observer.disconnect()
|
||||||
}
|
}
|
||||||
if (this._moreObserver) {
|
|
||||||
this._moreObserver.disconnect()
|
|
||||||
}
|
|
||||||
if (this._onResize) {
|
if (this._onResize) {
|
||||||
window.removeEventListener('resize', this._onResize)
|
window.removeEventListener('resize', this._onResize)
|
||||||
}
|
}
|
||||||
@@ -1741,56 +1362,6 @@ html, body, #app, .main-container, .directory-tree, .content-card {
|
|||||||
border: 1px solid #404040;
|
border: 1px solid #404040;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dir-filter-bar {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 10px 14px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
padding: 10px 12px;
|
|
||||||
background: #fff;
|
|
||||||
border-bottom: 1px solid #eaeaea;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dark-theme .dir-filter-bar {
|
|
||||||
background: #2d2d2d;
|
|
||||||
border-bottom-color: #404040;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dir-name-filter {
|
|
||||||
flex: 1 1 220px;
|
|
||||||
max-width: 420px;
|
|
||||||
min-width: 0;
|
|
||||||
height: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dir-name-filter .el-input__wrapper {
|
|
||||||
min-height: 36px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dir-filter-hint {
|
|
||||||
margin: 0;
|
|
||||||
flex: 1 1 200px;
|
|
||||||
min-width: 0;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.45;
|
|
||||||
color: #909399;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dark-theme .dir-filter-hint {
|
|
||||||
color: #bdc3c7;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tree-filter-empty {
|
|
||||||
padding: 16px 8px 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tree-select-row {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 8px;
|
|
||||||
margin-bottom: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.breadcrumb {
|
.breadcrumb {
|
||||||
background: #f8f9fa;
|
background: #f8f9fa;
|
||||||
padding: 16px 24px;
|
padding: 16px 24px;
|
||||||
@@ -1938,24 +1509,6 @@ html, body, #app, .main-container, .directory-tree, .content-card {
|
|||||||
color: #bdc3c7;
|
color: #bdc3c7;
|
||||||
}
|
}
|
||||||
|
|
||||||
.load-more-bar {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
gap: 10px;
|
|
||||||
padding: 10px 0 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.load-more-hint {
|
|
||||||
font-size: 12px;
|
|
||||||
color: #909399;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tree-load-more {
|
|
||||||
color: #409eff;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.empty-state {
|
.empty-state {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
padding: 30px 10px;
|
padding: 30px 10px;
|
||||||
@@ -2623,27 +2176,6 @@ html, body, #app, .main-container, .directory-tree, .content-card {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.dir-filter-bar {
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: stretch;
|
|
||||||
gap: 6px;
|
|
||||||
padding: 8px 10px;
|
|
||||||
}
|
|
||||||
.dir-name-filter {
|
|
||||||
flex: 0 0 auto;
|
|
||||||
max-width: none;
|
|
||||||
width: 100%;
|
|
||||||
height: auto;
|
|
||||||
}
|
|
||||||
.dir-name-filter .el-input__wrapper {
|
|
||||||
min-height: 40px;
|
|
||||||
}
|
|
||||||
.dir-filter-hint {
|
|
||||||
flex: none;
|
|
||||||
}
|
|
||||||
.tree-select-row .el-button {
|
|
||||||
flex: 1 1 0;
|
|
||||||
}
|
|
||||||
.file-grid {
|
.file-grid {
|
||||||
grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
|
grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
|
|||||||
@@ -1,83 +0,0 @@
|
|||||||
/**
|
|
||||||
* 目录分页(/v2/getFileListPage)前端辅助。
|
|
||||||
*
|
|
||||||
* - 后端给出的目录链接是 /v2/getFileList?...,换成 /v2/getFileListPage 并带 page / pageCursor 即可分页。
|
|
||||||
* - 不是 getFileList 链接的目录(例如第三方解析器返回的其它地址)不分页,按原样整体加载。
|
|
||||||
* - 加载失败(如蓝奏「请刷新,重试」限流)只提示重试,已加载的页保留不动。
|
|
||||||
*/
|
|
||||||
const { fileIdentity } = require('./batchTreeCollect.js')
|
|
||||||
|
|
||||||
const MORE_TYPE = 'more'
|
|
||||||
const LIST_PATH_RE = /^(.*?\/v2\/getFileList)(\?.*)?$/
|
|
||||||
|
|
||||||
function toPageUrl(listUrl, page = 1, cursor = '') {
|
|
||||||
if (!listUrl) return null
|
|
||||||
const m = String(listUrl).match(LIST_PATH_RE)
|
|
||||||
if (!m) return null
|
|
||||||
let url = `${m[1]}Page${m[2] || ''}`
|
|
||||||
const extra = [`page=${encodeURIComponent(page)}`]
|
|
||||||
if (cursor) extra.push(`pageCursor=${encodeURIComponent(cursor)}`)
|
|
||||||
url += (url.includes('?') ? '&' : '?') + extra.join('&')
|
|
||||||
return url
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 兼容两种响应:分页 envelope 或旧接口的纯数组。 */
|
|
||||||
function readPage(data) {
|
|
||||||
if (Array.isArray(data)) {
|
|
||||||
return { list: data, paged: false, hasMore: false, nextPage: null, nextCursor: null }
|
|
||||||
}
|
|
||||||
const d = data || {}
|
|
||||||
const hasMore = !!d.hasMore && Number.isInteger(d.nextPage)
|
|
||||||
return {
|
|
||||||
list: Array.isArray(d.list) ? d.list : [],
|
|
||||||
paged: !!d.paged,
|
|
||||||
hasMore,
|
|
||||||
nextPage: hasMore ? d.nextPage : null,
|
|
||||||
nextCursor: hasMore ? (d.nextCursor || null) : null,
|
|
||||||
total: d.total ?? null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 追加下一页,按文件身份去重,保持已加载项的顺序。 */
|
|
||||||
function appendUnique(existing, incoming) {
|
|
||||||
const out = [...(existing || [])]
|
|
||||||
const seen = new Set(out.map(fileIdentity))
|
|
||||||
for (const item of incoming || []) {
|
|
||||||
const key = fileIdentity(item)
|
|
||||||
if (seen.has(key)) continue
|
|
||||||
seen.add(key)
|
|
||||||
out.push(item)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 下一页的请求状态;没有更多时返回 null。 */
|
|
||||||
function nextState(listUrl, page) {
|
|
||||||
if (!listUrl || !page || !page.hasMore) return null
|
|
||||||
return { listUrl, nextPage: page.nextPage, nextCursor: page.nextCursor, loading: false, error: '' }
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeMoreNode(parentId, state) {
|
|
||||||
return {
|
|
||||||
id: `${parentId}::more`,
|
|
||||||
fileName: '加载更多…',
|
|
||||||
fileType: MORE_TYPE,
|
|
||||||
isLeaf: true,
|
|
||||||
disabled: true,
|
|
||||||
paging: state
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function isMoreNode(data) {
|
|
||||||
return !!(data && data.fileType === MORE_TYPE)
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
MORE_TYPE,
|
|
||||||
toPageUrl,
|
|
||||||
readPage,
|
|
||||||
appendUnique,
|
|
||||||
nextState,
|
|
||||||
makeMoreNode,
|
|
||||||
isMoreNode
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
const { describe, it } = require('node:test')
|
|
||||||
const assert = require('node:assert/strict')
|
|
||||||
|
|
||||||
const {
|
|
||||||
toPageUrl,
|
|
||||||
readPage,
|
|
||||||
appendUnique,
|
|
||||||
nextState,
|
|
||||||
makeMoreNode,
|
|
||||||
isMoreNode
|
|
||||||
} = require('./folderPaging.js')
|
|
||||||
|
|
||||||
function file(id) {
|
|
||||||
return { fileId: id, fileName: `${id}.apk`, fileType: 'file', parserUrl: `/v2/redirectUrl/lz/${id}` }
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('toPageUrl', () => {
|
|
||||||
it('switches getFileList to getFileListPage and keeps existing params', () => {
|
|
||||||
assert.equal(
|
|
||||||
toPageUrl('http://h/v2/getFileList?url=https%3A%2F%2Fa.com%2Fb1&dirId=7&auth=x%2By', 2, 'ab-_c='),
|
|
||||||
'http://h/v2/getFileListPage?url=https%3A%2F%2Fa.com%2Fb1&dirId=7&auth=x%2By&page=2&pageCursor=ab-_c%3D'
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('works without query and without cursor', () => {
|
|
||||||
assert.equal(toPageUrl('/v2/getFileList', 1), '/v2/getFileListPage?page=1')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not page unknown folder links', () => {
|
|
||||||
assert.equal(toPageUrl('https://other/api/list?x=1', 2), null)
|
|
||||||
assert.equal(toPageUrl('/v2/getFileListPage?url=a', 2), null)
|
|
||||||
assert.equal(toPageUrl('', 2), null)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('readPage', () => {
|
|
||||||
it('reads paged envelope', () => {
|
|
||||||
const page = readPage({ list: [file('a')], paged: true, page: 1, hasMore: true, nextPage: 2, nextCursor: 'c' })
|
|
||||||
assert.equal(page.list.length, 1)
|
|
||||||
assert.equal(page.hasMore, true)
|
|
||||||
assert.equal(page.nextPage, 2)
|
|
||||||
assert.equal(page.nextCursor, 'c')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('treats legacy array as complete list', () => {
|
|
||||||
const page = readPage([file('a'), file('b')])
|
|
||||||
assert.equal(page.list.length, 2)
|
|
||||||
assert.equal(page.hasMore, false)
|
|
||||||
assert.equal(nextState('/v2/getFileList', page), null)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('hasMore without a valid nextPage is not followed', () => {
|
|
||||||
assert.equal(readPage({ list: [], hasMore: true, nextPage: null }).hasMore, false)
|
|
||||||
assert.equal(readPage(null).list.length, 0)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('appendUnique', () => {
|
|
||||||
it('keeps loaded items and drops duplicates from the next page', () => {
|
|
||||||
const merged = appendUnique([file('a'), file('b')], [file('b'), file('c')])
|
|
||||||
assert.deepEqual(merged.map(f => f.fileId), ['a', 'b', 'c'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a failed (empty) load leaves loaded items untouched', () => {
|
|
||||||
const loaded = [file('a')]
|
|
||||||
assert.deepEqual(appendUnique(loaded, undefined), loaded)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('more node', () => {
|
|
||||||
it('carries the next page state and is not a file or folder', () => {
|
|
||||||
const state = nextState('/v2/getFileList?url=x', readPage({ list: [], hasMore: true, nextPage: 3, nextCursor: 'k' }))
|
|
||||||
const node = makeMoreNode('fid:1', state)
|
|
||||||
assert.equal(isMoreNode(node), true)
|
|
||||||
assert.equal(node.isLeaf, true)
|
|
||||||
assert.equal(node.paging.nextPage, 3)
|
|
||||||
assert.equal(node.paging.nextCursor, 'k')
|
|
||||||
assert.equal(isMoreNode(file('a')), false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,155 +0,0 @@
|
|||||||
/**
|
|
||||||
* 目录文件名筛选与批量勾选范围。
|
|
||||||
*
|
|
||||||
* 只处理已经加载的行,不发起下一页请求。分页仍由 folderPaging 的
|
|
||||||
* nextCursor / pageCursor 推进;这里只决定新页里哪些行可见、哪些会被全选。
|
|
||||||
*/
|
|
||||||
const { fileIdentity, uniqueFiles } = require('./batchTreeCollect')
|
|
||||||
const { appendUnique, nextState } = require('./folderPaging')
|
|
||||||
|
|
||||||
function normalizeQuery(keyword) {
|
|
||||||
return String(keyword == null ? '' : keyword).trim().toLowerCase()
|
|
||||||
}
|
|
||||||
|
|
||||||
function matchesFileName(file, keyword) {
|
|
||||||
const query = normalizeQuery(keyword)
|
|
||||||
if (!query) return true
|
|
||||||
return String((file && file.fileName) || '').toLowerCase().includes(query)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 空关键字返回副本,不清空调用方持有的已加载数组。 */
|
|
||||||
function filterByFileName(list, keyword) {
|
|
||||||
const rows = list || []
|
|
||||||
const query = normalizeQuery(keyword)
|
|
||||||
if (!query) return rows.slice()
|
|
||||||
return rows.filter(file => matchesFileName(file, keyword))
|
|
||||||
}
|
|
||||||
|
|
||||||
function isSelectableFile(file) {
|
|
||||||
return !!(
|
|
||||||
file
|
|
||||||
&& file.parserUrl
|
|
||||||
&& file.fileType !== 'folder'
|
|
||||||
&& file.fileType !== 'url'
|
|
||||||
&& file.fileType !== 'more'
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function countableEntries(list) {
|
|
||||||
return (list || []).filter(file => file && file.fileType !== 'more' && file.id !== 'root')
|
|
||||||
}
|
|
||||||
|
|
||||||
function filterSummary(loaded, keyword) {
|
|
||||||
const rows = countableEntries(loaded)
|
|
||||||
const matched = filterByFileName(rows, keyword)
|
|
||||||
return {
|
|
||||||
loaded: rows.length,
|
|
||||||
matched: matched.length,
|
|
||||||
text: `仅筛选已加载的 ${rows.length} 项,匹配 ${matched.length} 项`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 全选:只并入当前关键字命中的已加载可选文件。
|
|
||||||
* 不在这份可见集合里的原选择保留,隐藏项不会被加进来。
|
|
||||||
*/
|
|
||||||
function selectMatching(selected, loaded, keyword, isSelectable = isSelectableFile) {
|
|
||||||
const visible = filterByFileName(loaded, keyword).filter(file => isSelectable(file))
|
|
||||||
const visibleKeys = new Set(visible.map(fileIdentity))
|
|
||||||
const kept = (selected || []).filter(file => !visibleKeys.has(fileIdentity(file)))
|
|
||||||
return uniqueFiles(kept.concat(visible))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 取消全选:只移出当前可见可选文件,范围外的选择不动。 */
|
|
||||||
function deselectMatching(selected, loaded, keyword, isSelectable = isSelectableFile) {
|
|
||||||
const visibleKeys = new Set(
|
|
||||||
filterByFileName(loaded, keyword)
|
|
||||||
.filter(file => isSelectable(file))
|
|
||||||
.map(fileIdentity)
|
|
||||||
)
|
|
||||||
return (selected || []).filter(file => !visibleKeys.has(fileIdentity(file)))
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleSelected(selected, file, isSelectable = isSelectableFile) {
|
|
||||||
const list = (selected || []).slice()
|
|
||||||
if (!isSelectable(file)) return list
|
|
||||||
const key = fileIdentity(file)
|
|
||||||
const index = list.findIndex(item => fileIdentity(item) === key)
|
|
||||||
if (index >= 0) {
|
|
||||||
list.splice(index, 1)
|
|
||||||
return list
|
|
||||||
}
|
|
||||||
list.push(file)
|
|
||||||
return list
|
|
||||||
}
|
|
||||||
|
|
||||||
function isSelected(selected, file) {
|
|
||||||
const key = fileIdentity(file)
|
|
||||||
return (selected || []).some(item => fileIdentity(item) === key)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 已加载树节点。未展开的文件夹不往下走,因此不会把未请求的子项算进全选范围。
|
|
||||||
* 「加载更多」占位节点跳过。
|
|
||||||
*/
|
|
||||||
function collectLoadedNodes(node) {
|
|
||||||
const out = []
|
|
||||||
for (const child of (node && node.childNodes) || []) {
|
|
||||||
const data = child && child.data
|
|
||||||
if (!data || data.fileType === 'more') continue
|
|
||||||
out.push(data)
|
|
||||||
if (child.loaded) {
|
|
||||||
out.push(...collectLoadedNodes(child))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 用目录分页的 nextCursor 追加一页。
|
|
||||||
* 已有选择原样保留:新页即使命中关键字也不会被静默勾上。
|
|
||||||
*/
|
|
||||||
function applyCursorPage(state, page) {
|
|
||||||
const loaded = appendUnique(state.loaded, (page && page.list) || [])
|
|
||||||
const listUrl = (state.more && state.more.listUrl) || state.listUrl
|
|
||||||
return {
|
|
||||||
keyword: state.keyword,
|
|
||||||
view: state.view,
|
|
||||||
loaded,
|
|
||||||
selected: (state.selected || []).slice(),
|
|
||||||
listUrl,
|
|
||||||
more: nextState(listUrl, page)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function switchView(state, view) {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
view,
|
|
||||||
keyword: state.keyword,
|
|
||||||
selected: (state.selected || []).slice()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearKeyword(state) {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
keyword: ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
normalizeQuery,
|
|
||||||
matchesFileName,
|
|
||||||
filterByFileName,
|
|
||||||
isSelectableFile,
|
|
||||||
filterSummary,
|
|
||||||
selectMatching,
|
|
||||||
deselectMatching,
|
|
||||||
toggleSelected,
|
|
||||||
isSelected,
|
|
||||||
collectLoadedNodes,
|
|
||||||
applyCursorPage,
|
|
||||||
switchView,
|
|
||||||
clearKeyword
|
|
||||||
}
|
|
||||||
@@ -1,237 +0,0 @@
|
|||||||
const { describe, it } = require('node:test')
|
|
||||||
const assert = require('node:assert/strict')
|
|
||||||
|
|
||||||
const { readPage } = require('./folderPaging')
|
|
||||||
const {
|
|
||||||
normalizeQuery,
|
|
||||||
filterByFileName,
|
|
||||||
filterSummary,
|
|
||||||
selectMatching,
|
|
||||||
deselectMatching,
|
|
||||||
toggleSelected,
|
|
||||||
isSelected,
|
|
||||||
collectLoadedNodes,
|
|
||||||
applyCursorPage,
|
|
||||||
switchView,
|
|
||||||
clearKeyword
|
|
||||||
} = require('./nameFilter')
|
|
||||||
|
|
||||||
function file(name, id, extra = {}) {
|
|
||||||
return {
|
|
||||||
fileName: name,
|
|
||||||
fileId: id,
|
|
||||||
fileType: 'file',
|
|
||||||
parserUrl: '/v2/redirectUrl/lz/same',
|
|
||||||
...extra
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function folder(name, id) {
|
|
||||||
return {
|
|
||||||
fileName: name,
|
|
||||||
fileId: id,
|
|
||||||
fileType: 'folder',
|
|
||||||
parserUrl: `/v2/getFileList?dir=${id}`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function baseState(overrides = {}) {
|
|
||||||
return {
|
|
||||||
keyword: '',
|
|
||||||
view: 'pane',
|
|
||||||
loaded: [],
|
|
||||||
selected: [],
|
|
||||||
listUrl: '/v2/getFileList?url=share',
|
|
||||||
more: null,
|
|
||||||
...overrides
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('filename filter', () => {
|
|
||||||
const loaded = [
|
|
||||||
file('Alpha.TXT', '1'),
|
|
||||||
file('notes.md', '2'),
|
|
||||||
file(' photo.JPG', '3'),
|
|
||||||
folder('Albums', '4')
|
|
||||||
]
|
|
||||||
|
|
||||||
it('trims and matches a case-insensitive substring', () => {
|
|
||||||
assert.equal(normalizeQuery(' ApK '), 'apk')
|
|
||||||
const matched = filterByFileName(loaded, ' aL ')
|
|
||||||
assert.deepEqual(matched.map(item => item.fileId), ['1', '4'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('blank keyword restores the loaded list without dropping rows', () => {
|
|
||||||
const cleared = filterByFileName(loaded, ' ')
|
|
||||||
assert.deepEqual(cleared.map(item => item.fileId), ['1', '2', '3', '4'])
|
|
||||||
assert.notEqual(cleared, loaded)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('describes loaded N and matched M', () => {
|
|
||||||
const summary = filterSummary(loaded, 'photo')
|
|
||||||
assert.equal(summary.loaded, 4)
|
|
||||||
assert.equal(summary.matched, 1)
|
|
||||||
assert.equal(summary.text, '仅筛选已加载的 4 项,匹配 1 项')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('select and deselect scope', () => {
|
|
||||||
const outside = file('kept.zip', 'out', { parserUrl: '/v2/redirectUrl/lz/out' })
|
|
||||||
const match = file('Alpha.TXT', '1')
|
|
||||||
const other = file('Beta.bin', '2')
|
|
||||||
const hiddenFolder = folder('Alpha-dir', '3')
|
|
||||||
const link = file('Alpha-link.url', '4', { fileType: 'url', parserUrl: '' })
|
|
||||||
const loaded = [match, other, hiddenFolder, link]
|
|
||||||
|
|
||||||
it('selects only loaded selectable files matching the keyword', () => {
|
|
||||||
const selected = selectMatching([outside], loaded, 'alpha')
|
|
||||||
assert.deepEqual(selected.map(item => item.fileId), ['out', '1'])
|
|
||||||
assert.equal(isSelected(selected, other), false)
|
|
||||||
assert.equal(isSelected(selected, hiddenFolder), false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('deselect removes only the current match and keeps selections outside it', () => {
|
|
||||||
const selected = deselectMatching([outside, match, other], loaded, 'alpha')
|
|
||||||
assert.deepEqual(selected.map(item => item.fileId), ['out', '2'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not select a loaded file hidden by the keyword', () => {
|
|
||||||
const selected = selectMatching([other], loaded, 'alpha')
|
|
||||||
assert.equal(isSelected(selected, other), true)
|
|
||||||
assert.equal(isSelected(selected, match), true)
|
|
||||||
const narrowed = selectMatching(selected, loaded, 'beta')
|
|
||||||
assert.deepEqual(narrowed.map(item => item.fileId).sort(), ['1', '2'])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('same name, different id', () => {
|
|
||||||
const first = file('Report.TXT', 'a')
|
|
||||||
const second = file('Report.TXT', 'b')
|
|
||||||
|
|
||||||
it('keeps both files when selecting and can toggle one without the other', () => {
|
|
||||||
const selected = selectMatching([], [first, second], 'report')
|
|
||||||
assert.equal(selected.length, 2)
|
|
||||||
assert.notEqual(selected[0], selected[1])
|
|
||||||
const onlySecond = toggleSelected(selected, first)
|
|
||||||
assert.deepEqual(onlySecond.map(item => item.fileId), ['b'])
|
|
||||||
assert.equal(isSelected(onlySecond, first), false)
|
|
||||||
assert.equal(isSelected(onlySecond, second), true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('distinguishes files that only differ by id when fileId is absent', () => {
|
|
||||||
const left = { fileName: 'Report.TXT', id: 'x', fileType: 'file', parserUrl: '/v2/redirectUrl/lz/same' }
|
|
||||||
const right = { fileName: 'Report.TXT', id: 'y', fileType: 'file', parserUrl: '/v2/redirectUrl/lz/same' }
|
|
||||||
const selected = toggleSelected([], left)
|
|
||||||
assert.equal(isSelected(selected, right), false)
|
|
||||||
assert.equal(toggleSelected(selected, right).length, 2)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('cursor page', () => {
|
|
||||||
it('shows new matches from the next cursor without selecting them', () => {
|
|
||||||
let state = baseState({
|
|
||||||
keyword: 'alpha',
|
|
||||||
loaded: [file('Alpha.TXT', '1'), file('Beta.bin', '2')],
|
|
||||||
selected: [file('Beta.bin', '2')],
|
|
||||||
more: { listUrl: '/v2/getFileList?url=share', nextPage: 2, nextCursor: 'c1', loading: false, error: '' }
|
|
||||||
})
|
|
||||||
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1'])
|
|
||||||
|
|
||||||
state = applyCursorPage(state, readPage({
|
|
||||||
list: [file('ALPHA-extra.txt', '3'), file('Gamma.bin', '4')],
|
|
||||||
paged: true,
|
|
||||||
hasMore: true,
|
|
||||||
nextPage: 3,
|
|
||||||
nextCursor: 'c2'
|
|
||||||
}))
|
|
||||||
|
|
||||||
assert.deepEqual(state.loaded.map(item => item.fileId), ['1', '2', '3', '4'])
|
|
||||||
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1', '3'])
|
|
||||||
assert.deepEqual(state.selected.map(item => item.fileId), ['2'])
|
|
||||||
assert.equal(state.more.nextCursor, 'c2')
|
|
||||||
assert.equal(state.more.nextPage, 3)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps load-more available when nothing matches yet', () => {
|
|
||||||
let state = baseState({
|
|
||||||
keyword: 'zzzz',
|
|
||||||
loaded: [file('Alpha.TXT', '1')],
|
|
||||||
more: { listUrl: '/v2/getFileList?url=share', nextPage: 2, nextCursor: 'c1', loading: false, error: '' }
|
|
||||||
})
|
|
||||||
assert.equal(filterByFileName(state.loaded, state.keyword).length, 0)
|
|
||||||
assert.equal(state.more.nextCursor, 'c1')
|
|
||||||
|
|
||||||
state = applyCursorPage(state, readPage({
|
|
||||||
list: [file('zzzz-found.txt', '9')],
|
|
||||||
hasMore: true,
|
|
||||||
nextPage: 3,
|
|
||||||
nextCursor: 'c2'
|
|
||||||
}))
|
|
||||||
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['9'])
|
|
||||||
assert.equal(state.selected.length, 0)
|
|
||||||
assert.ok(state.more)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('view switch and clear', () => {
|
|
||||||
it('keeps the keyword and selected identities when the view changes', () => {
|
|
||||||
const chosen = file('Alpha.TXT', '1')
|
|
||||||
const state = baseState({
|
|
||||||
keyword: ' Alpha ',
|
|
||||||
view: 'pane',
|
|
||||||
loaded: [chosen, file('Beta.bin', '2')],
|
|
||||||
selected: [chosen]
|
|
||||||
})
|
|
||||||
const tree = switchView(state, 'tree')
|
|
||||||
assert.equal(tree.view, 'tree')
|
|
||||||
assert.equal(tree.keyword, ' Alpha ')
|
|
||||||
assert.deepEqual(tree.selected.map(item => item.fileId), ['1'])
|
|
||||||
const back = switchView(tree, 'pane')
|
|
||||||
assert.equal(back.keyword, state.keyword)
|
|
||||||
assert.equal(isSelected(back.selected, chosen), true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('clearing the keyword shows every loaded row again', () => {
|
|
||||||
const state = baseState({
|
|
||||||
keyword: 'alpha',
|
|
||||||
loaded: [file('Alpha.TXT', '1'), file('Beta.bin', '2')]
|
|
||||||
})
|
|
||||||
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1'])
|
|
||||||
const cleared = clearKeyword(state)
|
|
||||||
assert.deepEqual(
|
|
||||||
filterByFileName(cleared.loaded, cleared.keyword).map(item => item.fileId),
|
|
||||||
['1', '2']
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('loaded tree nodes', () => {
|
|
||||||
it('skips unloaded folders, hidden placeholders, and does not invent a fetch', () => {
|
|
||||||
const secret = file('secret.txt', 'secret')
|
|
||||||
const more = { data: { fileType: 'more', fileName: '加载更多…' }, loaded: true, childNodes: [] }
|
|
||||||
const root = {
|
|
||||||
childNodes: [
|
|
||||||
{ data: file('root.txt', 'root'), loaded: true, childNodes: [] },
|
|
||||||
{
|
|
||||||
data: folder('closed', 'closed'),
|
|
||||||
loaded: false,
|
|
||||||
childNodes: [{ data: secret, loaded: true, childNodes: [] }]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
data: folder('open', 'open'),
|
|
||||||
loaded: true,
|
|
||||||
childNodes: [
|
|
||||||
{ data: file('open-a.txt', 'oa'), loaded: true, childNodes: [] },
|
|
||||||
more
|
|
||||||
]
|
|
||||||
},
|
|
||||||
more
|
|
||||||
]
|
|
||||||
}
|
|
||||||
const loaded = collectLoadedNodes(root)
|
|
||||||
assert.deepEqual(loaded.map(item => item.fileId), ['root', 'closed', 'open', 'oa'])
|
|
||||||
const selected = selectMatching([], loaded, '')
|
|
||||||
assert.deepEqual(selected.map(item => item.fileId), ['root', 'oa'])
|
|
||||||
assert.equal(isSelected(selected, secret), false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -51,7 +51,7 @@
|
|||||||
<el-icon><Key /></el-icon>
|
<el-icon><Key /></el-icon>
|
||||||
</el-button>
|
</el-button>
|
||||||
</el-tooltip>
|
</el-tooltip>
|
||||||
<el-tooltip v-if="donatedAccountsEnabled" content="捐赠网盘账号" placement="bottom">
|
<el-tooltip content="捐赠网盘账号" placement="bottom">
|
||||||
<el-button circle size="small" type="warning" @click="showDonateDialog = true">
|
<el-button circle size="small" type="warning" @click="showDonateDialog = true">
|
||||||
<el-icon><Present /></el-icon>
|
<el-icon><Present /></el-icon>
|
||||||
</el-button>
|
</el-button>
|
||||||
@@ -319,10 +319,6 @@
|
|||||||
width="550px"
|
width="550px"
|
||||||
:close-on-click-modal="false">
|
:close-on-click-modal="false">
|
||||||
<el-form :model="authConfig" label-width="100px" size="default">
|
<el-form :model="authConfig" label-width="100px" size="default">
|
||||||
<el-form-item label="服务认证密钥">
|
|
||||||
<el-input v-model="serverAuthKey" type="password" show-password
|
|
||||||
autocomplete="off" placeholder="自建站已配置的 authEncryptKey(仅本页内存)" />
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="网盘类型" required>
|
<el-form-item label="网盘类型" required>
|
||||||
<el-select v-model="authConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onPanTypeChange">
|
<el-select v-model="authConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onPanTypeChange">
|
||||||
<el-option-group label="必须认证">
|
<el-option-group label="必须认证">
|
||||||
@@ -436,7 +432,6 @@
|
|||||||
</div>
|
</div>
|
||||||
<DirectoryTree
|
<DirectoryTree
|
||||||
:file-list="directoryData"
|
:file-list="directoryData"
|
||||||
:root-page-info="directoryPageInfo"
|
|
||||||
:share-url="link"
|
:share-url="link"
|
||||||
:password="password"
|
:password="password"
|
||||||
:auth="directoryAuth"
|
:auth="directoryAuth"
|
||||||
@@ -577,6 +572,10 @@
|
|||||||
<el-form :model="donateConfig" label-width="100px" size="default">
|
<el-form :model="donateConfig" label-width="100px" size="default">
|
||||||
<el-form-item label="网盘类型" required>
|
<el-form-item label="网盘类型" required>
|
||||||
<el-select v-model="donateConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onDonatePanTypeChange">
|
<el-select v-model="donateConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onDonatePanTypeChange">
|
||||||
|
<el-option-group label="必须认证">
|
||||||
|
<el-option label="夸克网盘 (QK)" value="QK" />
|
||||||
|
<el-option label="UC网盘 (UC)" value="UC" />
|
||||||
|
</el-option-group>
|
||||||
<el-option-group label="大文件需认证">
|
<el-option-group label="大文件需认证">
|
||||||
<el-option label="小飞机网盘 (FJ)" value="FJ" />
|
<el-option label="小飞机网盘 (FJ)" value="FJ" />
|
||||||
<el-option label="蓝奏优享 (IZ)" value="IZ" />
|
<el-option label="蓝奏优享 (IZ)" value="IZ" />
|
||||||
@@ -671,7 +670,6 @@ export default {
|
|||||||
// 目录树
|
// 目录树
|
||||||
showDirectoryTree: false,
|
showDirectoryTree: false,
|
||||||
directoryData: [],
|
directoryData: [],
|
||||||
directoryPageInfo: null,
|
|
||||||
directoryAuth: '', // 目录解析时的加密 auth,透传给子目录/下载
|
directoryAuth: '', // 目录解析时的加密 auth,透传给子目录/下载
|
||||||
|
|
||||||
// 统计信息
|
// 统计信息
|
||||||
@@ -712,10 +710,8 @@ export default {
|
|||||||
},
|
},
|
||||||
// 所有网盘的认证配置 { panType: config }
|
// 所有网盘的认证配置 { panType: config }
|
||||||
allAuthConfigs: {},
|
allAuthConfigs: {},
|
||||||
serverAuthKey: '',
|
|
||||||
|
|
||||||
// 捐赠账号相关
|
// 捐赠账号相关
|
||||||
donatedAccountsEnabled: false,
|
|
||||||
showDonateDialog: false,
|
showDonateDialog: false,
|
||||||
donateSubmitting: false,
|
donateSubmitting: false,
|
||||||
donateConfig: {
|
donateConfig: {
|
||||||
@@ -781,7 +777,7 @@ export default {
|
|||||||
},
|
},
|
||||||
folderParseMeta() {
|
folderParseMeta() {
|
||||||
if (!this.showDirectoryTree) return []
|
if (!this.showDirectoryTree) return []
|
||||||
const meta = [`${this.directoryData.length}${this.directoryPageInfo?.hasMore ? '+' : ''} 个文件/文件夹`]
|
const meta = [`${this.directoryData.length} 个文件/文件夹`]
|
||||||
const recognized = parserUrl.parseLink(this.link || '')
|
const recognized = parserUrl.parseLink(this.link || '')
|
||||||
const panType = this.getCurrentPanType()
|
const panType = this.getCurrentPanType()
|
||||||
const name = recognized?.name || (panType ? parseResultMeta.panDisplayName(panType.toLowerCase(), this.panList) : '')
|
const name = recognized?.name || (panType ? parseResultMeta.panDisplayName(panType.toLowerCase(), this.panList) : '')
|
||||||
@@ -981,10 +977,6 @@ export default {
|
|||||||
|
|
||||||
// 保存认证配置
|
// 保存认证配置
|
||||||
saveAuthConfig() {
|
saveAuthConfig() {
|
||||||
if (![16, 24, 32].includes(new TextEncoder().encode(this.serverAuthKey).length)) {
|
|
||||||
this.$message.warning('个人认证需要自建站配置的服务认证密钥(16、24 或 32 个 UTF-8 字节)')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (!this.authConfig.panType) {
|
if (!this.authConfig.panType) {
|
||||||
this.$message.warning('请先选择网盘类型')
|
this.$message.warning('请先选择网盘类型')
|
||||||
return
|
return
|
||||||
@@ -1027,7 +1019,6 @@ export default {
|
|||||||
ext5: ''
|
ext5: ''
|
||||||
}
|
}
|
||||||
this.allAuthConfigs = {}
|
this.allAuthConfigs = {}
|
||||||
this.serverAuthKey = ''
|
|
||||||
localStorage.removeItem('nfd_auth_configs')
|
localStorage.removeItem('nfd_auth_configs')
|
||||||
this.$message.success('所有认证配置已清除')
|
this.$message.success('所有认证配置已清除')
|
||||||
this.showAuthConfigDialog = false
|
this.showAuthConfigDialog = false
|
||||||
@@ -1047,15 +1038,31 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// 个人认证由可信客户端使用自建服务显式配置的密钥编码;捐赠凭据只在服务端使用。
|
// 生成加密的 auth 参数(优先使用个人配置,否则从后端随机获取捐赠账号)
|
||||||
async generateAuthParam() {
|
async generateAuthParam() {
|
||||||
const panType = this.getCurrentPanType()
|
const panType = this.getCurrentPanType()
|
||||||
if (!panType) return ''
|
if (!panType) return ''
|
||||||
const config = this.allAuthConfigs[panType]
|
|
||||||
if (!config) return ''
|
let config = null
|
||||||
const key = this.serverAuthKey
|
|
||||||
if (![16, 24, 32].includes(new TextEncoder().encode(key).length)) return ''
|
// 优先使用个人配置
|
||||||
|
if (this.allAuthConfigs[panType]) {
|
||||||
|
config = this.allAuthConfigs[panType]
|
||||||
|
} else {
|
||||||
|
// 从后端随机获取捐赠账号(后端已加密,直接使用 encryptedAuth)
|
||||||
|
try {
|
||||||
|
const response = await axios.get(`${this.baseAPI}/v2/randomAuth`, { params: { panType } })
|
||||||
|
const encryptedAuth = response.data?.data?.encryptedAuth
|
||||||
|
if (encryptedAuth) {
|
||||||
|
return encryptedAuth
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// no available donated account
|
||||||
|
}
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
// 个人配置:本地 AES 加密
|
||||||
const authObj = {}
|
const authObj = {}
|
||||||
if (config.authType) authObj.authType = config.authType
|
if (config.authType) authObj.authType = config.authType
|
||||||
if (config.username) authObj.username = config.username
|
if (config.username) authObj.username = config.username
|
||||||
@@ -1070,7 +1077,7 @@ export default {
|
|||||||
if (config.ext5) authObj.ext5 = config.ext5
|
if (config.ext5) authObj.ext5 = config.ext5
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const encrypted = this.aesEncrypt(JSON.stringify(authObj), key)
|
const encrypted = this.aesEncrypt(JSON.stringify(authObj), 'nfd_auth_key2026')
|
||||||
return encodeURIComponent(encrypted)
|
return encodeURIComponent(encrypted)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('生成认证参数失败:', e)
|
console.error('生成认证参数失败:', e)
|
||||||
@@ -1235,7 +1242,6 @@ export default {
|
|||||||
this.statisticsData = {}
|
this.statisticsData = {}
|
||||||
this.showDirectoryTree = false
|
this.showDirectoryTree = false
|
||||||
this.directoryData = []
|
this.directoryData = []
|
||||||
this.directoryPageInfo = null
|
|
||||||
this.directoryAuth = ''
|
this.directoryAuth = ''
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -1370,17 +1376,14 @@ export default {
|
|||||||
params.auth = this.directoryAuth
|
params.auth = this.directoryAuth
|
||||||
}
|
}
|
||||||
|
|
||||||
// 直接调用 getFileListPage,让后端返回错误(不做客户端类型检查)
|
// 直接调用 getFileList,让后端返回错误(不做客户端类型检查)
|
||||||
const directoryResult = await this.callAPI('/v2/getFileListPage', params)
|
const directoryResult = await this.callAPI('/v2/getFileList', params)
|
||||||
const page = directoryResult.data || {}
|
this.directoryData = directoryResult.data || []
|
||||||
this.directoryPageInfo = Array.isArray(page) ? null : page
|
|
||||||
this.directoryData = Array.isArray(page) ? page : (page.list || [])
|
|
||||||
this.showDirectoryTree = true
|
this.showDirectoryTree = true
|
||||||
// 自动赋值分享链接
|
// 自动赋值分享链接
|
||||||
this.showListLink = `${this.baseUrl}/showList?url=${encodeURIComponent(this.link)}`
|
this.showListLink = `${this.baseUrl}/showList?url=${encodeURIComponent(this.link)}`
|
||||||
|
|
||||||
const more = this.directoryPageInfo?.hasMore ? '(当前为第 1 页,可在列表底部加载更多)' : ''
|
this.$message.success(`目录解析成功!共找到 ${this.directoryData.length} 个文件/文件夹`)
|
||||||
this.$message.success(`目录解析成功!共找到 ${this.directoryData.length} 个文件/文件夹${more}`)
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('目录解析失败:', error)
|
console.error('目录解析失败:', error)
|
||||||
}
|
}
|
||||||
@@ -1710,11 +1713,7 @@ export default {
|
|||||||
token: isPasswordAuth ? '' : (this.donateConfig.token || ''),
|
token: isPasswordAuth ? '' : (this.donateConfig.token || ''),
|
||||||
remark: this.donateConfig.remark || ''
|
remark: this.donateConfig.remark || ''
|
||||||
}
|
}
|
||||||
const response = await axios.post(`${this.baseAPI}/v2/donateAccount`, payload)
|
await axios.post(`${this.baseAPI}/v2/donateAccount`, payload)
|
||||||
if (response.data?.code !== 200) {
|
|
||||||
this.$message.error(response.data?.msg || '捐赠失败')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
this.$message.success(`已捐赠 ${this.getPanDisplayName(this.donateConfig.panType)} 账号,感谢您的贡献!`)
|
this.$message.success(`已捐赠 ${this.getPanDisplayName(this.donateConfig.panType)} 账号,感谢您的贡献!`)
|
||||||
|
|
||||||
// 重置表单
|
// 重置表单
|
||||||
@@ -1744,7 +1743,6 @@ export default {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (data && typeof data === 'object') {
|
if (data && typeof data === 'object') {
|
||||||
this.donatedAccountsEnabled = data.enabled === true
|
|
||||||
// 兼容新结构: { active: {...}, inactive: {...} }
|
// 兼容新结构: { active: {...}, inactive: {...} }
|
||||||
if (data.active && data.inactive) {
|
if (data.active && data.inactive) {
|
||||||
if (data.active.total === undefined) {
|
if (data.active.total === undefined) {
|
||||||
|
|||||||
@@ -20,7 +20,6 @@
|
|||||||
<div v-else>
|
<div v-else>
|
||||||
<DirectoryTree
|
<DirectoryTree
|
||||||
:file-list="directoryData"
|
:file-list="directoryData"
|
||||||
:root-page-info="pageInfo"
|
|
||||||
:share-url="url"
|
:share-url="url"
|
||||||
:password="''"
|
:password="''"
|
||||||
:view-mode="viewMode"
|
:view-mode="viewMode"
|
||||||
@@ -43,7 +42,6 @@ export default {
|
|||||||
loading: true,
|
loading: true,
|
||||||
error: '',
|
error: '',
|
||||||
directoryData: [],
|
directoryData: [],
|
||||||
pageInfo: null,
|
|
||||||
url: '',
|
url: '',
|
||||||
viewMode: 'pane'
|
viewMode: 'pane'
|
||||||
}
|
}
|
||||||
@@ -57,10 +55,8 @@ export default {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const res = await axios.get('/v2/getFileListPage', { params: { url: this.url } })
|
const res = await axios.get('/v2/getFileList', { params: { url: this.url } })
|
||||||
const page = res.data.data || {}
|
this.directoryData = res.data.data || []
|
||||||
this.pageInfo = Array.isArray(page) ? null : page
|
|
||||||
this.directoryData = Array.isArray(page) ? page : (page.list || [])
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.error = e.response?.data?.msg || e.response?.data?.error || '目录解析失败'
|
this.error = e.response?.data?.msg || e.response?.data?.error || '目录解析失败'
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import cn.qaiu.db.pool.JDBCPoolInit;
|
|||||||
import cn.qaiu.lz.common.cache.CacheConfigLoader;
|
import cn.qaiu.lz.common.cache.CacheConfigLoader;
|
||||||
import cn.qaiu.lz.common.cache.CacheManager;
|
import cn.qaiu.lz.common.cache.CacheManager;
|
||||||
import cn.qaiu.lz.common.interceptorImpl.RateLimiter;
|
import cn.qaiu.lz.common.interceptorImpl.RateLimiter;
|
||||||
import cn.qaiu.lz.common.util.AuthParamCodec;
|
|
||||||
import cn.qaiu.lz.web.config.PlaygroundConfig;
|
import cn.qaiu.lz.web.config.PlaygroundConfig;
|
||||||
import cn.qaiu.lz.web.service.DbService;
|
import cn.qaiu.lz.web.service.DbService;
|
||||||
import cn.qaiu.lz.web.service.impl.ShoutServiceImpl;
|
import cn.qaiu.lz.web.service.impl.ShoutServiceImpl;
|
||||||
@@ -91,7 +90,6 @@ public class AppMain {
|
|||||||
* @param jsonObject 配置
|
* @param jsonObject 配置
|
||||||
*/
|
*/
|
||||||
private static void exec(JsonObject jsonObject) {
|
private static void exec(JsonObject jsonObject) {
|
||||||
AuthParamCodec.configure(jsonObject.getJsonObject(ConfigConstant.SERVER));
|
|
||||||
WebClientVertxInit.init(VertxHolder.getVertxInstance());
|
WebClientVertxInit.init(VertxHolder.getVertxInstance());
|
||||||
DatabindCodec.mapper().registerModule(new JavaTimeModule());
|
DatabindCodec.mapper().registerModule(new JavaTimeModule());
|
||||||
// 演练场配置要先加载,后续启动流程才能按开关决定是否注册动态解析器。
|
// 演练场配置要先加载,后续启动流程才能按开关决定是否注册动态解析器。
|
||||||
|
|||||||
@@ -3,18 +3,13 @@ package cn.qaiu.lz.common.util;
|
|||||||
import cn.qaiu.lz.web.model.AuthParam;
|
import cn.qaiu.lz.web.model.AuthParam;
|
||||||
import cn.qaiu.util.AESUtils;
|
import cn.qaiu.util.AESUtils;
|
||||||
import cn.qaiu.util.Base64Decoder;
|
import cn.qaiu.util.Base64Decoder;
|
||||||
|
import cn.qaiu.vx.core.util.SharedDataUtil;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
|
||||||
import java.net.URLDecoder;
|
import java.net.URLDecoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.security.MessageDigest;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.security.SecureRandom;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.HexFormat;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 认证参数编解码工具类
|
* 认证参数编解码工具类
|
||||||
@@ -29,56 +24,34 @@ import java.util.HexFormat;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
public class AuthParamCodec {
|
public class AuthParamCodec {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 默认加密密钥(16位)
|
||||||
|
*/
|
||||||
|
private static final String DEFAULT_ENCRYPT_KEY = "nfd_auth_key2026";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 配置中的密钥路径
|
||||||
|
*/
|
||||||
private static final String CONFIG_KEY_PATH = "authEncryptKey";
|
private static final String CONFIG_KEY_PATH = "authEncryptKey";
|
||||||
// 识别升级时保留下来的旧发行版配置;不再使用旧密钥。
|
|
||||||
private static final String RETIRED_KEY_SHA256 = "b2c23dd4619534db9831db32be8e699412f1de60138ac37234eaae827ff1bcf4";
|
|
||||||
private static final String PROCESS_RANDOM_KEY = generateKey();
|
|
||||||
private static volatile String encryptKey = PROCESS_RANDOM_KEY;
|
|
||||||
|
|
||||||
private AuthParamCodec() {
|
private AuthParamCodec() {
|
||||||
|
// 工具类禁止实例化
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void configure(JsonObject serverConfig) {
|
/**
|
||||||
String configuredKey = serverConfig.getString(CONFIG_KEY_PATH);
|
* 获取加密密钥
|
||||||
encryptKey = selectKey(configuredKey);
|
* 优先从配置文件读取,如果未配置则使用默认密钥
|
||||||
log.info("authEncryptKey: source={}, fingerprint(SHA-256)={}",
|
*/
|
||||||
encryptKey == PROCESS_RANDOM_KEY ? "generated (this process only)" : "configured",
|
|
||||||
fingerprint(encryptKey).substring(0, 12));
|
|
||||||
}
|
|
||||||
|
|
||||||
static String selectKey(String configuredKey) {
|
|
||||||
if (StringUtils.isBlank(configuredKey) || RETIRED_KEY_SHA256.equals(fingerprint(configuredKey))) {
|
|
||||||
return PROCESS_RANDOM_KEY;
|
|
||||||
}
|
|
||||||
int length = configuredKey.getBytes(StandardCharsets.UTF_8).length;
|
|
||||||
if (length != 16 && length != 24 && length != 32) {
|
|
||||||
throw new IllegalArgumentException("server.authEncryptKey must be 16, 24, or 32 UTF-8 bytes");
|
|
||||||
}
|
|
||||||
return configuredKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String generateKey() {
|
|
||||||
byte[] random = new byte[24];
|
|
||||||
new SecureRandom().nextBytes(random);
|
|
||||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(random);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String fingerprint(String value) {
|
|
||||||
try {
|
|
||||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
|
|
||||||
.digest(value.getBytes(StandardCharsets.UTF_8)));
|
|
||||||
} catch (NoSuchAlgorithmException e) {
|
|
||||||
throw new IllegalStateException("SHA-256 unavailable", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static SecretKeySpec asAesKey(String key) {
|
|
||||||
// Match CryptoJS: AES key lengths and values are defined by the full UTF-8 bytes.
|
|
||||||
return new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String getEncryptKey() {
|
public static String getEncryptKey() {
|
||||||
return encryptKey;
|
try {
|
||||||
|
String configKey = SharedDataUtil.getJsonStringForServerConfig(CONFIG_KEY_PATH);
|
||||||
|
if (StringUtils.isNotBlank(configKey)) {
|
||||||
|
return configKey;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("从配置读取加密密钥失败,使用默认密钥: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
return DEFAULT_ENCRYPT_KEY;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -96,7 +69,7 @@ public class AuthParamCodec {
|
|||||||
* 解码认证参数(指定密钥)
|
* 解码认证参数(指定密钥)
|
||||||
*
|
*
|
||||||
* @param encryptedAuth 加密后的认证参数字符串
|
* @param encryptedAuth 加密后的认证参数字符串
|
||||||
* @param key AES 密钥(16、24 或 32 个 UTF-8 字节)
|
* @param key AES密钥(16位)
|
||||||
* @return AuthParam 对象,解码失败返回 null
|
* @return AuthParam 对象,解码失败返回 null
|
||||||
*/
|
*/
|
||||||
public static AuthParam decode(String encryptedAuth, String key) {
|
public static AuthParam decode(String encryptedAuth, String key) {
|
||||||
@@ -112,13 +85,15 @@ public class AuthParamCodec {
|
|||||||
}
|
}
|
||||||
// 兼容 query 参数中 '+' 被还原为空格的情况
|
// 兼容 query 参数中 '+' 被还原为空格的情况
|
||||||
normalized = normalized.replace(' ', '+');
|
normalized = normalized.replace(' ', '+');
|
||||||
|
log.debug("认证参数规范化结果: {}", normalized);
|
||||||
|
|
||||||
// Step 2: Base64解码
|
// Step 2: Base64解码
|
||||||
byte[] base64Decoded = Base64Decoder.decode(normalized);
|
byte[] base64Decoded = Base64Decoder.decode(normalized);
|
||||||
log.debug("Base64解码成功,长度: {}", base64Decoded.length);
|
log.debug("Base64解码成功,长度: {}", base64Decoded.length);
|
||||||
|
|
||||||
// Step 3: AES解密
|
// Step 3: AES解密
|
||||||
String jsonStr = AESUtils.decryptByAES(base64Decoded, asAesKey(key));
|
String jsonStr = AESUtils.decryptByAES(base64Decoded, key);
|
||||||
|
log.debug("AES解密结果: {}", jsonStr);
|
||||||
|
|
||||||
// Step 4: JSON解析
|
// Step 4: JSON解析
|
||||||
JsonObject json = new JsonObject(jsonStr);
|
JsonObject json = new JsonObject(jsonStr);
|
||||||
@@ -127,9 +102,9 @@ public class AuthParamCodec {
|
|||||||
return authParam;
|
return authParam;
|
||||||
|
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
log.warn("认证参数格式无效");
|
log.warn("认证参数Base64解码失败: {}", e.getMessage());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("认证参数解码失败");
|
log.warn("认证参数解码失败: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -149,7 +124,7 @@ public class AuthParamCodec {
|
|||||||
* 编码认证参数(指定密钥)
|
* 编码认证参数(指定密钥)
|
||||||
*
|
*
|
||||||
* @param authParam 认证参数对象
|
* @param authParam 认证参数对象
|
||||||
* @param key AES 密钥(16、24 或 32 个 UTF-8 字节)
|
* @param key AES密钥(16位)
|
||||||
* @return 加密后的字符串,编码失败返回 null
|
* @return 加密后的字符串,编码失败返回 null
|
||||||
*/
|
*/
|
||||||
public static String encode(AuthParam authParam, String key) {
|
public static String encode(AuthParam authParam, String key) {
|
||||||
@@ -160,12 +135,15 @@ public class AuthParamCodec {
|
|||||||
try {
|
try {
|
||||||
// Step 1: 转换为JSON
|
// Step 1: 转换为JSON
|
||||||
String jsonStr = authParam.toJsonObject().encode();
|
String jsonStr = authParam.toJsonObject().encode();
|
||||||
|
log.debug("JSON字符串: {}", jsonStr);
|
||||||
|
|
||||||
// Step 2: AES加密 + Base64编码
|
// Step 2: AES加密 + Base64编码
|
||||||
String base64Encoded = AESUtils.encryptBase64ByAES(jsonStr, asAesKey(key));
|
String base64Encoded = AESUtils.encryptBase64ByAES(jsonStr, key);
|
||||||
|
log.debug("AES+Base64编码结果: {}", base64Encoded);
|
||||||
|
|
||||||
// Step 3: URL编码
|
// Step 3: URL编码
|
||||||
String urlEncoded = java.net.URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8);
|
String urlEncoded = java.net.URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8);
|
||||||
|
log.debug("URL编码结果: {}", urlEncoded);
|
||||||
|
|
||||||
return urlEncoded;
|
return urlEncoded;
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import cn.qaiu.lz.web.service.DbService;
|
|||||||
import cn.qaiu.parser.ParserCreate;
|
import cn.qaiu.parser.ParserCreate;
|
||||||
import cn.qaiu.vx.core.util.ConfigConstant;
|
import cn.qaiu.vx.core.util.ConfigConstant;
|
||||||
import cn.qaiu.vx.core.util.VertxHolder;
|
import cn.qaiu.vx.core.util.VertxHolder;
|
||||||
import cn.qaiu.vx.core.util.SharedDataUtil;
|
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
import io.vertx.core.MultiMap;
|
import io.vertx.core.MultiMap;
|
||||||
import io.vertx.core.http.HttpServerRequest;
|
import io.vertx.core.http.HttpServerRequest;
|
||||||
@@ -89,7 +88,7 @@ public class ParserAuthUtil {
|
|||||||
|
|
||||||
public static void recordDonatedAccountFailureIfNeeded(DbService dbService, JsonObject otherParam,
|
public static void recordDonatedAccountFailureIfNeeded(DbService dbService, JsonObject otherParam,
|
||||||
Throwable cause) {
|
Throwable cause) {
|
||||||
if (otherParam == null || !isLikelyAuthFailure(cause) || !isDonatedAccountsEnabled()) {
|
if (!isLikelyAuthFailure(cause) || otherParam == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String donatedAccountToken = otherParam.getString("donatedAccountToken");
|
String donatedAccountToken = otherParam.getString("donatedAccountToken");
|
||||||
@@ -102,7 +101,7 @@ public class ParserAuthUtil {
|
|||||||
|
|
||||||
public static void recordAutoDonatedFailureIfNeeded(DbService dbService, ShareLinkInfo shareLinkInfo,
|
public static void recordAutoDonatedFailureIfNeeded(DbService dbService, ShareLinkInfo shareLinkInfo,
|
||||||
Throwable cause) {
|
Throwable cause) {
|
||||||
if (shareLinkInfo == null || !isLikelyAuthFailure(cause) || !isDonatedAccountsEnabled()) {
|
if (shareLinkInfo == null || !isLikelyAuthFailure(cause)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Object tokenObj = shareLinkInfo.getOtherParam().get(DONATED_ACCOUNT_TOKEN);
|
Object tokenObj = shareLinkInfo.getOtherParam().get(DONATED_ACCOUNT_TOKEN);
|
||||||
@@ -113,31 +112,14 @@ public class ParserAuthUtil {
|
|||||||
.onFailure(e -> log.warn("记录自动捐赠账号失败次数失败", e));
|
.onFailure(e -> log.warn("记录自动捐赠账号失败次数失败", e));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isDonatedAccountsEnabled() {
|
|
||||||
return isDonatedAccountsEnabled(SharedDataUtil.getJsonConfig(ConfigConstant.SERVER));
|
|
||||||
}
|
|
||||||
|
|
||||||
static boolean isDonatedAccountsEnabled(JsonObject server) {
|
|
||||||
return server != null && Boolean.TRUE.equals(server.getValue("enableDonatedAccounts"))
|
|
||||||
&& Boolean.TRUE.equals(server.getValue("enableDatabase"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 只启用已检查解析结果不会携带捐赠账号下载请求头的网盘。
|
|
||||||
public static boolean supportsServerSideDonation(String type) {
|
|
||||||
return "ye".equalsIgnoreCase(type) || "fj".equalsIgnoreCase(type) || "iz".equalsIgnoreCase(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Future<Void> applyDonatedAccountFallback(ParserCreate parserCreate, DbService dbService) {
|
private static Future<Void> applyDonatedAccountFallback(ParserCreate parserCreate, DbService dbService) {
|
||||||
if (!isDonatedAccountsEnabled()) {
|
|
||||||
return Future.succeededFuture();
|
|
||||||
}
|
|
||||||
ShareLinkInfo shareLinkInfo = parserCreate.getShareLinkInfo();
|
ShareLinkInfo shareLinkInfo = parserCreate.getShareLinkInfo();
|
||||||
Map<String, Object> otherParam = shareLinkInfo.getOtherParam();
|
Map<String, Object> otherParam = shareLinkInfo.getOtherParam();
|
||||||
if (Boolean.TRUE.equals(otherParam.get(TEMP_AUTH_ADDED))) {
|
if (Boolean.TRUE.equals(otherParam.get(TEMP_AUTH_ADDED))) {
|
||||||
return Future.succeededFuture();
|
return Future.succeededFuture();
|
||||||
}
|
}
|
||||||
String type = shareLinkInfo.getType();
|
String type = shareLinkInfo.getType();
|
||||||
if (!supportsServerSideDonation(type) || hasUsableStaticAuthConfig(type)) {
|
if (StringUtils.isBlank(type) || hasUsableStaticAuthConfig(type)) {
|
||||||
return Future.succeededFuture();
|
return Future.succeededFuture();
|
||||||
}
|
}
|
||||||
return dbService.getRandomDonatedAccount(type.toUpperCase())
|
return dbService.getRandomDonatedAccount(type.toUpperCase())
|
||||||
|
|||||||
@@ -71,9 +71,7 @@ public class URLParamUtil {
|
|||||||
// 忽略单独处理的参数,不应拼接到分享URL中
|
// 忽略单独处理的参数,不应拼接到分享URL中
|
||||||
if (!paramName.equals("url") && !paramName.equals("pwd") && !paramName.equals("dirId")
|
if (!paramName.equals("url") && !paramName.equals("pwd") && !paramName.equals("dirId")
|
||||||
&& !paramName.equals("uuid") && !paramName.equals("auth")
|
&& !paramName.equals("uuid") && !paramName.equals("auth")
|
||||||
&& !paramName.equals("stoken") && !paramName.equals("zml")
|
&& !paramName.equals("stoken") && !paramName.equals("zml")) {
|
||||||
&& !paramName.equals("page") && !paramName.equals("pg")
|
|
||||||
&& !paramName.equals("pageCursor")) {
|
|
||||||
if (firstParam) {
|
if (firstParam) {
|
||||||
urlBuilder.append("?");
|
urlBuilder.append("?");
|
||||||
firstParam = false;
|
firstParam = false;
|
||||||
|
|||||||
@@ -10,11 +10,9 @@ import cn.qaiu.lz.common.util.URLParamUtil;
|
|||||||
import cn.qaiu.lz.web.model.AuthParam;
|
import cn.qaiu.lz.web.model.AuthParam;
|
||||||
import cn.qaiu.lz.web.model.CacheLinkInfo;
|
import cn.qaiu.lz.web.model.CacheLinkInfo;
|
||||||
import cn.qaiu.lz.web.model.ClientLinkResp;
|
import cn.qaiu.lz.web.model.ClientLinkResp;
|
||||||
import cn.qaiu.lz.web.model.FileListPageResp;
|
|
||||||
import cn.qaiu.lz.web.model.LinkInfoResp;
|
import cn.qaiu.lz.web.model.LinkInfoResp;
|
||||||
import cn.qaiu.lz.web.model.StatisticsInfo;
|
import cn.qaiu.lz.web.model.StatisticsInfo;
|
||||||
import cn.qaiu.lz.web.service.DbService;
|
import cn.qaiu.lz.web.service.DbService;
|
||||||
import cn.qaiu.parser.FolderPaging;
|
|
||||||
import cn.qaiu.parser.PanDomainTemplate;
|
import cn.qaiu.parser.PanDomainTemplate;
|
||||||
import cn.qaiu.parser.IPanTool;
|
import cn.qaiu.parser.IPanTool;
|
||||||
import cn.qaiu.parser.ParserCreate;
|
import cn.qaiu.parser.ParserCreate;
|
||||||
@@ -164,50 +162,9 @@ public class ParserApi {
|
|||||||
}}).collect(Collectors.toList());
|
}}).collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 目录列表。不带 page 时行为与旧版一致;带 page 时返回该页(结构不变)。pg 是 page 的别名。
|
|
||||||
* 需要 hasMore / nextCursor 时用 {@link #getFileListPage}。
|
|
||||||
*/
|
|
||||||
@RouteMapping("/getFileList")
|
@RouteMapping("/getFileList")
|
||||||
public Future<List<FileInfo>> getFileList(HttpServerRequest request, String pwd, String dirId, String uuid,
|
public Future<List<FileInfo>> getFileList(HttpServerRequest request, String pwd, String dirId, String uuid,
|
||||||
String stoken, String zml, String auth,
|
String stoken, String zml, String auth) {
|
||||||
String page, String pg, String pageCursor) {
|
|
||||||
Integer pageNo;
|
|
||||||
try {
|
|
||||||
pageNo = FolderPaging.parsePage(StringUtils.isNotBlank(page) ? page : pg);
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
return Future.failedFuture(e.getMessage());
|
|
||||||
}
|
|
||||||
return listFolder(request, pwd, dirId, uuid, stoken, zml, auth, pageNo, pageCursor)
|
|
||||||
.map(FolderListResult::list);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 目录分页:参数同 /getFileList,另有 page(默认 1)与 pageCursor(上一页的 nextCursor)。
|
|
||||||
*/
|
|
||||||
@RouteMapping("/getFileListPage")
|
|
||||||
public Future<FileListPageResp> getFileListPage(HttpServerRequest request, String pwd, String dirId, String uuid,
|
|
||||||
String stoken, String zml, String auth,
|
|
||||||
String page, String pg, String pageCursor) {
|
|
||||||
int pageNo;
|
|
||||||
try {
|
|
||||||
Integer parsed = FolderPaging.parsePage(StringUtils.isNotBlank(page) ? page : pg);
|
|
||||||
pageNo = parsed == null ? 1 : parsed;
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
return Future.failedFuture(e.getMessage());
|
|
||||||
}
|
|
||||||
return listFolder(request, pwd, dirId, uuid, stoken, zml, auth, pageNo, pageCursor)
|
|
||||||
.map(r -> r.unpagedBeyondFirst()
|
|
||||||
? FileListPageResp.beyondUnpaged(pageNo)
|
|
||||||
: FileListPageResp.of(r.list(), pageNo, FolderPaging.pageInfo(r.shareLinkInfo())));
|
|
||||||
}
|
|
||||||
|
|
||||||
private record FolderListResult(List<FileInfo> list, ShareLinkInfo shareLinkInfo, boolean unpagedBeyondFirst) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private Future<FolderListResult> listFolder(HttpServerRequest request, String pwd, String dirId, String uuid,
|
|
||||||
String stoken, String zml, String auth,
|
|
||||||
Integer page, String pageCursor) {
|
|
||||||
String url = URLParamUtil.parserParams(request);
|
String url = URLParamUtil.parserParams(request);
|
||||||
ParserCreate parserCreate;
|
ParserCreate parserCreate;
|
||||||
try {
|
try {
|
||||||
@@ -215,16 +172,6 @@ public class ParserApi {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return Future.failedFuture(e);
|
return Future.failedFuture(e);
|
||||||
}
|
}
|
||||||
ShareLinkInfo info = parserCreate.getShareLinkInfo();
|
|
||||||
if (page != null && page > 1 && !FileListPageResp.isPagedType(info.getType())) {
|
|
||||||
return Future.succeededFuture(new FolderListResult(new ArrayList<>(), info, true));
|
|
||||||
}
|
|
||||||
if (page != null) {
|
|
||||||
info.getOtherParam().put(FolderPaging.PAGE, page);
|
|
||||||
if (StringUtils.isNotBlank(pageCursor)) {
|
|
||||||
info.getOtherParam().put(FolderPaging.CURSOR, pageCursor);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
String linkPrefix = getLinkPrefix(request);
|
String linkPrefix = getLinkPrefix(request);
|
||||||
JsonObject otherParam = ParserAuthUtil.buildOtherParam(request, auth, linkPrefix);
|
JsonObject otherParam = ParserAuthUtil.buildOtherParam(request, auth, linkPrefix);
|
||||||
parserCreate.getShareLinkInfo().getOtherParam().put("domainName", linkPrefix);
|
parserCreate.getShareLinkInfo().getOtherParam().put("domainName", linkPrefix);
|
||||||
@@ -251,8 +198,7 @@ public class ParserApi {
|
|||||||
ParserAuthUtil.recordAutoDonatedFailureIfNeeded(dbService,
|
ParserAuthUtil.recordAutoDonatedFailureIfNeeded(dbService,
|
||||||
parserCreate.getShareLinkInfo(), t);
|
parserCreate.getShareLinkInfo(), t);
|
||||||
});
|
});
|
||||||
})
|
});
|
||||||
.map(list -> new FolderListResult(list, info, false));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 目录解析下载文件
|
// 目录解析下载文件
|
||||||
@@ -770,18 +716,11 @@ public class ParserApi {
|
|||||||
*/
|
*/
|
||||||
@RouteMapping(value = "/donateAccount", method = RouteMethod.POST)
|
@RouteMapping(value = "/donateAccount", method = RouteMethod.POST)
|
||||||
public Future<JsonObject> donateAccount(RoutingContext ctx) {
|
public Future<JsonObject> donateAccount(RoutingContext ctx) {
|
||||||
if (!ParserAuthUtil.isDonatedAccountsEnabled()) {
|
|
||||||
return Future.succeededFuture(JsonResult.error("捐赠账号功能未启用").toJsonObject());
|
|
||||||
}
|
|
||||||
JsonObject body = ctx.body().asJsonObject();
|
JsonObject body = ctx.body().asJsonObject();
|
||||||
if (body == null || StringUtils.isBlank(body.getString("panType"))
|
if (body == null || StringUtils.isBlank(body.getString("panType"))
|
||||||
|| StringUtils.isBlank(body.getString("authType"))) {
|
|| StringUtils.isBlank(body.getString("authType"))) {
|
||||||
return Future.succeededFuture(JsonResult.error("panType and authType are required").toJsonObject());
|
return Future.succeededFuture(JsonResult.error("panType and authType are required").toJsonObject());
|
||||||
}
|
}
|
||||||
if (!ParserAuthUtil.supportsServerSideDonation(body.getString("panType"))) {
|
|
||||||
return Future.succeededFuture(JsonResult.error("该网盘暂不支持服务端捐赠池").toJsonObject());
|
|
||||||
}
|
|
||||||
body.put("panType", body.getString("panType").toUpperCase(java.util.Locale.ROOT));
|
|
||||||
String ip = ctx.request().remoteAddress().host();
|
String ip = ctx.request().remoteAddress().host();
|
||||||
body.put("ip", ip);
|
body.put("ip", ip);
|
||||||
return dbService.saveDonatedAccount(body);
|
return dbService.saveDonatedAccount(body);
|
||||||
@@ -792,16 +731,23 @@ public class ParserApi {
|
|||||||
*/
|
*/
|
||||||
@RouteMapping(value = "/donateAccountCounts", method = RouteMethod.GET)
|
@RouteMapping(value = "/donateAccountCounts", method = RouteMethod.GET)
|
||||||
public Future<JsonObject> getDonateAccountCounts() {
|
public Future<JsonObject> getDonateAccountCounts() {
|
||||||
if (!ParserAuthUtil.isDonatedAccountsEnabled()) {
|
return dbService.getDonatedAccountCounts();
|
||||||
return Future.succeededFuture(JsonResult.data(new JsonObject().put("enabled", false)).toJsonObject());
|
|
||||||
}
|
|
||||||
return dbService.getDonatedAccountCounts().map(result -> {
|
|
||||||
JsonObject data = result.getJsonObject("data");
|
|
||||||
if (data != null) {
|
|
||||||
data.put("enabled", true);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 随机获取指定网盘类型的捐赠账号(内部使用,返回加密后的 auth 参数)
|
||||||
|
*/
|
||||||
|
@RouteMapping(value = "/randomAuth", method = RouteMethod.GET)
|
||||||
|
public Future<JsonObject> getRandomAuth(String panType) {
|
||||||
|
return dbService.getRandomDonatedAccount(panType).map(res -> {
|
||||||
|
if (Integer.valueOf(200).equals(res.getInteger("code")) && res.getJsonObject("data") != null) {
|
||||||
|
JsonObject data = res.getJsonObject("data");
|
||||||
|
String encryptedAuth = AuthParamCodec.encode(data);
|
||||||
|
JsonObject safeData = new JsonObject();
|
||||||
|
safeData.put("encryptedAuth", encryptedAuth);
|
||||||
|
res.put("data", safeData);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
package cn.qaiu.lz.web.model;
|
|
||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
|
||||||
import cn.qaiu.parser.FolderPaging;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
import lombok.Builder;
|
|
||||||
import lombok.Data;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* /v2/getFileListPage 的返回体。list 与 /v2/getFileList 的 data 结构一致。
|
|
||||||
* paged=false 表示该网盘不支持分页,list 已是完整目录,不要再请求下一页。
|
|
||||||
*/
|
|
||||||
@Data
|
|
||||||
@Builder
|
|
||||||
public class FileListPageResp {
|
|
||||||
private List<FileInfo> list;
|
|
||||||
private boolean paged;
|
|
||||||
private int page;
|
|
||||||
private Integer pageSize;
|
|
||||||
private boolean hasMore;
|
|
||||||
private Integer nextPage;
|
|
||||||
private String nextCursor;
|
|
||||||
private Integer total;
|
|
||||||
private Integer totalPage;
|
|
||||||
|
|
||||||
public static FileListPageResp of(List<FileInfo> list, int page, JsonObject pageInfo) {
|
|
||||||
if (pageInfo == null) {
|
|
||||||
return FileListPageResp.builder().list(list).paged(false).page(page).hasMore(false).build();
|
|
||||||
}
|
|
||||||
return FileListPageResp.builder()
|
|
||||||
.list(list)
|
|
||||||
.paged(true)
|
|
||||||
.page(pageInfo.getInteger("page", page))
|
|
||||||
.pageSize(pageInfo.getInteger("pageSize"))
|
|
||||||
.hasMore(Boolean.TRUE.equals(pageInfo.getBoolean("hasMore")))
|
|
||||||
.nextPage(pageInfo.getInteger("nextPage"))
|
|
||||||
.nextCursor(pageInfo.getString("nextCursor"))
|
|
||||||
.total(pageInfo.getInteger("total"))
|
|
||||||
.totalPage(pageInfo.getInteger("totalPage"))
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 不分页网盘的第 2 页及以后:返回空页,避免客户端重复追加同一份列表。 */
|
|
||||||
public static FileListPageResp beyondUnpaged(int page) {
|
|
||||||
return FileListPageResp.builder().list(List.of()).paged(false).page(page).hasMore(false).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
public static boolean isPagedType(String type) {
|
|
||||||
return FolderPaging.supports(type);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -39,7 +39,7 @@ public class DbServiceImpl implements DbService {
|
|||||||
private static final long FAILURE_TOKEN_TTL_MILLIS = 10 * 60 * 1000L;
|
private static final long FAILURE_TOKEN_TTL_MILLIS = 10 * 60 * 1000L;
|
||||||
private static final String HMAC_ALGORITHM = "HmacSHA256";
|
private static final String HMAC_ALGORITHM = "HmacSHA256";
|
||||||
private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_CONFIG = "donatedAccountFailureTokenSignKey";
|
private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_CONFIG = "donatedAccountFailureTokenSignKey";
|
||||||
private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK = java.util.UUID.randomUUID().toString() + java.util.UUID.randomUUID();
|
private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK = "nfd_donate_fail_token_sign_2026";
|
||||||
@Override
|
@Override
|
||||||
public Future<JsonObject> sayOk(String data) {
|
public Future<JsonObject> sayOk(String data) {
|
||||||
log.info("say ok1 -> wait...");
|
log.info("say ok1 -> wait...");
|
||||||
@@ -574,7 +574,7 @@ public class DbServiceImpl implements DbService {
|
|||||||
return configKey;
|
return configKey;
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.debug("读取捐赠账号失败计数签名密钥失败,使用进程随机值: {}", e.getMessage());
|
log.debug("读取捐赠账号失败计数签名密钥失败,使用默认值: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
return DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK;
|
return DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,10 +8,8 @@ server:
|
|||||||
# domainName: http://127.0.0.1:6401
|
# domainName: http://127.0.0.1:6401
|
||||||
# 预览服务URL
|
# 预览服务URL
|
||||||
previewURL: https://nfd-parser.github.io/nfd-preview/preview.html?src=
|
previewURL: https://nfd-parser.github.io/nfd-preview/preview.html?src=
|
||||||
# 未配置时每次启动自动生成随机密钥;多实例或外部客户端可配置共享密钥。
|
# auth参数加密密钥(16位AES密钥)
|
||||||
# authEncryptKey: ""
|
authEncryptKey: 'nfd_auth_key2026'
|
||||||
# 捐赠默认关闭;开启后凭据仅供服务端选用。
|
|
||||||
enableDonatedAccounts: false
|
|
||||||
|
|
||||||
# 反向代理服务器配置路径(不用加后缀)
|
# 反向代理服务器配置路径(不用加后缀)
|
||||||
proxyConf: server-proxy
|
proxyConf: server-proxy
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ import cn.qaiu.util.AESUtils;
|
|||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import javax.crypto.Cipher;
|
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
|
||||||
import java.net.URLDecoder;
|
import java.net.URLDecoder;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
@@ -23,64 +21,7 @@ import static org.junit.Assert.*;
|
|||||||
public class AuthParamCodecTest {
|
public class AuthParamCodecTest {
|
||||||
|
|
||||||
// 测试用的固定密钥
|
// 测试用的固定密钥
|
||||||
private static final String TEST_KEY = "dummy-test-key16";
|
private static final String TEST_KEY = "nfd_auth_key2026";
|
||||||
|
|
||||||
@Test
|
|
||||||
public void usesOneRandomKeyPerProcessAndSupportsExplicitConfiguration() {
|
|
||||||
String generated = AuthParamCodec.selectKey(null);
|
|
||||||
assertEquals(32, generated.getBytes(StandardCharsets.UTF_8).length);
|
|
||||||
assertSame(generated, AuthParamCodec.selectKey(""));
|
|
||||||
assertSame(generated, AuthParamCodec.selectKey(" "));
|
|
||||||
assertNotEquals(AuthParamCodec.generateKey(), AuthParamCodec.generateKey());
|
|
||||||
assertEquals(TEST_KEY, AuthParamCodec.selectKey(TEST_KEY));
|
|
||||||
assertThrows(IllegalArgumentException.class, () -> AuthParamCodec.selectKey("invalid length"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void generatedKeyRoundTripsSyntheticAuth() {
|
|
||||||
AuthParam auth = AuthParam.builder().authType("token").token("synthetic-only").build();
|
|
||||||
String key = AuthParamCodec.selectKey(null);
|
|
||||||
assertEquals("synthetic-only",
|
|
||||||
AuthParamCodec.decode(AuthParamCodec.encode(auth, key), key).getToken());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void interoperatesWithBrowserCryptoJsUsingFullUtf8Key() throws Exception {
|
|
||||||
// CryptoJS 4.2.0: AES-ECB/PKCS7, Utf8.parse(key),
|
|
||||||
// plaintext {"authType":"token","token":"synthetic-认证"}.
|
|
||||||
String[][] browserVectors = {
|
|
||||||
{"0123456789abcdef", "VxQ8JVsWso0Fhf76r82AjtWhuqKaDUtBWPUJcD+Oc1lGwDq001J2N8LJH3RSFBcA"},
|
|
||||||
{"0123456789abcdefghijklmn", "kCYuDyekW7KZf8rlLqIR0Rcwp7QWcFYn5X6tsGd6XUqlGf9RoJyFzogOgU26JJNS"},
|
|
||||||
{"0123456789abcdefghijklmnopqrstuv", "FB94nNibPhLIh+oMcnJW0Iuu3O3xSPK0WVHXCiwnvbblwSfe++oPk3RZmw6/7OqX"},
|
|
||||||
{"密钥测试甲乙丙丁", "cg0YzgNOQxws0chQxDOnepm1Ht+Pkgo7Am9McLXjkUcC35QcRiyHELm0/g4WQm2e"}
|
|
||||||
};
|
|
||||||
for (String[] vector : browserVectors) {
|
|
||||||
String key = vector[0];
|
|
||||||
AuthParam decoded = AuthParamCodec.decode(URLEncoder.encode(vector[1], StandardCharsets.UTF_8), key);
|
|
||||||
assertNotNull("browser ciphertext should decode with " + key.getBytes(StandardCharsets.UTF_8).length + "-byte key", decoded);
|
|
||||||
assertEquals("token", decoded.getAuthType());
|
|
||||||
assertEquals("synthetic-认证", decoded.getToken());
|
|
||||||
|
|
||||||
String encoded = AuthParamCodec.encode(decoded, key);
|
|
||||||
assertNotNull(encoded);
|
|
||||||
Cipher peer = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
|
||||||
peer.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
|
|
||||||
String base64 = URLDecoder.decode(encoded, StandardCharsets.UTF_8);
|
|
||||||
JsonObject plaintext = new JsonObject(new String(peer.doFinal(Base64.getDecoder().decode(base64)), StandardCharsets.UTF_8));
|
|
||||||
assertEquals("synthetic-认证", plaintext.getString("token"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void donatedAccountsRequireExplicitOptInAndDatabase() {
|
|
||||||
JsonObject server = new JsonObject().put("enableDatabase", true);
|
|
||||||
assertFalse(ParserAuthUtil.isDonatedAccountsEnabled(server));
|
|
||||||
assertTrue(ParserAuthUtil.isDonatedAccountsEnabled(server.put("enableDonatedAccounts", true)));
|
|
||||||
assertFalse(ParserAuthUtil.isDonatedAccountsEnabled(server.put("enableDatabase", false)));
|
|
||||||
assertTrue(ParserAuthUtil.supportsServerSideDonation("YE"));
|
|
||||||
assertFalse(ParserAuthUtil.supportsServerSideDonation("QK"));
|
|
||||||
assertFalse(ParserAuthUtil.supportsServerSideDonation("UC"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testAuthParamModel() {
|
public void testAuthParamModel() {
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import java.util.Base64;
|
|||||||
*/
|
*/
|
||||||
public class AuthParamCodecTestMain {
|
public class AuthParamCodecTestMain {
|
||||||
|
|
||||||
private static final String TEST_KEY = "dummy-test-key16";
|
private static final String TEST_KEY = "nfd_auth_key2026";
|
||||||
private static int passCount = 0;
|
private static int passCount = 0;
|
||||||
private static int failCount = 0;
|
private static int failCount = 0;
|
||||||
|
|
||||||
|
|||||||
@@ -1,42 +0,0 @@
|
|||||||
package cn.qaiu.lz.common.util;
|
|
||||||
|
|
||||||
import io.vertx.core.MultiMap;
|
|
||||||
import io.vertx.core.http.HttpServerRequest;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.lang.reflect.Proxy;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
/** 分页参数不能被当作截断的分享链接参数拼回 url,否则会改变分享链接与解析结果。 */
|
|
||||||
public class URLParamUtilPagingTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void pagingParamsAreNotAppendedToShareUrl() {
|
|
||||||
MultiMap params = MultiMap.caseInsensitiveMultiMap()
|
|
||||||
.add("url", "https://pan.lanzoui.com/b66477")
|
|
||||||
.add("pwd", "1234")
|
|
||||||
.add("page", "2")
|
|
||||||
.add("pg", "2")
|
|
||||||
.add("pageCursor", "eyJ2IjoxfQ");
|
|
||||||
assertEquals("https://pan.lanzoui.com/b66477", URLParamUtil.parserParams(request(params)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void truncatedShareParamsStillAppended() {
|
|
||||||
MultiMap params = MultiMap.caseInsensitiveMultiMap()
|
|
||||||
.add("url", "https://moteam.lanzoum.com/b00yaejvte?a=1")
|
|
||||||
.add("webpage", "x")
|
|
||||||
.add("page", "3");
|
|
||||||
assertEquals("https://moteam.lanzoum.com/b00yaejvte?a=1&webpage=x", URLParamUtil.parserParams(request(params)));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static HttpServerRequest request(MultiMap params) {
|
|
||||||
return (HttpServerRequest) Proxy.newProxyInstance(HttpServerRequest.class.getClassLoader(),
|
|
||||||
new Class<?>[]{HttpServerRequest.class}, (proxy, method, args) -> switch (method.getName()) {
|
|
||||||
case "params" -> params;
|
|
||||||
case "absoluteURI" -> "http://localhost/v2/getFileListPage";
|
|
||||||
default -> throw new UnsupportedOperationException(method.getName());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
package cn.qaiu.lz.web.model;
|
|
||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
|
||||||
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.assertNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
public class FileListPageRespTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void unpagedProviderReturnsWholeListAsLastPage() {
|
|
||||||
List<FileInfo> list = List.of(new FileInfo().setFileName("a"));
|
|
||||||
FileListPageResp resp = FileListPageResp.of(list, 1, null);
|
|
||||||
assertFalse(resp.isPaged());
|
|
||||||
assertFalse(resp.isHasMore());
|
|
||||||
assertEquals(1, resp.getList().size());
|
|
||||||
assertNull(resp.getNextCursor());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void unpagedProviderBeyondFirstPageIsEmpty() {
|
|
||||||
FileListPageResp resp = FileListPageResp.beyondUnpaged(2);
|
|
||||||
assertTrue(resp.getList().isEmpty());
|
|
||||||
assertFalse(resp.isHasMore());
|
|
||||||
assertEquals(2, resp.getPage());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void pagedInfoIsCopied() {
|
|
||||||
JsonObject info = new JsonObject().put("paged", true).put("page", 2).put("pageSize", 50)
|
|
||||||
.put("hasMore", true).put("nextPage", 3).put("nextCursor", "c").putNull("total");
|
|
||||||
FileListPageResp resp = FileListPageResp.of(List.of(), 2, info);
|
|
||||||
assertTrue(resp.isPaged());
|
|
||||||
assertTrue(resp.isHasMore());
|
|
||||||
assertEquals(Integer.valueOf(3), resp.getNextPage());
|
|
||||||
assertEquals("c", resp.getNextCursor());
|
|
||||||
assertNull(resp.getTotal());
|
|
||||||
assertTrue(FileListPageResp.isPagedType("lz"));
|
|
||||||
assertFalse(FileListPageResp.isPagedType("qk"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -214,7 +214,7 @@
|
|||||||
|
|
||||||
<div class="info-box">
|
<div class="info-box">
|
||||||
<p><strong>加密算法:</strong> AES/ECB/PKCS5Padding</p>
|
<p><strong>加密算法:</strong> AES/ECB/PKCS5Padding</p>
|
||||||
<p><strong>密钥:</strong> 自建服务配置的认证密钥(仅在可信本地环境使用)</p>
|
<p><strong>默认密钥:</strong> nfd_auth_key2026 (16位)</p>
|
||||||
<p><strong>编码流程:</strong> JSON对象 → AES加密 → Base64编码 → URL编码</p>
|
<p><strong>编码流程:</strong> JSON对象 → AES加密 → Base64编码 → URL编码</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -268,8 +268,8 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="encryptKey">加密密钥(必填)</label>
|
<label for="encryptKey">加密密钥 (可选,默认: nfd_auth_key2026)</label>
|
||||||
<input type="password" id="encryptKey" autocomplete="off" placeholder="本地服务配置的密钥">
|
<input type="text" id="encryptKey" placeholder="留空使用默认密钥" value="nfd_auth_key2026">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="button-group">
|
<div class="button-group">
|
||||||
@@ -368,10 +368,7 @@
|
|||||||
|
|
||||||
// AES 加密
|
// AES 加密
|
||||||
try {
|
try {
|
||||||
const encryptKey = document.getElementById('encryptKey').value;
|
const encryptKey = document.getElementById('encryptKey').value.trim() || 'nfd_auth_key2026';
|
||||||
if (![16, 24, 32].includes(new TextEncoder().encode(encryptKey).length)) {
|
|
||||||
throw new Error('密钥必须为 16、24 或 32 个 UTF-8 字节');
|
|
||||||
}
|
|
||||||
const encrypted = encryptAuthParam(JSON.stringify(authParam), encryptKey);
|
const encrypted = encryptAuthParam(JSON.stringify(authParam), encryptKey);
|
||||||
|
|
||||||
document.getElementById('encryptedResult').textContent = encrypted;
|
document.getElementById('encryptedResult').textContent = encrypted;
|
||||||
@@ -392,6 +389,11 @@
|
|||||||
|
|
||||||
// AES 加密函数
|
// AES 加密函数
|
||||||
function encryptAuthParam(jsonString, key) {
|
function encryptAuthParam(jsonString, key) {
|
||||||
|
// 确保密钥是16位
|
||||||
|
if (key.length !== 16) {
|
||||||
|
throw new Error('密钥必须是16位字符');
|
||||||
|
}
|
||||||
|
|
||||||
// AES 加密 (ECB 模式, PKCS5Padding)
|
// AES 加密 (ECB 模式, PKCS5Padding)
|
||||||
const encrypted = CryptoJS.AES.encrypt(
|
const encrypted = CryptoJS.AES.encrypt(
|
||||||
jsonString,
|
jsonString,
|
||||||
|
|||||||
Reference in new issue
Block a user