Compare commits

..
Author SHA1 Message Date
Cursor Agentandqaiu 551078b279 fix(ys): report invalid password instead of a bare HTTP 400
VerifyPassword answers a wrong password with HTTP 400 and
code invalid_password. Surface that short message and drop any
token-like text from the failure body.

Co-authored-by: qaiu <[email protected]>
2026-11-24 07:38:07 +00:00
Cursor Agentandqaiu 31bc383741 fix(ys): parse the new password gate and follow ys168 redirects
Yongshuo password spaces now use an entry page with data-verification-token.
Password verification still posts to /?handler=VerifyPassword, but after a
ys168.com 302 the request must go to the final ysepan.com host. The legacy
RequestVerificationToken script form remains accepted.

Co-authored-by: qaiu <[email protected]>
2026-11-24 03:52:41 +00:00
44 changed files with 732 additions and 5262 deletions

No files matched your search

-8
View File
@@ -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: 先看最新版本和更新说明,再反馈旧版本里已经修过的问题
-40
View File
@@ -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
-157
View File
@@ -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.12。
placeholder: "0.4.12"
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
-84
View File
@@ -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.12。不确定就写获取方式。
placeholder: "0.4.12"
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
-25
View File
@@ -1,25 +0,0 @@
## 更新内容
目录列表支持分页了。之前蓝奏云目录只返回前 50 个文件,小飞机盘和蓝奏云优享只返回前 60 个。早先的分页需求见 https://github.com/qaiu/netdisk-fast-download/issues/112 。
- 目录分页(#308):
- 蓝奏云:按页读取 `filemoreajax`,每页 50 个。只有 `zt=2`(翻过最后一页)或不足 50 个的页才算结束。`zt=4`「请刷新,重试0」视为限流,同一页等 2 秒、再等 5 秒重试;仍失败就返回可重试的错误,不当作最后一页。每页返回 `nextCursor`,下一页沿用同一组翻页参数。不带游标时最多直接请求到第 6 页。
- 小飞机盘、蓝奏云优享:`offset` 作为页码,每页 60 个,由 `totalPage` / `total` 判断是否还有下一页。
- 新接口 `/v2/getFileListPage` 返回 `list`、`hasMore`、`nextPage`、`nextCursor`、`total`、`totalPage`。`/v2/getFileList` 也接受 `page`(或 `pg`)和 `pageCursor`。不带页码时返回结构和以前一样。不支持分页的网盘请求第 2 页及以后时返回空页。
- 前端:目录面板和树形视图有「加载更多」,滚动到底也会自动加载下一页。已加载的文件会保留,加载失败时显示错误并停止自动加载,点击可重试。`list.html` 同样支持。
- 蓝奏云目录风控页(#307):目录分享页改用移动端 UA 请求,文件页仍用桌面 UA。如果仍返回空白风控页,提示「访问风控,不能据此判断分享已失效」,不再报成分享已失效。
- 新增 Issue 表单:解析失败、运行问题、功能建议(#305)。
## 实测范围
- 蓝奏云 `pan.lanzoui.com/b66477`:连续翻完 93 页,共 4598 个文件,没有重复,最后一页 9 个且 `hasMore=false`。实测遇到 `zt=4` 时,2 秒后重试成功。第 2 页的文件可以下载。
- 蓝奏云带密码目录 `moteam.lanzoum.com/b00yaejvte`(密码 `1234`):第 1 页 7 个且没有下一页,第 2 页为空。不带页码的旧接口仍返回 7 个。
- 蓝奏云优享:用真实小目录、把每页条数临时设为 1 来验证。`offset` 是从 1 开始的页码,`total` / `totalPage` 正确,翻过最后一页为空。
- 夸克、城通:目录列表和以前一样,请求第 2 页返回空页。
## 限制
- 小飞机盘没有可用的真实目录样本,只做了本地模拟测试(与蓝奏云优享是同一套接口)。
- 蓝奏云优享没有实测超过 60 个文件的大目录。
- 蓝奏云不带游标直接请求第 7 页及以后会提示需要游标,请按 `nextCursor` 顺序翻页。
- 风控页提示只能说明这次请求被拦截,不代表分享一定有效。
+1 -3
View File
@@ -9,9 +9,8 @@ on:
push:
tags:
- 'v*'
# '*' 不匹配含 / 的分支名(如 cursor/xxx),会让功能分支推送也发布 :latest 镜像
branches-ignore:
- '**'
- '*'
paths-ignore:
- 'bin/**'
- '.github/**'
@@ -303,6 +302,5 @@ jobs:
netdisk-fast-download-linux-amd64.zip
netdisk-fast-download-windows-amd64.zip
tag_name: ${{ github.ref_name }}
body_path: .github/release-notes.md
generate_release_notes: true
fail_on_unmatched_files: true
+2 -7
View File
@@ -64,7 +64,7 @@ wget -O v01 "https://lz.qaiu.top/parser?url=https%3A%2F%2Fwww.ecpan.cn%2Fweb%2F%
**注意⚠️小飞机解析有IP限制,多数云服务商的大陆IP会被拦截(可以自行配置代理),和本程序无关**
**注意⚠️收到很多用户反馈,小飞机近期封号频繁,请尽可能选择其他网盘分享**
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提 issues,请先检查分享是否有效。**反馈时使用 [问题模板](https://github.com/qaiu/netdisk-fast-download/issues/new/choose),只提供可公开的测试分享,不要粘贴 Cookie、令牌或账号密码。
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提issues,请先检查分享是否有效。**
## 网盘支持情况:
> 20230824 123云盘解析大文件(>100MB)失效,需要登录
@@ -470,7 +470,7 @@ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtow
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
```shell
cd ~
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.12/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
cd netdisk-fast-download
bash service-install.sh
@@ -546,11 +546,6 @@ auths:
username: 你的用户名
password: 你的密码
# authorization: 浏览器登录后的 authorToken / sso-token
# 城通免密和带密码分享都先匿名解析。仅当仍被 Turnstile 拦住时才需要登录令牌。
# 登录 https://pan.ctfile.com 后,从 Session Storage 复制 refresh_token。
# ct:
# refresh_token: 登录后的 refresh_token
# token: 可选,当前 access token
```
@@ -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;
}
}
@@ -1,264 +0,0 @@
package cn.qaiu.parser.impl;
import io.vertx.core.json.JsonObject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* ALTCHA v2(PBKDF2/SHA-256)挑战解算。
* <p>
* 口令是 nonce 的原始字节再拼上大端 uint32 计数器,盐是 salt 的原始字节。
* 找到派生密钥以 keyPrefix 开头的计数器后,按官方 widget 的方式拼出
* {@code base64({"challenge":{parameters,signature},"solution":{counter,derivedKey,time}})}。
* 计算是 CPU 密集的,调用方必须放在 Vert.x worker 上,不能占用 event loop。
*/
final class AltchaV2Solver {
static final int DEFAULT_MAX_COUNTER = 200_000;
static final long DEFAULT_TIMEOUT_MILLIS = 25_000L;
/** 城通当前 cost=1200。更高的 cost 会把解析线程占满,直接拒绝。 */
static final int MAX_COST = 20_000;
static final int MAX_KEY_LENGTH = 64;
private static final int MAX_THREADS = 4;
private AltchaV2Solver() {
}
static final class Solution {
final int counter;
final String derivedKeyHex;
final long tookMillis;
Solution(int counter, String derivedKeyHex, long tookMillis) {
this.counter = counter;
this.derivedKeyHex = derivedKeyHex;
this.tookMillis = tookMillis;
}
}
static Solution solve(JsonObject challenge) {
return solve(challenge, DEFAULT_MAX_COUNTER, DEFAULT_TIMEOUT_MILLIS);
}
static Solution solve(JsonObject challenge, int maxCounter, long timeoutMillis) {
if (challenge == null || challenge.getJsonObject("parameters") == null) {
throw new IllegalArgumentException("ALTCHA 挑战为空");
}
JsonObject parameters = challenge.getJsonObject("parameters");
String algorithm = parameters.getString("algorithm", "");
if (!"PBKDF2/SHA-256".equals(algorithm)) {
throw new IllegalArgumentException("不支持的 ALTCHA 算法: " + algorithm);
}
int cost = intValue(parameters.getValue("cost"), -1);
int keyLength = intValue(parameters.getValue("keyLength"), 32);
if (cost < 1 || cost > MAX_COST) {
throw new IllegalArgumentException("ALTCHA cost 超出可解范围: " + cost);
}
if (keyLength < 16 || keyLength > MAX_KEY_LENGTH) {
throw new IllegalArgumentException("ALTCHA keyLength 超出可解范围: " + keyLength);
}
byte[] nonce = decodeHex(parameters.getString("nonce", ""), "nonce");
byte[] salt = decodeHex(parameters.getString("salt", ""), "salt");
byte[] prefix = decodeHex(parameters.getString("keyPrefix", ""), "keyPrefix");
if (prefix.length == 0 || prefix.length > keyLength) {
throw new IllegalArgumentException("ALTCHA keyPrefix 长度无效");
}
int limit = Math.max(1, maxCounter);
long budget = Math.max(1L, timeoutMillis);
int threads = Math.min(MAX_THREADS, Math.max(1, Runtime.getRuntime().availableProcessors()));
threads = Math.min(threads, limit);
AtomicInteger winner = new AtomicInteger(-1);
AtomicBoolean stop = new AtomicBoolean(false);
String[] derivedHex = new String[1];
long started = System.nanoTime();
long deadline = started + TimeUnit.MILLISECONDS.toNanos(budget);
ExecutorService pool = Executors.newFixedThreadPool(threads, runnable -> {
Thread thread = new Thread(runnable, "ctfile-altcha");
thread.setDaemon(true);
return thread;
});
try {
Future<?>[] tasks = new Future<?>[threads];
for (int i = 0; i < threads; i++) {
int start = i;
int stride = threads;
tasks[i] = pool.submit((Callable<Void>) () -> {
search(start, stride, limit, deadline, nonce, salt, prefix, cost, keyLength, winner, stop, derivedHex);
return null;
});
}
for (Future<?> task : tasks) {
task.get(budget + 2000L, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
stop.set(true);
throw new IllegalStateException("ALTCHA 解算被中断");
} catch (IllegalStateException e) {
stop.set(true);
throw e;
} catch (Exception e) {
stop.set(true);
throw new IllegalStateException("ALTCHA 解算失败: " + e.getMessage());
} finally {
stop.set(true);
pool.shutdownNow();
}
int counter = winner.get();
if (counter < 0 || derivedHex[0] == null) {
throw new IllegalStateException("ALTCHA 人机验证解算超时,请稍后重试");
}
long took = Math.max(1L, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
return new Solution(counter, derivedHex[0], took);
}
/**
* 官方 altcha widget 成功后提交的 payload:标准 Base64(含填充),不是 URL-safe。
*/
static String payload(JsonObject challenge, Solution solution) {
JsonObject body = new JsonObject()
.put("challenge", new JsonObject()
.put("parameters", challenge.getJsonObject("parameters"))
.put("signature", challenge.getString("signature")))
.put("solution", new JsonObject()
.put("counter", solution.counter)
.put("derivedKey", solution.derivedKeyHex)
.put("time", solution.tookMillis));
return Base64.getEncoder().encodeToString(body.encode().getBytes(StandardCharsets.UTF_8));
}
/**
* PBKDF2-HMAC-SHA256,口令是原始字节。
* JDK 的 {@code SecretKeyFactory("PBKDF2WithHmacSHA256")} 会把 char[] 口令按 UTF-8 编码,
* nonce 里大于 0x7F 的字节会被展开,和 ALTCHA / WebCrypto 的原始字节口令对不上。
*/
static byte[] pbkdf2(byte[] password, byte[] salt, int cost, int keyLength) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(password, "HmacSHA256"));
return pbkdf2(mac, salt, cost, keyLength);
} catch (Exception e) {
throw new IllegalStateException("PBKDF2 计算失败: " + e.getMessage());
}
}
private static void search(int start, int stride, int limit, long deadline, byte[] nonce, byte[] salt,
byte[] prefix, int cost, int keyLength, AtomicInteger winner, AtomicBoolean stop,
String[] derivedHex) {
Mac mac;
try {
mac = Mac.getInstance("HmacSHA256");
} catch (Exception e) {
throw new IllegalStateException("PBKDF2 初始化失败: " + e.getMessage());
}
for (int counter = start; counter < limit && winner.get() < 0 && !stop.get(); counter += stride) {
if ((counter & 31) == start && System.nanoTime() > deadline) {
return;
}
byte[] derived;
try {
mac.init(new SecretKeySpec(password(nonce, counter), "HmacSHA256"));
derived = pbkdf2(mac, salt, cost, keyLength);
} catch (Exception e) {
throw new IllegalStateException("PBKDF2 计算失败: " + e.getMessage());
}
if (startsWith(derived, prefix) && winner.compareAndSet(-1, counter)) {
derivedHex[0] = toHex(derived);
return;
}
}
}
private static byte[] pbkdf2(Mac mac, byte[] salt, int iterations, int keyLength) throws Exception {
int hashLength = mac.getMacLength();
byte[] result = new byte[keyLength];
byte[] block = new byte[salt.length + 4];
System.arraycopy(salt, 0, block, 0, salt.length);
int offset = 0;
for (int index = 1; offset < keyLength; index++) {
block[salt.length] = (byte) (index >>> 24);
block[salt.length + 1] = (byte) (index >>> 16);
block[salt.length + 2] = (byte) (index >>> 8);
block[salt.length + 3] = (byte) index;
byte[] mixed = mac.doFinal(block);
byte[] digest = mixed.clone();
for (int round = 1; round < iterations; round++) {
mixed = mac.doFinal(mixed);
for (int i = 0; i < mixed.length; i++) {
digest[i] ^= mixed[i];
}
}
int length = Math.min(hashLength, keyLength - offset);
System.arraycopy(digest, 0, result, offset, length);
offset += length;
}
return result;
}
private static byte[] password(byte[] nonce, int counter) {
byte[] password = Arrays.copyOf(nonce, nonce.length + 4);
password[nonce.length] = (byte) (counter >>> 24);
password[nonce.length + 1] = (byte) (counter >>> 16);
password[nonce.length + 2] = (byte) (counter >>> 8);
password[nonce.length + 3] = (byte) counter;
return password;
}
private static boolean startsWith(byte[] value, byte[] prefix) {
if (prefix.length > value.length) {
return false;
}
for (int i = 0; i < prefix.length; i++) {
if (value[i] != prefix[i]) {
return false;
}
}
return true;
}
static byte[] decodeHex(String hex, String name) {
if (hex == null || hex.length() % 2 != 0 || !hex.matches("[0-9a-fA-F]*")) {
throw new IllegalArgumentException("ALTCHA " + name + " 不是合法十六进制");
}
byte[] out = new byte[hex.length() / 2];
for (int i = 0; i < out.length; i++) {
out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return out;
}
static String toHex(byte[] bytes) {
StringBuilder builder = new StringBuilder(bytes.length * 2);
for (byte value : bytes) {
builder.append(Character.forDigit((value >> 4) & 0xF, 16));
builder.append(Character.forDigit(value & 0xF, 16));
}
return builder.toString();
}
private static int intValue(Object value, int fallback) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value == null) {
return fallback;
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return fallback;
}
}
}
@@ -1,112 +1,345 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.PanBase;
import cn.qaiu.parser.impl.CtfileSession.CtfileException;
import cn.qaiu.parser.impl.CtfileSession.DirectLink;
import cn.qaiu.parser.impl.CtfileSession.ShareTarget;
import cn.qaiu.parser.impl.CtfileSession.VerificationMismatch;
import cn.qaiu.util.CommonUtils;
import cn.qaiu.util.FileSizeConverter;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.WorkerExecutor;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.uritemplate.UriTemplate;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 城通网盘。免密和带访问密码的分享都先走匿名网页接口和 ALTCHA v2。
* 官方客户端 {@code /v4} 只在匿名结果仍是 Turnstile、且调用方自己配置了登录令牌时回退。
* <a href="https://www.ctfile.com">诚通网盘</a>
*/
public class CtTool extends PanBase {
private static final String API_URL_PREFIX = "https://webapi.ctfile.com";
private static final String SHARE_FILE_URL_PREFIX = "https://ctfile.com/file/";
private static final int DEFAULT_MAX_LIST_PAGES = 50;
private static final String AJAX_ACCEPT = "application/json, text/javascript, */*; q=0.01";
private static final String BROWSER_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
private static final int FILE_LIST_PAGE_SIZE = 200;
private static final int MAX_FILE_LIST_PAGES = 50;
private static final Object WORKER_LOCK = new Object();
private static volatile WorkerExecutor sharedWorker;
private static volatile boolean workerShutdown;
// https://webapi.ctfile.com/getfile.php?path=f&f=64115194-17569800420720-06c697&
// passcode=7609&r=0.6611183001986635&ref=&url=https%3A%2F%2Furl94.ctfile.com%2Ff%2F64115194-17569800420720-06c697%3Fp%3D7609
private static final String API1 = API_URL_PREFIX + "/getfile.php?path={path}" +
"&f={shareKey}&passcode={pwd}&r={rand}&ref=&url={url}";
// https://webapi.ctfile.com/get_down_url.php?uid=64115194&fid=17569800420720&
// file_chk=af5c8757a49cbc69a557eb3da59b246c&start_time=1780471868&wait_seconds=0&rd=0.36...
private static final String API2 = API_URL_PREFIX + "/get_down_url.php?" +
"uid={uid}&fid={fid}&file_chk={file_chk}" +
"&start_time={start_time}&wait_seconds={wait_seconds}&rd={rand}";
// https://webapi.ctfile.com/getdir.php?path=d&d=64115194-164803691-48508c&
// folder_id=164803691&fk=decb36&passcode=7609&r=0.23...&ref=&url=https://url94.ctfile.com/d/...
private static final String API_GETDIR = API_URL_PREFIX + "/getdir.php?path={path}" +
"&d={shareKey}&folder_id={folder_id}&fk={fk}&passcode={pwd}&r={rand}&ref=&url={url}";
// DataTables参数,用于获取目录文件列表
private static final String FILE_LIST_PARAMS_TEMPLATE = "&sEcho=1&iColumns=4&sColumns=%2C%2C%2C" +
"&iDisplayStart={start}&iDisplayLength={length}" +
"&mDataProp_0=0&sSearch_0=&bRegex_0=false&bSearchable_0=true&bSortable_0=false" +
"&mDataProp_1=1&sSearch_1=&bRegex_1=false&bSearchable_1=true&bSortable_1=true" +
"&mDataProp_2=2&sSearch_2=&bRegex_2=false&bSearchable_2=true&bSortable_2=true" +
"&mDataProp_3=3&sSearch_3=&bRegex_3=false&bSearchable_3=true&bSortable_3=true" +
"&sSearch=&bRegex=false" +
"&iSortCol_0=3&sSortDir_0=desc&iSortingCols=1";
// 文件列表HTML解析正则
private static final Pattern FILE_ID_PATTERN = Pattern.compile("value=[\"']f(\\d+)[\"']");
private static final Pattern FOLDER_ID_PATTERN = Pattern.compile("value=[\"']d(\\d+)[\"']");
private static final Pattern FILE_HREF_PATTERN = Pattern.compile("href=[\"']#/f/([^\"']+)[\"']");
private static final Pattern FILE_NAME_PATTERN = Pattern.compile("<a\\b[^>]*>([^<]+)</a>", Pattern.CASE_INSENSITIVE);
private static final Pattern FILE_ICON_PATTERN = Pattern.compile("alt=[\"']([^\"']+)[\"']");
private static final Pattern SUBDIR_PATTERN = Pattern.compile("load_subdir\\s*\\((\\d+)\\s*,\\s*['\"]([^'\"]+)['\"]\\)");
/**
* 子类重写此构造方法不需要添加额外逻辑
* 如:
* <blockquote><pre>
* public XxTool(String key, String pwd) {
* super(key, pwd);
* }
* </pre></blockquote>
*
* @param shareLinkInfo 分享链接信息
*/
public CtTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
}
public static void shutdownWorkerExecutor() {
synchronized (WORKER_LOCK) {
workerShutdown = true;
if (sharedWorker != null) {
sharedWorker.close();
sharedWorker = null;
}
}
}
@Override
public Future<String> parse() {
String shareKey = shareLinkInfo.getShareKey();
if (shareKey == null || shareKey.isBlank()) {
fail("shareKey为空");
final String shareKey = shareLinkInfo.getShareKey();
if (shareKey == null || shareKey.indexOf('-') == -1) {
fail("shareKey格式不正确找不到'-': {}", shareKey);
return promise.future();
}
try {
worker().executeBlocking(() -> {
ParsedDownload link = resolveDownload(shareKey);
shareLinkInfo.getOtherParam().put("fileInfo", fileInfoFrom(link.file));
if (link.fileDir != null && !link.fileDir.isBlank()) {
shareLinkInfo.getOtherParam().put("ctFileDir", link.fileDir);
}
return link;
}, false).onSuccess(link -> {
if (link.headers == null || link.headers.isEmpty()) {
complete(link.url);
} else {
completeWithMeta(link.url, link.headers);
}
}).onFailure(error -> fail("{}", rootMessage(error)));
} catch (RuntimeException e) {
fail("{}", e.getMessage());
String[] split = shareKey.split("-");
if (split.length < 2 || split[0].isBlank() || split[1].isBlank()) {
fail("shareKey格式不正确: {}", shareKey);
return promise.future();
}
String fallbackUid = split[0], fallbackFid = split[1];
String path = extractPath(shareLinkInfo.getShareUrl());
HttpRequest<Buffer> bufferHttpRequest1 = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API1))
.setTemplateParam("path", path)
.setTemplateParam("shareKey", shareKey)
.setTemplateParam("pwd", shareLinkInfo.getSharePassword())
.setTemplateParam("rand", String.valueOf(Math.random()))
.setTemplateParam("url", shareLinkInfo.getShareUrl()), shareLinkInfo.getShareUrl());
bufferHttpRequest1
.send().onSuccess(res -> {
try {
var resJson = asJson(res);
if (resJson == null || resJson.isEmpty()) {
fail("解析失败, 上游返回空响应或非JSON响应");
return;
}
Object fileValue = resJson.getValue("file");
if (!(fileValue instanceof JsonObject)) {
fail("解析失败, 文件信息为空或格式错误, 可能分享已失效: {}", resJson);
return;
}
var fileJson = (JsonObject) fileValue;
String uid = resolveDownloadUid(fileJson, fallbackUid);
String fid = resolveDownloadFid(fileJson, fallbackFid);
String fileChk = fileJson.getString("file_chk");
String startTime = valueToString(fileJson.getValue("start_time"));
String waitSeconds = valueToString(fileJson.getValue("wait_seconds"));
if (uid.isBlank() || fid.isBlank() || fileChk == null || fileChk.isBlank()
|| startTime.isBlank() || waitSeconds.isBlank()) {
fail("解析失败, 下载参数不完整, 可能分享已失效或者分享密码不对: {}", fileJson);
return;
}
// 提取文件信息并存储
FileInfo fileInfo = new FileInfo()
.setFileName(fileJson.getString("file_name"))
.setFileId(fid)
.setSizeStr(fileJson.getString("file_size"))
.setCreateTime(fileJson.getString("file_time"))
.setCreateBy(fileJson.getString("username"))
.setFileType("file")
.setPanType(shareLinkInfo.getType());
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
HttpRequest<Buffer> bufferHttpRequest2 = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API2))
.setTemplateParam("uid", uid)
.setTemplateParam("fid", fid)
.setTemplateParam("file_chk", fileChk)
.setTemplateParam("start_time", startTime)
.setTemplateParam("wait_seconds", waitSeconds)
.setTemplateParam("rand", String.valueOf(Math.random())), shareLinkInfo.getShareUrl());
bufferHttpRequest2
.send().onSuccess(res2 -> handleDownloadUrlResponse(res2))
.onFailure(t -> fail("下载链接请求失败: {}", t.getMessage()));
} catch (Exception e) {
fail("解析失败: {}", e.getMessage());
}
}).onFailure(t -> fail("文件信息请求失败: {}", t.getMessage()));
return promise.future();
}
private void handleDownloadUrlResponse(io.vertx.ext.web.client.HttpResponse<Buffer> res) {
try {
JsonObject resJson = asJson(res);
if (resJson == null || resJson.isEmpty()) {
fail("解析失败, 下载接口返回空响应或非JSON响应");
return;
}
String downloadUrl = resJson.getString("downurl");
if (downloadUrl == null || downloadUrl.isBlank()) {
fail("解析失败, 可能分享已失效: json: {} 字段 {} 不存在", resJson, "downurl");
return;
}
// 存储下载元数据,包括必要的请求头
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", BROWSER_UA);
if (shareLinkInfo.getShareUrl() != null && !shareLinkInfo.getShareUrl().isBlank()) {
headers.put("Referer", shareLinkInfo.getShareUrl());
}
// 使用新的 completeWithMeta 方法
completeWithMeta(downloadUrl, headers);
} catch (Exception e) {
fail("解析失败, 下载接口响应处理异常: {}", e.getMessage());
}
}
@Override
public Future<List<FileInfo>> parseFileList() {
Promise<List<FileInfo>> listPromise = Promise.promise();
String shareKey = shareLinkInfo.getShareKey();
if (shareKey == null || shareKey.isBlank()) {
listPromise.fail(baseMsg() + " - 解析异常: shareKey为空");
final String shareKey = shareLinkInfo.getShareKey();
final String shareUrl = shareLinkInfo.getShareUrl();
final String pwd = shareLinkInfo.getSharePassword();
// shareKey格式: uid-folder_id-hash (例如 64115194-164803691-48508c)
if (shareKey == null) {
listPromise.fail(baseMsg() + " shareKey为空");
return listPromise.future();
}
try {
worker().executeBlocking(() -> listDirectory(shareKey), false)
.onSuccess(listPromise::complete)
.onFailure(error -> {
if (!listPromise.future().isComplete()) {
listPromise.fail(baseMsg() + " - 解析异常: " + rootMessage(error));
}
});
} catch (RuntimeException e) {
listPromise.fail(baseMsg() + " - 解析异常: " + e.getMessage());
String[] split = shareKey.split("-");
if (split.length < 2) {
listPromise.fail(baseMsg() + " shareKey格式不正确: " + shareKey);
return listPromise.future();
}
String path = extractPath(shareUrl);
Object dirId = shareLinkInfo.getOtherParam() == null ? null : shareLinkInfo.getOtherParam().get("dirId");
DirectoryContext directoryContext = resolveDirectoryContext(shareUrl, dirId);
HttpRequest<Buffer> getDirRequest = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API_GETDIR))
.setTemplateParam("path", path)
.setTemplateParam("shareKey", shareKey)
.setTemplateParam("folder_id", directoryContext.folderId)
.setTemplateParam("fk", directoryContext.folderKey)
.setTemplateParam("pwd", pwd != null ? pwd : "")
.setTemplateParam("rand", String.valueOf(Math.random()))
.setTemplateParam("url", shareUrl), shareUrl);
getDirRequest.send().onSuccess(res -> {
try {
var resJson = asJson(res);
if (resJson == null || resJson.isEmpty()) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: 上游返回空响应或非JSON响应");
return;
}
if (!resJson.containsKey("file")) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: " + resJson.encode());
return;
}
Object dirInfoValue = resJson.getValue("file");
if (!(dirInfoValue instanceof JsonObject)) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: file字段格式错误: " + resJson.encode());
return;
}
JsonObject dirInfo = (JsonObject) dirInfoValue;
Object fileListUrlValue = dirInfo.getValue("url");
String fileListRelUrl = fileListUrlValue instanceof String ? ((String) fileListUrlValue).trim() : "";
if (fileListRelUrl.isBlank()) {
failListPromise(listPromise, baseMsg() + " " + buildDirectoryFailureMessage(resJson, dirInfo));
return;
}
fetchFileListPage(toCtApiUrl(fileListRelUrl), 0, 0, new ArrayList<>(), listPromise,
shareLinkInfo.getType(), getDomainName(), shareUrl, pwd);
} catch (Exception e) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: " + e.getMessage());
}
}).onFailure(t -> failListPromise(listPromise, t));
return listPromise.future();
}
private void fetchFileListPage(String fileListBaseUrl, int start, int pageIndex, List<FileInfo> fileList,
Promise<List<FileInfo>> listPromise, String panType, String domainName,
String shareUrl, String pwd) {
try {
if (pageIndex >= MAX_FILE_LIST_PAGES) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 分页超过最大限制 " + MAX_FILE_LIST_PAGES
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
return;
}
String fileListUrl = appendQueryParams(fileListBaseUrl,
buildFileListParams(start, FILE_LIST_PAGE_SIZE) + "&_=" + System.currentTimeMillis());
withCtAjaxHeaders(clientSession.getAbs(fileListUrl), shareUrl)
.send()
.onSuccess(res -> handleFileListPageResponse(fileListBaseUrl, start, pageIndex, fileList,
listPromise, panType, domainName, shareUrl, pwd, res))
.onFailure(t -> failListPromise(listPromise, t));
} catch (Exception e) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: " + e.getMessage()
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
}
}
private void handleFileListPageResponse(String fileListBaseUrl, int start, int pageIndex, List<FileInfo> fileList,
Promise<List<FileInfo>> listPromise, String panType, String domainName,
String shareUrl, String pwd, io.vertx.ext.web.client.HttpResponse<Buffer> res) {
try {
var listJson = asJson(res);
if (listJson == null || listJson.isEmpty()) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 上游返回空响应或非JSON响应"
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
return;
}
Object aaDataValue = listJson.getValue("aaData");
if (!(aaDataValue instanceof JsonArray)) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: aaData为空: " + listJson.encode());
return;
}
JsonArray aaData = (JsonArray) aaDataValue;
for (int i = 0; i < aaData.size(); i++) {
try {
Object rowValue = aaData.getValue(i);
if (!(rowValue instanceof JsonArray)) {
log.warn("城通文件列表行格式错误: {}", rowValue);
continue;
}
FileInfo fileInfo = parseFileListRow((JsonArray) rowValue, panType,
domainName, shareUrl, pwd);
if (fileInfo != null) {
fileList.add(fileInfo);
}
} catch (Exception e) {
log.warn("解析文件行失败: {}", e.getMessage());
}
}
int nextStart = start + aaData.size();
int total = parseFileListTotal(listJson);
if (isUnexpectedEmptyFileListPage(start, aaData.size(), total)) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 上游返回空分页"
+ " (start=" + start + ", total=" + total + ")");
return;
}
if (shouldFetchNextFileListPage(start, aaData.size(), total)) {
fetchFileListPage(fileListBaseUrl, nextStart, pageIndex + 1, fileList,
listPromise, panType, domainName, shareUrl, pwd);
} else {
completeListPromise(listPromise, fileList);
}
} catch (Exception e) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: " + e.getMessage()
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
}
}
@Override
public Future<String> parseById() {
Object paramValue = shareLinkInfo.getOtherParam().get("paramJson");
if (!(paramValue instanceof JsonObject)) {
fail("缺少下载参数paramJson");
return promise.future();
Promise<String> parsePromise = Promise.promise();
parsePromise.fail(baseMsg() + " 缺少下载参数paramJson");
return parsePromise.future();
}
if (!applyFileParam(shareLinkInfo, (JsonObject) paramValue)) {
fail("下载参数id为空");
return promise.future();
JsonObject paramJson = (JsonObject) paramValue;
if (!applyFileParam(shareLinkInfo, paramJson)) {
Promise<String> parsePromise = Promise.promise();
parsePromise.fail(baseMsg() + " 下载参数id为空");
return parsePromise.future();
}
return parse();
}
@@ -117,298 +350,324 @@ public class CtTool extends PanBase {
return false;
}
shareLinkInfo.setSharePassword(paramJson.getString("pwd", ""));
String xtlink = paramJson.getString("xtlink", "");
if (!xtlink.isBlank()) {
shareLinkInfo.getOtherParam().put("ctXtlink", xtlink);
shareLinkInfo.getOtherParam().put("ctV4FileId", fileShareKey);
String parentKey = paramJson.getString("shareKey", "");
if (!parentKey.isBlank()) {
shareLinkInfo.setShareKey(parentKey);
} else if (shareLinkInfo.getShareKey() == null || shareLinkInfo.getShareKey().isBlank()) {
shareLinkInfo.setShareKey(fileShareKey);
}
return true;
}
shareLinkInfo.setShareKey(fileShareKey);
shareLinkInfo.setShareUrl(SHARE_FILE_URL_PREFIX + fileShareKey);
shareLinkInfo.setStandardUrl(SHARE_FILE_URL_PREFIX + fileShareKey);
return true;
}
private ParsedDownload resolveDownload(String shareKey) throws Exception {
if (requiresV4()) {
return downloadWithV4(shareKey);
static String resolveDownloadUid(JsonObject fileJson, String fallbackUid) {
return firstNonBlank(valueToString(fileJson.getValue("userid")), fallbackUid);
}
static String resolveDownloadFid(JsonObject fileJson, String fallbackFid) {
return firstNonBlank(valueToString(fileJson.getValue("file_id")), fallbackFid);
}
private HttpRequest<Buffer> withCtAjaxHeaders(HttpRequest<Buffer> request, String shareUrl) {
request.putHeader("User-Agent", BROWSER_UA)
.putHeader("Accept", AJAX_ACCEPT)
.putHeader("X-Requested-With", "XMLHttpRequest");
if (shareUrl != null && !shareUrl.isBlank()) {
request.putHeader("Referer", shareUrl);
}
VerificationMismatch mismatch = null;
for (int attempt = 0; attempt < 2; attempt++) {
try (CtfileSession session = CtfileSession.open(shareLinkInfo)) {
try {
return downloadOnce(session, shareKey);
} catch (VerificationMismatch retryable) {
// verifycode 和签发它的那次连接绑在一起。换一个客户端再取一次。
mismatch = retryable;
} catch (CtfileException e) {
if (turnstile(e) && CtfileV4Client.hasCredentials(shareLinkInfo)) {
return downloadWithV4(shareKey);
}
throw e;
}
}
String origin = extractOrigin(shareUrl);
if (!origin.isBlank()) {
request.putHeader("Origin", origin);
}
throw mismatch == null ? new CtfileException("未返回下载地址") : mismatch;
return request;
}
private ParsedDownload downloadWithV4(String shareKey) throws Exception {
if (!CtfileV4Client.hasCredentials(shareLinkInfo)) {
throw new CtfileException(CtfileV4Client.missingAccountMessage());
}
CtfileV4Client.DirectLink link = new CtfileV4Client(shareLinkInfo).downloadShare(shareKey, directoryShare());
return new ParsedDownload(link.url, java.util.Map.of(), link.file, "");
}
/** 只有 v4 目录列表生成的文件参数才直接走客户端协议。访问密码本身不触发登录。 */
static boolean requiresV4(ShareLinkInfo info) {
if (info == null || info.getOtherParam() == null) {
return false;
}
Object fileId = info.getOtherParam().get("ctV4FileId");
return fileId != null && !fileId.toString().isBlank();
}
private boolean requiresV4() {
return requiresV4(shareLinkInfo);
}
private static boolean turnstile(CtfileException error) {
return error.getMessage() != null && error.getMessage().contains("Turnstile");
}
private boolean directoryShare() {
String type = shareLinkInfo.getType();
if (type != null && type.equalsIgnoreCase("ctd")) {
return true;
}
String url = shareLinkInfo.getShareUrl();
return url != null && url.matches("(?i).*/d/[^/].*");
}
private ParsedDownload downloadOnce(CtfileSession session, String shareKey) throws Exception {
String password = shareLinkInfo.getSharePassword();
ShareTarget target = ShareTarget.from(shareLinkInfo);
JsonObject resource = session.loadResource("file", shareKey, target, password, turnstileToken());
JsonObject data = CtfileSession.dataOf(resource);
JsonObject file = data == null ? null : data.getJsonObject("file");
if (file == null) {
throw new CtfileException("下载参数不完整:上游没有返回文件信息");
}
DirectLink link = session.download(shareKey, target, password, resource);
return new ParsedDownload(link.url, link.headers, file, file.getString("file_dir", ""));
}
private List<FileInfo> listDirectory(String shareKey) throws Exception {
String password = shareLinkInfo.getSharePassword();
ShareTarget target = ShareTarget.from(shareLinkInfo);
int maxPages = maxListPages();
try (CtfileSession session = CtfileSession.open(shareLinkInfo)) {
JsonObject resource = session.loadResource("dir", shareKey, target, password, turnstileToken());
List<FileInfo> files = new ArrayList<>();
int start = 0;
for (int page = 0; page < maxPages; page++) {
JsonObject listing = session.listing("dir", shareKey, target, password, resource, start,
CtfileSession.pageSize());
int code = CtfileSession.intValue(listing.getValue("code"), 200);
if (code != 200) {
throw new CtfileException(CtfileSession.classify(listing, code, password).message);
}
JsonArray rows = CtfileSession.rowsOf(listing);
for (int i = 0; i < rows.size(); i++) {
if (rows.getValue(i) instanceof JsonObject row) {
FileInfo info = toFileInfo(row, shareLinkInfo);
if (info != null) {
files.add(info);
}
}
}
if (rows.isEmpty() || !CtfileSession.hasMore(listing, rows.size())) {
return files;
}
start += rows.size();
}
if (maxPages != DEFAULT_MAX_LIST_PAGES || shareLinkInfo.getOtherParam().containsKey("ctMaxListPages")) {
return files;
}
throw new CtfileException("目录文件过多,已超过 " + maxPages + " 页");
} catch (CtfileException e) {
if (turnstile(e) && CtfileV4Client.hasCredentials(shareLinkInfo)) {
return new CtfileV4Client(shareLinkInfo).listShare(shareKey, target.folderId, maxPages);
}
throw e;
}
}
static FileInfo toFileInfo(JsonObject row, ShareLinkInfo info) {
if (row == null) {
static FileInfo parseFileListRow(JsonArray row, String panType, String domainName, String shareUrl, String pwd) {
if (row == null || row.size() < 2) {
return null;
}
String name = row.getString("name", "").trim();
if (name.isBlank()) {
String checkboxHtml = rowString(row, 0);
String nameCellHtml = rowString(row, 1);
String sizeStr = rowString(row, 2).trim();
String dateStr = rowString(row, 3).trim();
if (nameCellHtml.isBlank()) {
return null;
}
String kind = row.getString("kind", "");
String password = info.getSharePassword() == null ? "" : info.getSharePassword();
FileInfo fileInfo = new FileInfo()
.setFileName(name)
.setPanType(info.getType())
.setCreateBy(CtfileSession.text(row.getValue("ownerId")));
String date = row.getString("date", "");
if (!date.isBlank()) {
fileInfo.setCreateTime(date).setUpdateTime(date);
String fileName = matchFirst(FILE_NAME_PATTERN, nameCellHtml);
String fileIcon = matchFirst(FILE_ICON_PATTERN, nameCellHtml);
if (fileName == null || fileName.isBlank()) {
return null;
}
if ("folder".equals(kind)) {
String folderId = CtfileSession.text(row.getValue("folderId"));
if (folderId.isBlank()) {
Matcher subdirMatcher = SUBDIR_PATTERN.matcher(nameCellHtml);
boolean hasSubdirCall = subdirMatcher.find();
if (hasSubdirCall || "folder".equalsIgnoreCase(fileIcon)) {
String folderId = hasSubdirCall ? subdirMatcher.group(1) : null;
String folderKey = hasSubdirCall ? subdirMatcher.group(2) : "";
if (folderId == null) {
folderId = matchFirst(FOLDER_ID_PATTERN, checkboxHtml);
}
if (folderId == null || folderId.isBlank()) {
return null;
}
String folderKey = row.getString("folderKey", "");
fileInfo.setFileId(folderId)
.setFileType("folder")
String dirId = folderId + ":" + folderKey;
FileInfo fileInfo = new FileInfo()
.setFileName(fileName.trim())
.setFileId(folderId)
.setSize(0L)
.setSizeStr("0B")
.setParserUrl(buildFolderParserUrl(info, folderId + ":" + (folderKey == null ? "" : folderKey), password));
.setSizeStr(sizeStr.isBlank() ? "0B" : sizeStr)
.setFileType("folder")
.setFileIcon(fileIcon)
.setPanType(panType)
.setParserUrl(buildFolderParserUrl(domainName, shareUrl, dirId, pwd));
if (!dateStr.isBlank()) {
fileInfo.setCreateTime(dateStr).setUpdateTime(dateStr);
}
return fileInfo;
}
if (!"file".equals(kind)) {
String fileShareKey = matchFirst(FILE_HREF_PATTERN, nameCellHtml);
if (fileShareKey == null || fileShareKey.isBlank()) {
return null;
}
String fileKey = fileKeyFromHref(row.getString("href", ""));
if (fileKey.isBlank()) {
fileKey = CtfileSession.text(row.getValue("fileId"));
String fileId = matchFirst(FILE_ID_PATTERN, checkboxHtml);
JsonObject paramJson = new JsonObject()
.put("id", fileShareKey)
.put("fileName", fileName.trim())
.put("pwd", pwd == null ? "" : pwd);
String param = CommonUtils.urlBase64Encode(paramJson.encode());
long sizeBytes = 0;
try {
sizeBytes = sizeStr.isBlank() ? 0 : FileSizeConverter.convertToBytes(sizeStr);
} catch (Exception ignored) {
}
if (fileKey.isBlank()) {
return null;
FileInfo fileInfo = new FileInfo()
.setFileName(fileName.trim())
.setFileId(fileId)
.setSizeStr(sizeStr)
.setSize(sizeBytes)
.setFileType(fileIcon != null ? fileIcon : "file")
.setFileIcon(fileIcon)
.setPanType(panType)
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
domainName, panType, param));
if (!dateStr.isBlank()) {
fileInfo.setCreateTime(dateStr).setUpdateTime(dateStr);
}
long size = CtfileSession.longValue(row.getValue("size_bytes"), 0L);
JsonObject param = new JsonObject()
.put("id", fileKey)
.put("fileName", name)
.put("pwd", password);
String encoded = CommonUtils.urlBase64Encode(param.encode());
String domain = info.getOtherParam() == null ? "" : info.getOtherParam().getOrDefault("domainName", "").toString();
fileInfo.setFileId(CtfileSession.firstNonBlank(CtfileSession.text(row.getValue("fileId")), fileKey))
.setFileType(CtfileSession.firstNonBlank(row.getString("extension"), "file"))
.setSize(size)
.setSizeStr(row.getString("size", ""))
.setParserUrl(domain + "/v2/redirectUrl/" + info.getType() + "/" + encoded);
return fileInfo;
}
private static String buildFolderParserUrl(ShareLinkInfo info, String dirId, String password) {
String domain = info.getOtherParam() == null ? "" : info.getOtherParam().getOrDefault("domainName", "").toString();
String shareUrl = info.getShareUrl() == null ? "" : info.getShareUrl();
String url = domain + "/v2/getFileList?url=" + urlEncode(shareUrl) + "&dirId=" + urlEncode(dirId);
if (password != null && !password.isBlank()) {
url += "&pwd=" + urlEncode(password);
private static String buildFolderParserUrl(String domainName, String shareUrl, String dirId, String pwd) {
String url = String.format("%s/v2/getFileList?url=%s&dirId=%s",
domainName, urlEncode(shareUrl), urlEncode(dirId));
if (pwd != null && !pwd.isBlank()) {
url += "&pwd=" + urlEncode(pwd);
}
return url;
}
private static String fileKeyFromHref(String href) {
if (href == null || href.isBlank()) {
return "";
static String extractQueryParam(String url, String paramName) {
if (url == null || paramName == null) return null;
int qIdx = url.indexOf('?');
if (qIdx < 0) return null;
String query = url.substring(qIdx + 1);
int fragmentIdx = query.indexOf('#');
if (fragmentIdx >= 0) {
query = query.substring(0, fragmentIdx);
}
int marker = href.indexOf("/f/");
int skip = 3;
if (marker < 0) {
marker = href.indexOf("/file/");
skip = 6;
}
if (marker < 0) {
return "";
}
String rest = href.substring(marker + skip);
int cut = rest.length();
for (int i = 0; i < rest.length(); i++) {
char c = rest.charAt(i);
if (c == '?' || c == '#' || c == '/') {
cut = i;
break;
for (String param : query.split("&")) {
int eqIdx = param.indexOf('=');
if (eqIdx > 0 && urlDecode(param.substring(0, eqIdx)).equals(paramName)) {
return urlDecode(param.substring(eqIdx + 1));
}
}
return rest.substring(0, cut);
return null;
}
private FileInfo fileInfoFrom(JsonObject file) {
long size = CtfileSession.longValue(file.getValue("file_size_bytes"), 0L);
FileInfo info = new FileInfo()
.setFileName(file.getString("file_name", ""))
.setFileId(CtfileSession.text(file.getValue("file_id")))
.setSize(size)
.setSizeStr(file.getString("file_size", ""))
.setFileType("file")
.setCreateBy(file.getString("username", ""))
.setPanType(shareLinkInfo.getType());
String created = file.getString("file_time", "");
if (!created.isBlank()) {
info.setCreateTime(created);
}
return info;
}
private String turnstileToken() {
if (shareLinkInfo.getOtherParam() == null) {
static String extractPath(String shareUrl) {
if (shareUrl == null) {
return "";
}
Object value = shareLinkInfo.getOtherParam().get("turnstileToken");
return value == null ? "" : value.toString().trim();
int comIdx = shareUrl.indexOf("com/");
if (comIdx < 0) {
return "";
}
int pathStart = comIdx + 4;
int pathEnd = shareUrl.indexOf('/', pathStart);
if (pathEnd < 0) {
pathEnd = shareUrl.indexOf('?', pathStart);
}
if (pathEnd < 0) {
pathEnd = shareUrl.length();
}
return shareUrl.substring(pathStart, pathEnd);
}
private int maxListPages() {
if (shareLinkInfo.getOtherParam() == null || !shareLinkInfo.getOtherParam().containsKey("ctMaxListPages")) {
return DEFAULT_MAX_LIST_PAGES;
}
int configured = CtfileSession.intValue(shareLinkInfo.getOtherParam().get("ctMaxListPages"), DEFAULT_MAX_LIST_PAGES);
return configured < 1 ? 1 : configured;
static String extractFolderKey(String shareUrl) {
return trimToEmpty(extractQueryParam(shareUrl, "fk"));
}
private static String rootMessage(Throwable error) {
Throwable current = error;
while (current.getCause() != null && current.getCause() != current
&& (current.getMessage() == null || current.getMessage().isBlank()
|| current.getClass().getName().contains("CompletionException")
|| current.getClass().getName().contains("ExecutionException"))) {
current = current.getCause();
static DirectoryContext resolveDirectoryContext(String shareUrl, Object dirIdObj) {
String dirId = dirIdObj == null ? "" : urlDecode(String.valueOf(dirIdObj).trim());
if (!dirId.isBlank()) {
String[] split = dirId.split(":", 2);
return new DirectoryContext(trimToDefault(split[0], "undefined"),
split.length > 1 ? trimToEmpty(split[1]) : "");
}
String message = current.getMessage();
return message == null || message.isBlank() ? current.getClass().getSimpleName() : message;
String queryFolderId = firstNonBlank(extractQueryParam(shareUrl, "folder_id"), extractQueryParam(shareUrl, "d"));
String queryFk = extractFolderKey(shareUrl);
if (!queryFolderId.isBlank() || !queryFk.isBlank()) {
return new DirectoryContext(trimToDefault(queryFolderId, "undefined"), queryFk);
}
return new DirectoryContext("undefined", "");
}
static String buildDirectoryFailureMessage(JsonObject resJson, JsonObject dirInfo) {
String code = valueToString(resJson.getValue("code"));
String message = valueToString(dirInfo.getValue("message"));
if (message != null && !message.isBlank()) {
return "目录解析失败: " + message + " (code=" + code + ")";
}
if ("423".equals(code)) {
return "目录解析失败: 需要访问密码或该分享受限 (code=423)";
}
return "目录解析失败: 文件列表URL为空, 上游响应: " + resJson.encode();
}
static String buildFileListParams(int start, int length) {
return FILE_LIST_PARAMS_TEMPLATE
.replace("{start}", String.valueOf(Math.max(0, start)))
.replace("{length}", String.valueOf(Math.max(1, length)));
}
static int parseFileListTotal(JsonObject listJson) {
int displayTotal = parseInteger(listJson.getValue("iTotalDisplayRecords"), -1);
return displayTotal >= 0 ? displayTotal : parseInteger(listJson.getValue("iTotalRecords"), -1);
}
static boolean shouldFetchNextFileListPage(int start, int rowCount, int total) {
if (rowCount <= 0) {
return false;
}
int fetchedThrough = start + rowCount;
return total < 0 ? rowCount >= FILE_LIST_PAGE_SIZE : fetchedThrough < total;
}
static boolean isUnexpectedEmptyFileListPage(int start, int rowCount, int total) {
return total >= 0 && start < total && rowCount <= 0;
}
private static int parseInteger(Object value, int defaultValue) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value == null) {
return defaultValue;
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return defaultValue;
}
}
private static void failListPromise(Promise<List<FileInfo>> listPromise, String message) {
if (!listPromise.future().isComplete()) {
listPromise.fail(message);
}
}
private static void failListPromise(Promise<List<FileInfo>> listPromise, Throwable throwable) {
if (!listPromise.future().isComplete()) {
listPromise.fail(throwable);
}
}
private static void completeListPromise(Promise<List<FileInfo>> listPromise, List<FileInfo> fileList) {
if (!listPromise.future().isComplete()) {
listPromise.complete(fileList);
}
}
private static String toCtApiUrl(String url) {
if (url.startsWith("http://") || url.startsWith("https://")) {
return url;
}
return API_URL_PREFIX + url;
}
private static String appendQueryParams(String url, String params) {
String normalizedParams = params != null && params.startsWith("&") ? params.substring(1) : params;
return url + (url.contains("?") ? "&" : "?") + normalizedParams;
}
private static String rowString(JsonArray row, int index) {
if (row == null || index >= row.size()) {
return "";
}
return valueToString(row.getValue(index));
}
private static String valueToString(Object value) {
return value == null ? "" : value.toString();
}
private static String matchFirst(Pattern pattern, String text) {
if (text == null) {
return null;
}
Matcher matcher = pattern.matcher(text);
return matcher.find() ? matcher.group(1) : null;
}
private static String firstNonBlank(String first, String second) {
return !trimToEmpty(first).isBlank() ? trimToEmpty(first) : trimToEmpty(second);
}
private static String trimToDefault(String value, String defaultValue) {
String result = trimToEmpty(value);
return result.isBlank() ? defaultValue : result;
}
private static String trimToEmpty(String value) {
return value == null ? "" : value.trim();
}
private static String urlEncode(String value) {
return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8);
}
private static WorkerExecutor worker() {
synchronized (WORKER_LOCK) {
if (workerShutdown) {
throw new IllegalStateException("城通解析线程池已关闭");
}
if (sharedWorker == null) {
sharedWorker = WebClientVertxInit.get().createSharedWorkerExecutor("ctfile-worker", 4);
}
return sharedWorker;
private static String urlDecode(String value) {
if (value == null) {
return "";
}
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8);
} catch (Exception e) {
return value;
}
}
private static final class ParsedDownload {
final String url;
final java.util.Map<String, String> headers;
final JsonObject file;
final String fileDir;
private static String extractOrigin(String shareUrl) {
try {
URI uri = URI.create(shareUrl);
if (uri.getScheme() == null || uri.getHost() == null) {
return "";
}
String origin = uri.getScheme() + "://" + uri.getHost();
return uri.getPort() > 0 ? origin + ":" + uri.getPort() : origin;
} catch (Exception e) {
return "";
}
}
ParsedDownload(String url, java.util.Map<String, String> headers, JsonObject file, String fileDir) {
this.url = url;
this.headers = headers;
this.file = file;
this.fileDir = fileDir;
static final class DirectoryContext {
final String folderId;
final String folderKey;
DirectoryContext(String folderId, String folderKey) {
this.folderId = folderId;
this.folderKey = folderKey;
}
}
}
@@ -1,692 +0,0 @@
package cn.qaiu.parser.impl;
import cn.qaiu.entity.ShareLinkInfo;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 城通新版分享接口(api.ctfile.com/url/*)。
* <p>
* 一次解析专用一个 HttpClient:资源接口签发的 verifycode 绑定本次连接的出口 IP,
* 下载必须跟在同一次连接上的 resource 之后。访问令牌 access_pass 约 24 小时、按分享者复用,
* 用来跳过重复的 ALTCHA 计算。
*/
final class CtfileSession implements AutoCloseable {
static final String API = "https://api.ctfile.com";
private static final String CHALLENGE_PATH = "/url/captcha/altcha?captcha_action=share_passcode";
private static final String UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(20);
private static final int PAGE_SIZE = 200;
private static final long PASS_SKEW_MILLIS = 60_000L;
private static final ConcurrentHashMap<String, CachedPass> ACCESS_PASSES = new ConcurrentHashMap<>();
private final HttpClient client;
private final String origin;
private final String referer;
private CtfileSession(HttpClient client, String origin, String referer) {
this.client = client;
this.origin = origin;
this.referer = referer;
}
static CtfileSession open(ShareLinkInfo info) {
String shareUrl = info == null ? "" : info.getShareUrl();
String origin = originOf(shareUrl);
if (origin.isBlank()) {
origin = "https://www.ctfile.com";
}
String referer = shareUrl == null || shareUrl.isBlank() ? origin + "/" : shareUrl;
return new CtfileSession(newClient(info), origin, referer);
}
JsonObject loadResource(String kind, String id, ShareTarget target, String password, String turnstileToken)
throws Exception {
JsonObject body = getResource(kind, id, target, password, null, null, null);
Decision decision = classify(body, 200, password);
if (decision.kind == Kind.OK) {
remember(decision, password, null);
return body;
}
// 带密码分享的首次响应经常标成 turnstile,但提交一次 ALTCHA 后正确密码会直接 200。
// 过期的 access_pass 同样会回到这个分支,丢弃后重新计算。
if (shouldSolveAltcha(decision)) {
String cached = cachedPass(decision.ownerId, password);
if (cached != null) {
JsonObject retry = getResource(kind, id, target, password, null, null, cached);
Decision again = classify(retry, 200, password);
if (again.kind == Kind.OK) {
remember(again, password, cached);
return retry;
}
forget(decision.ownerId, password);
}
JsonObject challenge = challenge();
if (expiresSoon(challenge)) {
challenge = challenge();
}
AltchaV2Solver.Solution solution = AltchaV2Solver.solve(challenge);
String token = AltchaV2Solver.payload(challenge, solution);
JsonObject retry = getResource(kind, id, target, password, token, null, null);
Decision solved = classify(retry, 200, password);
if (solved.kind == Kind.OK) {
remember(solved, password, null);
return retry;
}
if (solved.kind == Kind.ALTCHA) {
throw new CtfileException("ALTCHA 人机验证未通过,请重试");
}
if (solved.kind == Kind.TURNSTILE && turnstileToken != null && !turnstileToken.isBlank()) {
JsonObject withTurnstile = getResource(kind, id, target, password, null, turnstileToken, null);
Decision afterTurnstile = classify(withTurnstile, 200, password);
if (afterTurnstile.kind == Kind.OK) {
remember(afterTurnstile, password, null);
return withTurnstile;
}
throw new CtfileException(afterTurnstile.message);
}
throw new CtfileException(solved.message);
}
throw new CtfileException(decision.message);
}
/** 匿名分享优先解 ALTCHA。首次响应写成 turnstile 时,正确密码仍可能被 ALTCHA 放行。 */
static boolean shouldSolveAltcha(Decision decision) {
return decision != null && (decision.kind == Kind.ALTCHA || decision.kind == Kind.TURNSTILE);
}
DirectLink download(String id, ShareTarget target, String password, JsonObject resource) throws Exception {
JsonObject data = dataOf(resource);
JsonObject file = data == null ? null : data.getJsonObject("file");
if (file == null) {
throw new CtfileException("下载参数不完整:上游没有返回文件信息");
}
String pass = firstNonBlank(data.getString("access_pass"), cachedPass(ownerId(data), password));
return postDownload(id, target, password, file, pass, 0);
}
JsonObject listing(String kind, String id, ShareTarget target, String password, JsonObject resource,
int start, int length) throws Exception {
JsonObject data = dataOf(resource);
String pass = data == null ? null : firstNonBlank(data.getString("access_pass"), cachedPass(ownerId(data), password));
Map<String, String> query = resourceQuery(kind, id, target, password, null, null, pass);
query.put("start", String.valueOf(Math.max(0, start)));
query.put("length", String.valueOf(Math.max(1, length)));
return exchange("GET", "/url/listing?" + form(query), null, origin, referer);
}
static int pageSize() {
return PAGE_SIZE;
}
private DirectLink postDownload(String id, ShareTarget target, String password, JsonObject file, String pass,
int waitedSeconds) throws Exception {
if (waitedSeconds > 120) {
throw new CtfileException("下载需要等待的时间过长");
}
String verify = file.getString("verifycode", "");
String fileChk = file.getString("file_chk", "");
if (verify.isBlank() || fileChk.isBlank() || file.getValue("file_id") == null || file.getValue("userid") == null) {
throw new CtfileException("下载参数不完整:缺少 file_chk 或 verifycode");
}
JsonObject context = new JsonObject()
.put("kind", "file")
.put("id", id)
.put("folder_id", target.folderId)
.put("fk", target.fk)
.put("passcode", password == null ? "" : password)
.put("type_id", target.typeId);
if (pass != null && !pass.isBlank()) {
context.put("access_pass", pass);
}
JsonObject original = new JsonObject()
.put("file_id", file.getValue("file_id"))
.put("userid", file.getValue("userid"))
.put("file_chk", fileChk)
.put("start_time", file.getValue("start_time"))
.put("wait_seconds", file.getValue("wait_seconds"));
JsonObject body = new JsonObject()
.put("context", context)
.put("app", false)
.put("verifycode", verify)
.put("original_file", original)
.put("carrier", 0);
JsonObject response = exchange("POST", "/url/download", body.encode().getBytes(StandardCharsets.UTF_8),
origin, referer);
int top = codeOf(response, 200);
JsonObject data = dataOf(response);
int code = data != null && data.getValue("code") != null ? codeOf(data, top) : top;
String message = firstNonBlank(response.getString("msg"), response.getString("message"),
data == null ? "" : firstNonBlank(data.getString("msg"), data.getString("message")));
if (code == 218) {
int remaining = intValue(data == null ? null : data.getValue("remaining_seconds"),
intValue(response.getValue("remaining_seconds"), 1));
remaining = Math.max(1, Math.min(remaining, 30));
sleepSeconds(remaining);
return postDownload(id, target, password, file, pass, waitedSeconds + remaining);
}
if (code == 219) {
throw new CtfileException("需要登录后才能下载");
}
if (code == 403 && message.toLowerCase().contains("verification")) {
throw new VerificationMismatch("下载校验未通过或已过期,请重试");
}
String downurl = data == null ? null : data.getString("downurl");
if (code != 200 || downurl == null || downurl.isBlank()) {
throw new CtfileException(message.isBlank()
? "未返回下载地址 (code=" + code + ")"
: "未返回下载地址: " + message);
}
Map<String, String> headers = new LinkedHashMap<>();
if (data.getValue("headers") instanceof JsonObject headerJson) {
for (String key : headerJson.fieldNames()) {
Object value = headerJson.getValue(key);
if (key != null && value != null && !value.toString().isBlank()) {
headers.put(key, value.toString());
}
}
}
return new DirectLink(downurl, headers);
}
private JsonObject getResource(String kind, String id, ShareTarget target, String password,
String altchaToken, String turnstileToken, String accessPass) throws Exception {
Map<String, String> params = resourceQuery(kind, id, target, password, altchaToken, turnstileToken, accessPass);
return exchange("GET", "/url/resource?" + form(params), null, origin, referer);
}
private JsonObject challenge() throws Exception {
return exchange("GET", CHALLENGE_PATH, null, "https://h5.ctfile.com",
"https://h5.ctfile.com/captcha/altcha.html");
}
private JsonObject exchange(String method, String path, byte[] body, String requestOrigin, String requestReferer)
throws Exception {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(API + path))
.timeout(REQUEST_TIMEOUT)
.header("User-Agent", UA)
.header("Accept", "application/json, text/plain, */*")
.header("Origin", requestOrigin)
.header("Referer", requestReferer);
if (body == null) {
builder.method(method, HttpRequest.BodyPublishers.noBody());
} else {
builder.header("Content-Type", "application/json");
builder.method(method, HttpRequest.BodyPublishers.ofByteArray(body));
}
HttpResponse<String> response;
try {
response = client.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CtfileException("请求被中断");
} catch (IOException e) {
throw new CtfileException("请求失败: " + e.getMessage());
}
String text = response.body();
if (text == null || text.isBlank()) {
throw new CtfileException("上游返回空响应 (HTTP " + response.statusCode() + ")");
}
try {
return new JsonObject(text);
} catch (Exception e) {
throw new CtfileException("上游返回了无法识别的响应 (HTTP " + response.statusCode() + ")");
}
}
static Map<String, String> resourceQuery(String kind, String id, ShareTarget target, String password,
String altchaToken, String turnstileToken, String accessPass) {
Map<String, String> query = new LinkedHashMap<>();
query.put("kind", kind == null || kind.isBlank() ? "file" : kind);
query.put("id", id == null ? "" : id);
query.put("folder_id", target.folderId);
query.put("fk", target.fk);
query.put("passcode", password == null ? "" : password);
query.put("type_id", target.typeId);
if (altchaToken != null && !altchaToken.isBlank()) {
query.put("altcha_token", altchaToken);
}
if (turnstileToken != null && !turnstileToken.isBlank()) {
query.put("turnstile_token", turnstileToken);
}
if (accessPass != null && !accessPass.isBlank()) {
query.put("access_pass", accessPass);
}
return query;
}
static String form(Map<String, String> query) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : query.entrySet()) {
if (entry.getValue() == null) {
continue;
}
if (builder.length() > 0) {
builder.append('&');
}
builder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
builder.append('=');
builder.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
}
return builder.toString();
}
static Decision classify(JsonObject body, int httpStatus, String password) {
int code = codeOf(body, httpStatus);
JsonObject data = dataOf(body);
String message = firstNonBlank(body == null ? "" : body.getString("msg"),
body == null ? "" : body.getString("message"));
String errorType = data == null ? "" : text(data.getValue("error_type"));
String captcha = data == null ? "" : text(data.getValue("captcha_type"));
JsonObject capabilities = data == null ? null : data.getJsonObject("capabilities");
boolean passcodeRequired = capabilities != null && Boolean.TRUE.equals(capabilities.getValue("passcodeRequired"));
String owner = capabilities == null ? "" : text(capabilities.getValue("ownerId"));
boolean passwordMissing = password == null || password.isBlank();
boolean captchaAsked = "captcha_required".equals(errorType) || errorType.startsWith("captcha_");
if (code == 200) {
return Decision.ok(owner, accessPass(data));
}
if (code == 404) {
return Decision.of(Kind.NOT_FOUND, owner, "分享不存在或已过期" + suffix(message));
}
if (code == 403) {
return Decision.of(Kind.INVALID, owner, "分享链接无效或已失效" + suffix(message));
}
if (code == 423) {
if ("passcode_incorrect".equals(errorType)) {
return Decision.of(Kind.BAD_PASSWORD, owner, "访问密码不正确" + suffix(message));
}
if (passwordMissing && passcodeRequired && !captchaAsked) {
return Decision.of(Kind.NEED_PASSWORD, owner, "需要访问密码");
}
if ("turnstile".equalsIgnoreCase(captcha)) {
return Decision.of(Kind.TURNSTILE, owner, "触发 Cloudflare Turnstile 人机验证,暂不支持服务端自动通过");
}
if ("altcha".equalsIgnoreCase(captcha)) {
return Decision.of(Kind.ALTCHA, owner, "需要完成 ALTCHA 人机验证");
}
if (passwordMissing && passcodeRequired) {
return Decision.of(Kind.NEED_PASSWORD, owner, "需要访问密码");
}
return Decision.of(Kind.OTHER, owner, "分享暂时无法访问" + suffix(message) + " (code=423)");
}
return Decision.of(Kind.OTHER, owner,
"上游返回异常 (code=" + code + ")" + suffix(message));
}
private static void remember(Decision decision, String password, String fallbackPass) {
String token = firstNonBlank(decision.accessPass, fallbackPass);
if (decision.ownerId == null || decision.ownerId.isBlank() || token == null || token.isBlank()) {
return;
}
long expiry = passExpiry(token);
if (expiry < System.currentTimeMillis() + PASS_SKEW_MILLIS) {
return;
}
ACCESS_PASSES.put(cacheKey(decision.ownerId, password), new CachedPass(token, expiry));
}
private static String cachedPass(String ownerId, String password) {
if (ownerId == null || ownerId.isBlank()) {
return null;
}
CachedPass cached = ACCESS_PASSES.get(cacheKey(ownerId, password));
if (cached == null) {
return null;
}
if (cached.expiresAtMillis < System.currentTimeMillis() + PASS_SKEW_MILLIS) {
ACCESS_PASSES.remove(cacheKey(ownerId, password), cached);
return null;
}
return cached.token;
}
private static void forget(String ownerId, String password) {
if (ownerId != null && !ownerId.isBlank()) {
ACCESS_PASSES.remove(cacheKey(ownerId, password));
}
}
static void clearCachedPasses() {
ACCESS_PASSES.clear();
}
private static String cacheKey(String ownerId, String password) {
return ownerId + "\n" + (password == null ? "" : password);
}
private static long passExpiry(String token) {
try {
String[] parts = token.split("\\.");
if (parts.length < 2) {
return System.currentTimeMillis() + Duration.ofMinutes(30).toMillis();
}
byte[] json = Base64.getUrlDecoder().decode(padBase64(parts[1]));
JsonObject payload = new JsonObject(new String(json, StandardCharsets.UTF_8));
Object expiry = payload.getValue("e");
if (expiry instanceof Number) {
return ((Number) expiry).longValue() * 1000L;
}
} catch (Exception ignored) {
// 解析不了有效期时按半小时使用,失效后会重新计算 ALTCHA。
}
return System.currentTimeMillis() + Duration.ofMinutes(30).toMillis();
}
private static boolean expiresSoon(JsonObject challenge) {
JsonObject parameters = challenge.getJsonObject("parameters");
if (parameters == null) {
return false;
}
Object expiry = parameters.getValue("expiresAt");
if (!(expiry instanceof Number)) {
return false;
}
long expiresAtMillis = ((Number) expiry).longValue() * 1000L;
return expiresAtMillis < System.currentTimeMillis() + 15_000L;
}
private static String accessPass(JsonObject data) {
return data == null ? "" : text(data.getValue("access_pass"));
}
private static String ownerId(JsonObject data) {
if (data == null) {
return "";
}
JsonObject capabilities = data.getJsonObject("capabilities");
return capabilities == null ? "" : text(capabilities.getValue("ownerId"));
}
static JsonObject dataOf(JsonObject body) {
if (body == null || !(body.getValue("data") instanceof JsonObject)) {
return null;
}
return body.getJsonObject("data");
}
static JsonArray rowsOf(JsonObject listing) {
JsonObject data = dataOf(listing);
if (data == null || !(data.getValue("rows") instanceof JsonArray)) {
return new JsonArray();
}
return data.getJsonArray("rows");
}
static boolean hasMore(JsonObject listing, int rowCount) {
JsonObject data = dataOf(listing);
if (data != null && data.getValue("hasMore") instanceof Boolean) {
return data.getBoolean("hasMore");
}
return rowCount >= PAGE_SIZE;
}
private static int codeOf(JsonObject body, int fallback) {
if (body == null) {
return fallback;
}
return intValue(body.getValue("code"), fallback);
}
static int intValue(Object value, int fallback) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value == null) {
return fallback;
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return fallback;
}
}
static long longValue(Object value, long fallback) {
if (value instanceof Number) {
return ((Number) value).longValue();
}
if (value == null) {
return fallback;
}
try {
return Long.parseLong(value.toString());
} catch (NumberFormatException e) {
return fallback;
}
}
private static String suffix(String message) {
return message == null || message.isBlank() ? "" : "(" + message + ")";
}
static String text(Object value) {
return value == null ? "" : value.toString().trim();
}
static String firstNonBlank(String... values) {
if (values == null) {
return "";
}
for (String value : values) {
if (value != null && !value.isBlank()) {
return value;
}
}
return "";
}
private static String padBase64(String value) {
int mod = value.length() % 4;
if (mod == 0) {
return value;
}
return value + "=".repeat(4 - mod);
}
private static void sleepSeconds(int seconds) throws CtfileException {
try {
Thread.sleep(seconds * 1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CtfileException("下载等待被中断");
}
}
private static String originOf(String shareUrl) {
if (shareUrl == null || shareUrl.isBlank()) {
return "";
}
try {
URI uri = URI.create(shareUrl);
if (uri.getScheme() == null || uri.getHost() == null) {
return "";
}
String origin = uri.getScheme() + "://" + uri.getHost();
return uri.getPort() > 0 ? origin + ":" + uri.getPort() : origin;
} catch (Exception e) {
return "";
}
}
static String queryParam(String url, String name) {
if (url == null || name == null) {
return "";
}
int query = url.indexOf('?');
if (query < 0) {
return "";
}
String raw = url.substring(query + 1);
int hash = raw.indexOf('#');
if (hash >= 0) {
raw = raw.substring(0, hash);
}
for (String part : raw.split("&")) {
int eq = part.indexOf('=');
if (eq <= 0) {
continue;
}
String key = decode(part.substring(0, eq));
if (name.equals(key)) {
return decode(part.substring(eq + 1));
}
}
return "";
}
private static String decode(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8);
} catch (Exception e) {
return value;
}
}
private static HttpClient newClient(ShareLinkInfo info) {
HttpClient.Builder builder = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NEVER);
Object proxyValue = info == null || info.getOtherParam() == null ? null : info.getOtherParam().get("proxy");
if (proxyValue instanceof JsonObject proxy) {
String host = proxy.getString("host");
Integer port = proxy.getInteger("port");
if (host != null && !host.isBlank() && port != null) {
builder.proxy(ProxySelector.of(new InetSocketAddress(host, port)));
String username = proxy.getString("username");
String password = proxy.getString("password", "");
if (username != null && !username.isBlank()) {
builder.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
return new PasswordAuthentication(username, password.toCharArray());
}
return null;
}
});
}
}
}
return builder.build();
}
@Override
public void close() {
try {
client.getClass().getMethod("close").invoke(client);
} catch (NoSuchMethodException ignored) {
// JDK 17 的 HttpClient 还不能关闭,连接会按空闲超时回收。
} catch (Exception ignored) {
// 关闭失败不影响解析结果。
}
}
static final class ShareTarget {
final String folderId;
final String fk;
final String typeId;
ShareTarget(String folderId, String fk, String typeId) {
this.folderId = folderId == null || folderId.isBlank() ? "0" : folderId;
this.fk = fk == null ? "" : fk;
this.typeId = typeId == null || typeId.isBlank() ? "0" : typeId;
}
static ShareTarget from(ShareLinkInfo info) {
String dirId = "";
if (info.getOtherParam() != null && info.getOtherParam().get("dirId") != null) {
dirId = decode(info.getOtherParam().get("dirId").toString().trim());
}
if (!dirId.isBlank()) {
String[] parts = dirId.split(":", 2);
return new ShareTarget(parts[0], parts.length > 1 ? parts[1] : "",
queryParam(info.getShareUrl(), "type_id"));
}
String shareUrl = info.getShareUrl();
String folderId = firstNonBlank(queryParam(shareUrl, "folder_id"), queryParam(shareUrl, "d"));
return new ShareTarget(folderId, queryParam(shareUrl, "fk"), queryParam(shareUrl, "type_id"));
}
}
static final class DirectLink {
final String url;
final Map<String, String> headers;
DirectLink(String url, Map<String, String> headers) {
this.url = url;
this.headers = headers;
}
}
enum Kind {
OK, NOT_FOUND, INVALID, NEED_PASSWORD, BAD_PASSWORD, TURNSTILE, ALTCHA, OTHER
}
static final class Decision {
final Kind kind;
final String ownerId;
final String accessPass;
final String message;
private Decision(Kind kind, String ownerId, String accessPass, String message) {
this.kind = kind;
this.ownerId = ownerId == null ? "" : ownerId;
this.accessPass = accessPass == null ? "" : accessPass;
this.message = message == null ? "" : message;
}
static Decision ok(String ownerId, String accessPass) {
return new Decision(Kind.OK, ownerId, accessPass, "");
}
static Decision of(Kind kind, String ownerId, String message) {
return new Decision(kind, ownerId, "", message);
}
}
static class CtfileException extends Exception {
CtfileException(String message) {
super(message);
}
}
static final class VerificationMismatch extends CtfileException {
VerificationMismatch(String message) {
super(message);
}
}
private static final class CachedPass {
final String token;
final long expiresAtMillis;
CachedPass(String token, long expiresAtMillis) {
this.token = token;
this.expiresAtMillis = expiresAtMillis;
}
}
}
@@ -1,679 +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.TokenCache;
import cn.qaiu.parser.impl.CtfileSession.CtfileException;
import cn.qaiu.util.CommonUtils;
import io.vertx.core.MultiMap;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* 城通官方客户端协议 {@code /v4}。匿名 ALTCHA 仍被 Turnstile 拦住时的可选回退,
* 需要调用方自己的登录令牌。带访问密码的分享默认不走这里。
*/
final class CtfileV4Client {
static final String API = "https://api.ctfile.com";
private static final String UA = "Mozilla/5.0 CTFileApp/5.1.24";
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(20);
private static final long EXPIRY_SKEW_MILLIS = 60_000L;
private static final int PAGE_SIZE = 100;
private static final ConcurrentHashMap<String, Session> SESSIONS = new ConcurrentHashMap<>();
private static final HttpClient HTTP = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NEVER)
.build();
private final ShareLinkInfo shareLinkInfo;
CtfileV4Client(ShareLinkInfo shareLinkInfo) {
this.shareLinkInfo = shareLinkInfo;
}
static boolean hasCredentials(ShareLinkInfo info) {
return credentials(info).usable();
}
static String missingAccountMessage() {
return "匿名解析仍被 Cloudflare Turnstile 拦住,且未配置城通账号。"
+ "可在 app-dev.yml 配置 auths.ct.refresh_token 作为可选回退,或在请求 auth 中传入。"
+ "refresh_token 来自浏览器登录 pan.ctfile.com 后 Session Storage 中的 refresh_token;"
+ "token 可填当前 access token。目录类型 ctd 未单独配置时回退使用 ct。";
}
DirectLink downloadShare(String shareKey, boolean directory) throws Exception {
String explicitFileId = text(shareLinkInfo.getOtherParam().get("ctV4FileId"));
String xtlink = text(shareLinkInfo.getOtherParam().get("ctXtlink"));
if (xtlink.isBlank()) {
xtlink = CtfileXtlink.fromShare(shareKey, shareLinkInfo.getSharePassword(), directory && explicitFileId.isBlank());
}
if (xtlink == null) {
throw new CtfileException("这个分享标识不能转换成官方 xtlink");
}
String fileId = explicitFileId.isBlank()
? CtfileXtlink.prefixedId(shareId(shareKey), false)
: CtfileXtlink.prefixedId(explicitFileId, false);
if (fileId.isBlank()) {
throw new CtfileException("分享标识里没有文件 id,无法取直链");
}
String token = accessToken(false);
JsonObject listed = null;
try {
listed = post("/v4/public/browser/list", listBody(xtlink, "0", 0, 20), token);
} catch (V4CallException e) {
if (e.authenticationFailure()) {
token = recoverAuth(e, token);
try {
listed = post("/v4/public/browser/list", listBody(xtlink, "0", 0, 20), token);
} catch (V4CallException again) {
if (terminal(again)) {
throw again;
}
}
} else if (terminal(e)) {
throw e;
}
}
JsonObject matched = listed == null ? null : findItem(listed, fileId);
String url = fetchDownloadUrl(xtlink, fileId, token);
JsonObject file = new JsonObject()
.put("file_name", matched == null ? shareLinkInfo.getShareKey() : itemName(matched))
.put("file_id", CtfileXtlink.bareId(fileId))
.put("file_size_bytes", matched == null ? 0 : itemSize(matched))
.put("file_size", matched == null ? "" : String.valueOf(itemSize(matched)))
.put("username", "");
if (matched != null && !itemDate(matched).isBlank()) {
file.put("file_time", itemDate(matched));
}
return new DirectLink(url, file);
}
List<FileInfo> listShare(String shareKey, String folderId, int maxPages) throws Exception {
boolean directory = true;
String xtlink = CtfileXtlink.fromShare(shareKey, shareLinkInfo.getSharePassword(), directory);
if (xtlink == null) {
throw new CtfileException("这个分享标识不能转换成官方 xtlink");
}
String token = accessToken(false);
List<FileInfo> files = new ArrayList<>();
int start = 0;
String apiFolder = folderId == null || folderId.isBlank() || "0".equals(folderId) ? "0" : CtfileXtlink.bareId(folderId);
for (int page = 0; page < maxPages; page++) {
JsonObject body;
try {
body = post("/v4/public/browser/list", listBody(xtlink, apiFolder, start, PAGE_SIZE), token);
} catch (V4CallException e) {
token = recoverAuth(e, token);
body = post("/v4/public/browser/list", listBody(xtlink, apiFolder, start, PAGE_SIZE), token);
}
JsonArray rows = resultsOf(body);
if (rows.isEmpty()) {
return files;
}
for (int i = 0; i < rows.size(); i++) {
if (rows.getValue(i) instanceof JsonObject row) {
FileInfo info = toFileInfo(row, shareLinkInfo, xtlink);
if (info != null) {
files.add(info);
}
}
}
int total = totalOf(body);
start += rows.size();
if (rows.size() < PAGE_SIZE || (total >= 0 && start >= total)) {
return files;
}
}
return files;
}
private String fetchDownloadUrl(String xtlink, String fileId, String token) throws Exception {
JsonObject auth;
try {
auth = post("/v4/public/browser/create-download-auth", authBody(xtlink, CtfileXtlink.prefixedId(fileId, false)), token);
} catch (V4CallException e) {
token = recoverAuth(e, token);
auth = post("/v4/public/browser/create-download-auth", authBody(xtlink, CtfileXtlink.prefixedId(fileId, false)), token);
}
String signature = signatureOf(auth);
if (signature.isBlank()) {
throw new CtfileException("城通没有返回下载签名,可能是密码错误、分享失效或账号没有下载权限");
}
JsonObject fetched;
try {
fetched = post("/v4/public/browser/fetch-url", fetchBody(xtlink, CtfileXtlink.bareId(fileId), signature), token);
} catch (V4CallException e) {
token = recoverAuth(e, token);
fetched = post("/v4/public/browser/fetch-url", fetchBody(xtlink, CtfileXtlink.bareId(fileId), signature), token);
}
String url = downloadUrlOf(fetched);
if (url.isBlank()) {
throw new CtfileException("城通没有返回下载直链");
}
return url;
}
private String recoverAuth(V4CallException error, String currentToken) throws Exception {
if (!error.authenticationFailure()) {
throw error;
}
String refreshed = accessToken(true);
if (refreshed == null || refreshed.isBlank() || refreshed.equals(currentToken)) {
throw error;
}
return refreshed;
}
private String accessToken(boolean forceRefresh) throws Exception {
Credentials credentials = credentials(shareLinkInfo);
if (!credentials.usable()) {
throw new CtfileException(missingAccountMessage());
}
Session session = SESSIONS.computeIfAbsent(credentials.accountKey, key -> new Session());
synchronized (session) {
long now = System.currentTimeMillis();
if ((session.refreshToken == null || session.refreshToken.isBlank()) && credentials.refreshToken != null) {
session.refreshToken = credentials.refreshToken;
}
if ((session.accessToken == null || session.accessToken.isBlank()) && credentials.accessToken != null) {
session.accessToken = credentials.accessToken;
}
if (!forceRefresh && session.accessToken != null && !session.accessToken.isBlank()
&& (session.expiresAtMillis == 0 || session.expiresAtMillis - EXPIRY_SKEW_MILLIS > now)) {
return session.accessToken;
}
if (session.refreshToken == null || session.refreshToken.isBlank()) {
if (session.accessToken != null && !session.accessToken.isBlank() && !forceRefresh) {
session.expiresAtMillis = 0;
return session.accessToken;
}
throw new CtfileException("城通 access token 已失效,且没有可用的 refresh_token。请重新登录后更新配置。");
}
RefreshResult refreshed = refresh(session.refreshToken);
session.accessToken = refreshed.accessToken;
session.expiresAtMillis = now + refreshed.expiresInSeconds * 1000L;
if (refreshed.refreshToken != null && !refreshed.refreshToken.isBlank()
&& !refreshed.refreshToken.equals(session.refreshToken)) {
session.refreshToken = refreshed.refreshToken;
rememberRefreshToken(credentials, refreshed.refreshToken);
} else {
session.refreshToken = refreshed.refreshToken == null || refreshed.refreshToken.isBlank()
? session.refreshToken : refreshed.refreshToken;
}
TokenCache.putToken(credentials.cacheKey(), session.accessToken);
TokenCache.putExpire(credentials.cacheKey(), session.expiresAtMillis);
TokenCache.queueCachedTokenPersist(credentials.cacheKey(), session.accessToken, session.expiresAtMillis);
return session.accessToken;
}
}
private RefreshResult refresh(String refreshToken) throws Exception {
V4CallException first = null;
try {
return readRefresh(post("/v4/user/auth/refresh-token", refreshBody(refreshToken, false), null), refreshToken);
} catch (V4CallException e) {
first = e;
}
try {
return readRefresh(post("/v4/user/auth/refresh-token", refreshBody(refreshToken, true), null), refreshToken);
} catch (V4CallException e) {
throw first.messageKey.contains("invalid_refresh") ? first : e;
}
}
private JsonObject post(String path, JsonObject body, String accessToken) throws Exception {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(API + path))
.timeout(REQUEST_TIMEOUT)
.header("User-Agent", UA)
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.header("X-Client-Type", "native")
.header("X-Client-Version", "5.1.24")
.header("X-Client-Platform", "linux")
.header("X-Client-OS-Version", "6.1.0")
.header("X-Client-Arch", "x64")
.header("X-Client-Captcha", "image,turnstile,altcha,cap")
.POST(HttpRequest.BodyPublishers.ofString(body.encode()));
if (accessToken != null && !accessToken.isBlank()) {
builder.header("Authorization", "Bearer " + accessToken);
}
HttpResponse<String> response;
try {
response = HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CtfileException("城通客户端请求被中断");
} catch (IOException e) {
throw new CtfileException("城通客户端请求失败: " + e.getMessage());
}
String text = response.body() == null ? "" : response.body();
JsonObject json;
try {
json = new JsonObject(text);
} catch (Exception e) {
throw new CtfileException("城通客户端返回了无法识别的响应 (HTTP " + response.statusCode() + ")");
}
int code = CtfileSession.intValue(json.getValue("code"), response.statusCode());
if (code != 200) {
throw new V4CallException(code, json.getString("message", ""), json.getString("message_key", ""));
}
return json;
}
private void rememberRefreshToken(Credentials credentials, String refreshToken) {
if (credentials.auths != null) {
credentials.auths.set("refresh_token", refreshToken);
}
TokenCache.queueCredentialUpdate(credentials.cacheKey(), refreshToken);
try {
Object auths = WebClientVertxInit.get().sharedData().getLocalMap("local").get("auths");
if (auths instanceof JsonObject json) {
for (String type : new String[] {"ct", "ctd"}) {
JsonObject config = json.getJsonObject(type);
if (config != null && config.containsKey("refresh_token")) {
config.put("refresh_token", refreshToken);
}
}
}
} catch (RuntimeException ignored) {
// 单测或未启动服务时没有共享配置,进程内的 TokenCache 仍然保存新令牌。
}
}
static JsonObject listBody(String xtlink, String folderId, int start, int pageSize) {
Object folder = folderId != null && folderId.matches("\\d+") ? Long.parseLong(folderId) : folderId;
return new JsonObject()
.put("xtlink", xtlink)
.put("folder_id", folder)
.put("start", start)
.put("pagesize", pageSize);
}
static JsonObject authBody(String xtlink, String ids) {
return new JsonObject().put("xtlink", xtlink).put("ids", ids);
}
static JsonObject fetchBody(String xtlink, String fileId, String signature) {
return new JsonObject()
.put("file_id", fileId)
.put("download_sign", signature)
.put("xtlink", xtlink)
.put("carrier", 0);
}
static JsonObject refreshBody(String refreshToken, boolean rotate) {
JsonObject body = new JsonObject().put("refresh_token", refreshToken);
if (rotate) {
body.put("rotate_token", true);
}
return body;
}
static String describeFailure(int code, String message, String messageKey) {
String text = message == null ? "" : message;
String key = messageKey == null ? "" : messageKey;
String lower = (text + " " + key).toLowerCase();
if (lower.contains("invalid_refresh") || lower.contains("refresh token") || text.contains("refresh token")) {
return "城通 refresh_token 无效或已过期,请重新登录 pan.ctfile.com 后更新 auths.ct.refresh_token";
}
if (text.contains("扫码") || text.contains("登录保护") || lower.contains("qr") || lower.contains("captcha_required")) {
return "城通账号需要扫码或完成登录保护后,再更新 refresh_token";
}
if (text.contains("锁定") && !text.contains("无效的令牌") && !text.contains("令牌无效")) {
return "城通账号已锁定";
}
if (code == 401 || text.contains("无效的令牌") || text.contains("未登录") || text.contains("令牌无效")) {
return "城通登录令牌无效或账号已锁定";
}
if (code == 404 || text.contains("不存在") || text.contains("失效") || lower.contains("not found")) {
return "分享不存在或已过期";
}
if (text.contains("密码") || lower.contains("passcode") || lower.contains("password")) {
return "访问密码不正确";
}
if (code == 403) {
return "城通拒绝了这次下载" + (text.isBlank() ? "" : "(" + text + ")");
}
return "城通客户端接口返回错误 (code=" + code + ")" + (text.isBlank() ? "" : ":" + text);
}
static FileInfo toFileInfo(JsonObject item, ShareLinkInfo info, String xtlink) {
if (item == null) {
return null;
}
String name = itemName(item);
if (name.isBlank()) {
return null;
}
String key = itemKey(item);
boolean folder = isFolder(item, key);
String password = info.getSharePassword() == null ? "" : info.getSharePassword();
FileInfo fileInfo = new FileInfo()
.setFileName(name)
.setPanType(info.getType())
.setFileId(CtfileXtlink.bareId(key));
String date = itemDate(item);
if (!date.isBlank()) {
fileInfo.setCreateTime(date).setUpdateTime(date);
}
String domain = info.getOtherParam() == null ? "" : String.valueOf(info.getOtherParam().getOrDefault("domainName", ""));
if (folder) {
return fileInfo.setFileType("folder")
.setSize(0L)
.setSizeStr("0B")
.setParserUrl(domain + "/v2/getFileList?url=" + url(info.getShareUrl())
+ "&dirId=" + url(CtfileXtlink.bareId(key))
+ (password.isBlank() ? "" : "&pwd=" + url(password)));
}
long size = itemSize(item);
JsonObject param = new JsonObject()
.put("id", CtfileXtlink.prefixedId(key, false))
.put("pwd", password)
.put("fileName", name)
.put("xtlink", xtlink)
.put("shareKey", info.getShareKey() == null ? "" : info.getShareKey());
String kind = CtfileSession.firstNonBlank(text(item.getValue("icon")), text(item.getValue("ext")), "file");
return fileInfo.setFileType(kind)
.setSize(size)
.setSizeStr(size > 0 ? size + "B" : text(item.getValue("size")))
.setParserUrl(domain + "/v2/redirectUrl/" + info.getType() + "/"
+ CommonUtils.urlBase64Encode(param.encode()));
}
static Credentials credentials(ShareLinkInfo info) {
MultiMap auths = null;
if (info != null && info.getOtherParam() != null && info.getOtherParam().get("auths") instanceof MultiMap map) {
auths = map;
}
String refresh = firstAuth(auths, "refresh_token", "refreshToken");
String access = firstAuth(auths, "token", "authorization", "access_token", "accessToken");
String accountId = firstAuth(auths, "_configId");
if ((refresh == null || refresh.isBlank()) && (access == null || access.isBlank())) {
JsonObject shared = sharedAuth(info == null ? "" : info.getType());
if (shared != null) {
refresh = firstJson(shared, "refresh_token", "refreshToken");
access = firstJson(shared, "token", "authorization", "access_token", "accessToken");
}
}
if (accountId == null || accountId.isBlank()) {
accountId = refresh != null && !refresh.isBlank() ? "refresh" : "access";
}
return new Credentials(auths, accountId, blankToNull(refresh), blankToNull(stripBearer(access)));
}
static void clearSessions() {
SESSIONS.clear();
}
private static JsonObject sharedAuth(String type) {
try {
Object auths = WebClientVertxInit.get().sharedData().getLocalMap("local").get("auths");
if (!(auths instanceof JsonObject json)) {
return null;
}
JsonObject config = type == null ? null : json.getJsonObject(type);
if ((config == null || config.isEmpty()) && "ctd".equalsIgnoreCase(type)) {
config = json.getJsonObject("ct");
}
return config;
} catch (RuntimeException e) {
return null;
}
}
private static RefreshResult readRefresh(JsonObject json, String previous) throws CtfileException {
String token = firstJson(json, "token", "access_token", "accessToken");
JsonObject data = json.getJsonObject("data");
if ((token == null || token.isBlank()) && data != null) {
token = firstJson(data, "token", "access_token", "accessToken");
}
if (token == null || token.isBlank()) {
throw new CtfileException("刷新城通登录状态失败:上游没有返回 access token");
}
String rotated = firstJson(json, "refresh_token", "refreshToken");
if ((rotated == null || rotated.isBlank()) && data != null) {
rotated = firstJson(data, "refresh_token", "refreshToken");
}
int expires = CtfileSession.intValue(json.getValue("expires_in"), -1);
if (expires < 0 && data != null) {
expires = CtfileSession.intValue(data.getValue("expires_in"), 900);
}
if (expires < 0) {
expires = 900;
}
return new RefreshResult(token, rotated == null || rotated.isBlank() ? previous : rotated, expires);
}
private static String signatureOf(JsonObject json) {
JsonObject data = json.getJsonObject("data");
String signature = data == null ? "" : data.getString("download_signature", "");
if (signature.isBlank()) {
signature = json.getString("download_signature", "");
}
return signature;
}
private static String downloadUrlOf(JsonObject json) {
JsonObject data = json.getJsonObject("data");
String url = data == null ? "" : data.getString("download_url", "");
if (url.isBlank() && data != null) {
url = data.getString("url", "");
}
if (url.isBlank()) {
url = json.getString("download_url", "");
}
return url;
}
private static JsonArray resultsOf(JsonObject json) {
JsonObject data = json.getJsonObject("data");
if (data != null && data.getValue("results") instanceof JsonArray rows) {
return rows;
}
if (json.getValue("results") instanceof JsonArray rows) {
return rows;
}
return new JsonArray();
}
private static int totalOf(JsonObject json) {
JsonObject data = json.getJsonObject("data");
if (data == null) {
return -1;
}
int total = CtfileSession.intValue(data.getValue("totalNum"), -1);
return total >= 0 ? total : CtfileSession.intValue(data.getValue("num"), -1);
}
private static JsonObject findItem(JsonObject listed, String fileId) {
String bare = CtfileXtlink.bareId(fileId);
for (int i = 0; i < resultsOf(listed).size(); i++) {
if (!(resultsOf(listed).getValue(i) instanceof JsonObject row)) {
continue;
}
if (bare.equals(CtfileXtlink.bareId(itemKey(row)))) {
return row;
}
}
JsonArray rows = resultsOf(listed);
if (rows.size() == 1 && rows.getValue(0) instanceof JsonObject only && !isFolder(only, itemKey(only))) {
return only;
}
return null;
}
private static boolean isFolder(JsonObject item, String key) {
if (Boolean.TRUE.equals(item.getValue("is_folder"))) {
return true;
}
String type = item.getString("type", "");
String icon = item.getString("icon", "");
String ext = item.getString("ext", "");
return "folder".equalsIgnoreCase(type) || "folder".equalsIgnoreCase(icon) || "folder".equalsIgnoreCase(ext)
|| (key != null && key.startsWith("d"));
}
private static String itemKey(JsonObject item) {
return CtfileSession.firstNonBlank(text(item.getValue("fid")), text(item.getValue("key")), text(item.getValue("id")));
}
private static String itemName(JsonObject item) {
return item.getString("name", "").trim();
}
private static long itemSize(JsonObject item) {
long size = CtfileSession.longValue(item.getValue("size_bytes"), -1);
if (size >= 0) {
return size;
}
return CtfileSession.longValue(item.getValue("size"), 0);
}
private static String itemDate(JsonObject item) {
return CtfileSession.firstNonBlank(text(item.getValue("date")), text(item.getValue("file_time")));
}
private static String shareId(String shareKey) {
if (shareKey == null) {
return "";
}
String[] parts = shareKey.split("-");
return parts.length >= 2 ? parts[1] : "";
}
private static String firstAuth(MultiMap auths, String... keys) {
if (auths == null) {
return null;
}
for (String key : keys) {
String value = auths.get(key);
if (value != null && !value.isBlank()) {
return value.trim();
}
}
return null;
}
private static String firstJson(JsonObject json, String... keys) {
if (json == null) {
return null;
}
for (String key : keys) {
String value = json.getString(key);
if (value != null && !value.isBlank()) {
return value.trim();
}
}
return null;
}
private static String stripBearer(String token) {
if (token == null) {
return null;
}
String value = token.trim();
if (value.regionMatches(true, 0, "Bearer ", 0, 7)) {
return value.substring(7).trim();
}
return value;
}
private static String blankToNull(String value) {
return value == null || value.isBlank() ? null : value;
}
private static String text(Object value) {
return value == null ? "" : value.toString().trim();
}
private static String url(String value) {
return java.net.URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8);
}
static final class Credentials {
final MultiMap auths;
final String accountId;
final String refreshToken;
final String accessToken;
final String accountKey;
Credentials(MultiMap auths, String accountId, String refreshToken, String accessToken) {
this.auths = auths;
this.accountId = accountId;
this.refreshToken = refreshToken;
this.accessToken = accessToken;
this.accountKey = accountId == null ? "default" : accountId;
}
boolean usable() {
return (refreshToken != null && !refreshToken.isBlank()) || (accessToken != null && !accessToken.isBlank());
}
String cacheKey() {
return TokenCache.key("ct", accountKey);
}
}
static final class DirectLink {
final String url;
final JsonObject file;
DirectLink(String url, JsonObject file) {
this.url = url;
this.file = file;
}
}
private static final class Session {
String refreshToken;
String accessToken;
long expiresAtMillis;
}
private static final class RefreshResult {
final String accessToken;
final String refreshToken;
final int expiresInSeconds;
RefreshResult(String accessToken, String refreshToken, int expiresInSeconds) {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.expiresInSeconds = expiresInSeconds;
}
}
static final class V4CallException extends CtfileException {
final int code;
final String messageKey;
V4CallException(int code, String message, String messageKey) {
super(describeFailure(code, message, messageKey));
this.code = code;
this.messageKey = messageKey == null ? "" : messageKey;
}
boolean authenticationFailure() {
return code == 401 || getMessage().contains("令牌") || getMessage().contains("锁定");
}
}
private static boolean terminal(V4CallException error) {
String message = error.getMessage() == null ? "" : error.getMessage();
return message.contains("密码") || message.contains("不存在") || message.contains("已过期") || message.contains("失效");
}
}
@@ -1,71 +0,0 @@
package cn.qaiu.parser.impl;
/**
* 把网页分享 key 转成官方客户端 xtlink。
* 免密是 {@code xturl{userid}-{f|d}{id}[-checksum]},
* 带密码是 {@code xtc{userid}-{f|d}{id}-{checksum}-{password}}。
*/
final class CtfileXtlink {
private CtfileXtlink() {
}
static String fromShare(String shareKey, String password, boolean directory) {
if (shareKey == null || shareKey.isBlank()) {
throw new IllegalArgumentException("分享标识为空,无法生成 xtlink");
}
String key = shareKey.trim();
if (key.startsWith("ctfile://")) {
key = key.substring("ctfile://".length());
}
if (key.startsWith("xturl") || key.startsWith("xtc")) {
return key;
}
if (key.startsWith("t-")) {
return null;
}
String[] parts = key.split("-");
if (parts.length < 2 || parts[0].isBlank() || parts[1].isBlank()) {
throw new IllegalArgumentException("分享标识无法转换成 xtlink: " + shareKey);
}
String userId = parts[0];
String rawId = parts[1];
String checksum = parts.length >= 3 ? parts[2] : "";
if (!rawId.matches("[fd]\\d+")) {
rawId = (directory ? "d" : "f") + rawId;
}
boolean hasPassword = password != null && !password.isBlank();
if (!hasPassword) {
return checksum.isEmpty()
? "xturl" + userId + "-" + rawId
: "xturl" + userId + "-" + rawId + "-" + checksum;
}
if (checksum.isEmpty()) {
return "xtc" + userId + "-" + rawId + "-" + password;
}
return "xtc" + userId + "-" + rawId + "-" + checksum + "-" + password;
}
static String prefixedId(String fileId, boolean directory) {
if (fileId == null || fileId.isBlank()) {
return "";
}
String value = fileId.trim();
if (value.matches("[fd]\\d+")) {
return value;
}
String digits = value.replaceAll("\\D", "");
if (digits.isEmpty()) {
return value;
}
return (directory || value.startsWith("d") ? "d" : "f") + digits;
}
static String bareId(String fileId) {
String prefixed = prefixedId(fileId, false);
if (prefixed.matches("[fd]\\d+")) {
return prefixed.substring(1);
}
return prefixed;
}
}
@@ -2,7 +2,6 @@ package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.FolderPaging;
import cn.qaiu.parser.PanBase;
import cn.qaiu.util.*;
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" +
"={uuid}&extra=2&timestamp={ts}&shareId={shareId}&folderId" +
"={folderId}&offset={offset}&limit={limit}";
/** share/list 每页条数;offset 是从 1 开始的页码。 */
static final int LIST_LIMIT = 60;
"={folderId}&offset=1&limit=60";
private static final MultiMap header;
private static final MultiMap header0;
@@ -496,11 +492,7 @@ public class FjTool extends PanBase {
.setParserUrl(id)
.setPanType(shareLinkInfo.getType());
List<FileInfo> result = new ArrayList<>();
int page = FolderPaging.pageOrFirst(shareLinkInfo);
if (page == 1) {
result.add(fileInfo);
}
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
result.add(fileInfo);
promise.complete(result);
return;
}
@@ -514,101 +506,86 @@ public class FjTool extends PanBase {
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode)
.setTemplateParam("folderId", id)
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
.send().onSuccess(res -> {
JsonArray list;
JsonObject jsonObject;
try {
jsonObject = asJson(res);
JsonObject jsonObject = asJson(res);
log.debug("目录列表: {}", jsonObject.encodePrettily());
list = jsonObject.getJsonArray("list");
} catch (Exception e) {
log.error("解析目录失败: {}", res.bodyAsString());
promise.tryFail("目录解析失败: 响应不是 JSON");
return;
}
if (list == null) {
promise.tryFail("目录解析失败: 响应缺少 list 字段: " + jsonObject);
return;
}
ArrayList<FileInfo> result = new ArrayList<>();
try {
list.forEach(item->{
JsonObject fileJson = (JsonObject) item;
FileInfo fileInfo = new FileInfo();
list.forEach(item->{
JsonObject fileJson = (JsonObject) item;
FileInfo fileInfo = new FileInfo();
// 映射已知字段fileInfo
String fileId = fileJson.getString("fileId");
String userId = fileJson.getString("userId");
// 映射已知字段fileInfo
String fileId = fileJson.getString("fileId");
String userId = fileJson.getString("userId");
// 其他参数
long nowTs2 = System.currentTimeMillis();
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
// 其他参数
long nowTs2 = System.currentTimeMillis();
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
// 回传用到的参数
//"fidEncode", paramJson.getString("fidEncode"))
//"uuid", paramJson.getString("uuid"))
//"ts", paramJson.getString("ts"))
//"auth", paramJson.getString("auth"))
//"shareId", paramJson.getString("shareId"))
JsonObject entries = JsonObject.of(
"fileId", fileId,
"userId", userId,
"fidEncode", fidEncode,
"uuid", uuid,
"ts", tsEncode2,
"auth", auth,
"shareId", shareId);
String param = CommonUtils.urlBase64Encode(entries.encode());
// 回传用到的参数
//"fidEncode", paramJson.getString("fidEncode"))
//"uuid", paramJson.getString("uuid"))
//"ts", paramJson.getString("ts"))
//"auth", paramJson.getString("auth"))
//"shareId", paramJson.getString("shareId"))
JsonObject entries = JsonObject.of(
"fileId", fileId,
"userId", userId,
"fidEncode", fidEncode,
"uuid", uuid,
"ts", tsEncode2,
"auth", auth,
"shareId", shareId);
String param = CommonUtils.urlBase64Encode(entries.encode());
if (fileJson.getInteger("fileType") == 2) {
// 如果是目录
fileInfo.setFileName(fileJson.getString("name"))
.setFileId(fileJson.getString("folderId"))
.setCreateTime(fileJson.getString("updTime"))
.setFileType("folder")
.setSize(0L)
.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))
if (fileJson.getInteger("fileType") == 2) {
// 如果是目录
fileInfo.setFileName(fileJson.getString("name"))
.setFileId(fileJson.getString("folderId"))
.setCreateTime(fileJson.getString("updTime"))
.setFileType("folder")
.setSize(0L)
.setSizeStr("0B")
.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));
// 设置目录解析的URL
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&uuid=%s", getDomainName(),
shareLinkInfo.getShareUrl(), fileJson.getString("folderId"), uuid));
result.add(fileInfo);
});
} catch (Exception e) {
log.error("目录列表条目解析失败: {}", jsonObject, e);
promise.tryFail("目录解析失败: 列表条目格式异常 " + e);
return;
}
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
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())
.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);
}).onFailure(err -> promise.tryFail("目录解析失败: " + err.getMessage()));
});
}
@Override
@@ -2,7 +2,6 @@ package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.FolderPaging;
import cn.qaiu.parser.PanBase;
import cn.qaiu.parser.TokenCache;
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" +
"={uuid}&extra=2&timestamp={ts}&shareId={shareId}&folderId" +
"={folderId}&offset={offset}&limit={limit}";
/** share/list 每页条数;offset 是从 1 开始的页码。 */
static final int LIST_LIMIT = 60;
"={folderId}&offset=1&limit=60";
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
@@ -573,11 +569,7 @@ public class IzTool extends PanBase {
.setParserUrl(id)
.setPanType(shareLinkInfo.getType());
List<FileInfo> result = new ArrayList<>();
int page = FolderPaging.pageOrFirst(shareLinkInfo);
if (page == 1) {
result.add(fileInfo);
}
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
result.add(fileInfo);
promise.complete(result);
return;
}
@@ -594,8 +586,6 @@ public class IzTool extends PanBase {
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode)
.setTemplateParam("folderId", id)
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
.send().onSuccess(res -> {
String resBody = asText(res);
// 检查是否包含 cookie 验证
@@ -610,8 +600,6 @@ public class IzTool extends PanBase {
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode)
.setTemplateParam("folderId", id)
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
.send().onSuccess(res2 -> {
processDirResponse(res2, shareId, promise);
}).onFailure(err -> {
@@ -703,7 +691,6 @@ public class IzTool extends PanBase {
shareLinkInfo.getType(), param));
result.add(fileInfo);
});
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
promise.complete(result);
} catch (Exception e) {
log.error("处理目录响应异常: {}", e.getMessage(), e);
@@ -2,7 +2,6 @@ package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.FolderPaging;
import cn.qaiu.parser.PanBase;
import cn.qaiu.util.AESUtils;
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" +
"={uuid}&extra=2&timestamp={ts}&shareId={shareId}&folderId" +
"={folderId}&offset={offset}&limit={limit}";
/** share/list 每页条数;offset 是从 1 开始的页码。 */
static final int LIST_LIMIT = 60;
"={folderId}&offset=1&limit=60";
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
@@ -516,11 +512,7 @@ public class IzToolWithAuth extends PanBase {
.setParserUrl(id)
.setPanType(shareLinkInfo.getType());
List<FileInfo> result = new ArrayList<>();
int page = FolderPaging.pageOrFirst(shareLinkInfo);
if (page == 1) {
result.add(fileInfo);
}
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
result.add(fileInfo);
promise.complete(result);
return;
}
@@ -573,8 +565,6 @@ public class IzToolWithAuth extends PanBase {
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode)
.setTemplateParam("folderId", id)
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
.send().onSuccess(res -> {
String resBody = asText(res);
// 检查是否包含 cookie 验证
@@ -589,8 +579,6 @@ public class IzToolWithAuth extends PanBase {
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode)
.setTemplateParam("folderId", id)
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
.send().onSuccess(res2 -> {
processDirResponse(res2, shareId, promise);
}).onFailure(err -> {
@@ -683,7 +671,6 @@ public class IzToolWithAuth extends PanBase {
shareLinkInfo.getType(), param));
result.add(fileInfo);
});
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
promise.complete(result);
} catch (Exception 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.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.FolderPaging;
import cn.qaiu.parser.PanBase;
import cn.qaiu.util.*;
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.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.ProxyOptions;
import io.vertx.core.net.ProxyType;
@@ -27,11 +25,9 @@ import java.io.ByteArrayInputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -77,18 +73,6 @@ public class LzTool extends PanBase {
"https://www.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 请求超时 */
private static final long REQUEST_TIMEOUT = 8000;
/** 下载域跳转与二次验证超时,链路更长 */
@@ -743,16 +727,6 @@ public class LzTool extends PanBase {
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) {
if (raw == null) {
return "";
@@ -1101,7 +1075,7 @@ public class LzTool extends PanBase {
private static String originOf(String url, String fallback) {
try {
URL u = new URL(url);
return u.getProtocol() + "://" + u.getHost() + (u.getPort() == -1 ? "" : ":" + u.getPort());
return u.getProtocol() + "://" + u.getHost();
} catch (Exception e) {
return fallback;
}
@@ -1153,14 +1127,6 @@ public class LzTool extends PanBase {
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。 */
private static MultiMap folderListHeaders(String referer) {
MultiMap headers = MultiMap.caseInsensitiveMultiMap();
@@ -1180,77 +1146,18 @@ public class LzTool extends PanBase {
final String sUrl = resolveShareUrl();
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
? LzFolderCursor.decode(FolderPaging.cursor(shareLinkInfo), shareLinkInfo.getShareKey(), page)
: null;
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));
getWithArg1Retry(sUrl, PAGE_HEADERS)
.onSuccess(html -> handleFileListParse(html, pwd, sUrl, listPromise))
.onFailure(listPromise::fail);
return listPromise.future();
}
/** 游标过期(令牌约 10 分钟)或被拒:页码不大时整段重翻,否则让调用方从第 1 页重新加载。 */
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) {
private void handleFileListParse(String html, String pwd, String sUrl, Promise<List<FileInfo>> listPromise) {
if (!isLzFolderShare(sUrl, html)) {
listPromise.fail(baseMsg() + "该链接为蓝奏云文件分享,请使用文件解析接口");
return;
}
if (isAccessRiskPage(html)) {
listPromise.fail(baseMsg() + "蓝奏云返回了访问风控页,不能据此判断分享已失效,请稍后重试");
return;
}
try {
String webpage = extractWebpage(sUrl, html);
if (webpage != null) {
@@ -1262,106 +1169,14 @@ public class LzTool extends PanBase {
}
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) {
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 取参数。 */
private AjaxCall folderAjaxFromJs(String html, String pwd) throws ScriptException, NoSuchMethodException {
String jsText = getJsByPwd(pwd, html, "var urls =window.location.href");
@@ -1398,26 +1213,6 @@ public class LzTool extends PanBase {
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) {
if (html == null || html.isBlank()) {
return false;
@@ -1454,59 +1249,66 @@ public class LzTool extends PanBase {
return u;
}
/**
* 目录页 JS 不渲染 id 为 -1 的占位项(如「***.apk」),这里同样跳过;它仍计入每页 50 条。
* 同一页里重复的 id 只保留第一条。
*/
private List<FileInfo> toFolderFileInfos(List<JsonObject> items) {
List<FileInfo> list = new ArrayList<>();
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
private void handleFileListResponse(String responseBody, Promise<List<FileInfo>> listPromise) {
try {
JsonObject fileListJson = parseLzJson(responseBody);
if (fileListJson == null) {
listPromise.fail(baseMsg() + "目录列表返回非JSON");
return;
}
*/
String id = fileJson.getString("id");
if (id == null || id.isBlank() || LZ_PLACEHOLDER_ID.equals(id) || !seen.add(id)) {
continue;
Integer zt = fileListJson.getInteger("zt");
if (zt == null || zt != 1) {
listPromise.fail(baseMsg() + fileListJson.getString("info"));
return;
}
FileInfo fileInfo = new FileInfo();
String size = fileJson.getString("size");
Long sizeNum = FileSizeConverter.convertToBytes(size);
String panType = shareLinkInfo.getType();
String fileName = fileJson.getString("name_all");
// 构建 base64 参数,用于 /v2/redirectUrl 接口
JsonObject paramJson = new JsonObject()
.put("id", id)
.put("fileName", fileName)
.put("shareKey", shareLinkInfo.getShareKey());
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);
List<FileInfo> list = new ArrayList<>();
fileListJson.getJsonArray("text").forEach(item -> {
/*
{
"icon": "apk",
"t": 0,
"id": "iULV2n4361c",
"name_all": "xx.apk",
"size": "49.8 M",
"time": "2021-03-19",
"duan": "in4361",
"p_ico": 0
}
*/
JsonObject fileJson = (JsonObject) item;
FileInfo fileInfo = new FileInfo();
String size = fileJson.getString("size");
Long sizeNum = FileSizeConverter.convertToBytes(size);
String panType = shareLinkInfo.getType();
String id = fileJson.getString("id");
String fileName = fileJson.getString("name_all");
// 构建 base64 参数,用于 /v2/redirectUrl 接口
JsonObject paramJson = new JsonObject()
.put("id", id)
.put("fileName", fileName)
.put("shareKey", shareLinkInfo.getShareKey());
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
@@ -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,96 +0,0 @@
package cn.qaiu.parser.impl;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import java.util.Base64;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class AltchaV2SolverTest {
private static final String NONCE = "00112233445566778899aabbccddeeff";
private static final String SALT = "0102030405060708090a0b0c0d0e0f10";
@Test
public void pbkdf2MatchesAltchaVector() {
byte[] password = password(NONCE, 7);
byte[] derived = AltchaV2Solver.pbkdf2(password, AltchaV2Solver.decodeHex(SALT, "salt"), 100, 32);
assertEquals("dce8b41d12bd8245a12f9fbca56d1d5db2924c1bfe02b924be69f6d89dc1721b",
AltchaV2Solver.toHex(derived));
}
@Test
public void productionCostMatchesCounterZero() {
byte[] derived = AltchaV2Solver.pbkdf2(password(NONCE, 0),
AltchaV2Solver.decodeHex(SALT, "salt"), 1200, 32);
assertEquals("c24bb34595d0df8688c53e6be3b63e4a0fb0f2d9f732b5c4daebc46fba958bf7",
AltchaV2Solver.toHex(derived));
}
@Test
public void solverFindsPrefixedCounterAndBuildsPayload() {
byte[] derived = AltchaV2Solver.pbkdf2(password(NONCE, 3),
AltchaV2Solver.decodeHex(SALT, "salt"), 50, 32);
String prefix = AltchaV2Solver.toHex(derived).substring(0, 8);
JsonObject challenge = challenge(50, prefix, "sig-test");
AltchaV2Solver.Solution solution = AltchaV2Solver.solve(challenge, 20, 5_000);
assertEquals(3, solution.counter);
assertTrue(solution.derivedKeyHex.startsWith(prefix));
JsonObject payload = new JsonObject(new String(Base64.getDecoder().decode(AltchaV2Solver.payload(challenge, solution))));
assertEquals("sig-test", payload.getJsonObject("challenge").getString("signature"));
assertEquals("PBKDF2/SHA-256", payload.getJsonObject("challenge").getJsonObject("parameters").getString("algorithm"));
assertEquals(3, payload.getJsonObject("solution").getInteger("counter").intValue());
assertEquals(solution.derivedKeyHex, payload.getJsonObject("solution").getString("derivedKey"));
}
@Test
public void impossiblePrefixStopsAtTheCounterCap() {
byte[] beyondCap = AltchaV2Solver.pbkdf2(password(NONCE, 40),
AltchaV2Solver.decodeHex(SALT, "salt"), 20, 32);
JsonObject challenge = challenge(20, AltchaV2Solver.toHex(beyondCap).substring(0, 8), "sig");
try {
AltchaV2Solver.solve(challenge, 8, 5_000);
fail("expected the search to stop");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("超时"));
}
}
@Test
public void rejectsCostAboveTheSafetyCap() {
JsonObject challenge = challenge(AltchaV2Solver.MAX_COST + 1, "00", "sig");
try {
AltchaV2Solver.solve(challenge, 1, 1_000);
fail("expected cost to be rejected");
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("cost"));
}
}
private static JsonObject challenge(int cost, String keyPrefix, String signature) {
return new JsonObject()
.put("parameters", new JsonObject()
.put("algorithm", "PBKDF2/SHA-256")
.put("cost", cost)
.put("keyLength", 32)
.put("nonce", NONCE)
.put("salt", SALT)
.put("keyPrefix", keyPrefix))
.put("signature", signature);
}
private static byte[] password(String nonceHex, int counter) {
byte[] nonce = AltchaV2Solver.decodeHex(nonceHex, "nonce");
byte[] password = new byte[nonce.length + 4];
System.arraycopy(nonce, 0, password, 0, nonce.length);
password[nonce.length] = (byte) (counter >>> 24);
password[nonce.length + 1] = (byte) (counter >>> 16);
password[nonce.length + 2] = (byte) (counter >>> 8);
password[nonce.length + 3] = (byte) counter;
return password;
}
}
@@ -1,274 +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.ParserCreate;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* 城通真实联调。默认不跑:
* mvn -pl parser -DskipTests=false -Dctfile.live=true -Dtest=CtToolLiveTest test
*/
public class CtToolLiveTest {
private static final String FREE_FILE = "https://474b.com/file/4015376-131945810";
private static final String PASSWORD_FILE =
"https://url94.ctfile.com/f/64115194-17569800420720-06c697?p=7609";
private static final String PASSWORD_FILE_WITHOUT_PASSWORD =
"https://url94.ctfile.com/f/64115194-17569800420720-06c697";
private static final String PASSWORD_DIR =
"https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609";
private static final String PASSWORD_FILE_WRONG =
"https://url94.ctfile.com/f/64115194-17569800420720-06c697?p=0000";
private static Vertx vertx;
@AfterClass
public static void tearDown() throws Exception {
CtfileSession.clearCachedPasses();
if (vertx != null) {
CtTool.shutdownWorkerExecutor();
vertx.close().toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS);
}
}
@Test
public void freeFileDownloadsRealPdfBytes() throws Exception {
liveOnly();
CtTool tool = tool(FREE_FILE);
String url = tool.parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
FileInfo info = (FileInfo) tool.getShareLinkInfo().getOtherParam().get("fileInfo");
assertNotNull(info);
assertTrue(info.getFileName().endsWith(".pdf"));
assertTrue(info.getSize() > 1000);
assertTrue(url.startsWith("https://"));
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpResponse<byte[]> head = client.send(HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(30))
.header("Range", "bytes=0-15")
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
assertTrue("head status " + head.statusCode(), head.statusCode() == 206 || head.statusCode() == 200);
String magic = new String(head.body(), 0, Math.min(5, head.body().length), StandardCharsets.ISO_8859_1);
assertEquals("%PDF-", magic);
String range = head.headers().firstValue("content-range").orElse("");
String length = head.headers().firstValue("content-length").orElse("");
assertTrue(range.endsWith("/" + info.getSize()) || length.equals(String.valueOf(info.getSize()))
|| range.contains("/" + info.getSize()));
long size = info.getSize();
HttpResponse<byte[]> tail = client.send(HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(30))
.header("Range", "bytes=" + Math.max(0, size - 20) + "-" + (size - 1))
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
String ending = new String(tail.body(), StandardCharsets.ISO_8859_1);
assertTrue(ending.contains("%%EOF"));
}
@Test
public void sameSessionListsParentDirectory() throws Exception {
liveOnly();
ShareLinkInfo info = ParserCreate.fromShareUrl(FREE_FILE).getShareLinkInfo();
try (CtfileSession session = CtfileSession.open(info)) {
JsonObject resource = session.loadResource("file", info.getShareKey(),
CtfileSession.ShareTarget.from(info), "", "");
JsonObject file = CtfileSession.dataOf(resource).getJsonObject("file");
String fileDir = file.getString("file_dir", "");
int marker = fileDir.indexOf("/d/");
assertTrue(fileDir, marker >= 0);
String dirId = fileDir.substring(marker + 3);
int query = dirId.indexOf('?');
if (query >= 0) {
dirId = dirId.substring(0, query);
}
JsonObject listing = session.listing("dir", dirId, new CtfileSession.ShareTarget("0", "", "0"),
"", resource, 0, 20);
JsonArray rows = CtfileSession.rowsOf(listing);
assertTrue(rows.size() > 0);
ShareLinkInfo directory = ShareLinkInfo.newBuilder()
.type("ctd")
.panName("城通网盘-目录")
.shareKey(dirId)
.shareUrl("https://474b.com/d/" + dirId)
.build();
directory.getOtherParam().put("domainName", "https://nfd.example");
int named = 0;
for (int i = 0; i < rows.size(); i++) {
FileInfo item = CtTool.toFileInfo(rows.getJsonObject(i), directory);
if (item != null && item.getFileName() != null && !item.getFileName().isBlank()) {
named++;
assertNotNull(item.getParserUrl());
}
}
assertTrue(named > 0);
}
}
@Test
public void passwordFileDownloadsAnonymously() throws Exception {
liveOnly();
CtTool tool = tool(PASSWORD_FILE);
String url = tool.parse().toCompletionStage().toCompletableFuture().get(120, TimeUnit.SECONDS);
FileInfo info = (FileInfo) tool.getShareLinkInfo().getOtherParam().get("fileInfo");
assertEquals("欢迎使用微盘.pdf", info.getFileName());
assertEquals(Long.valueOf(4005749L), info.getSize());
byte[] body = download(url);
assertEquals(4005749, body.length);
assertTrue(new String(body, 0, 5, StandardCharsets.ISO_8859_1).startsWith("%PDF-"));
assertTrue(new String(body, body.length - 16, 16, StandardCharsets.ISO_8859_1).contains("%%EOF"));
assertEquals("cce8357689762fd1acd1f73fcd7e83d62b4e9bcee6fccf0c9b8f46d26ee74902", sha256(body));
}
@Test
public void passwordDirectoryListsAndDownloadsZipAnonymously() throws Exception {
liveOnly();
CtTool directory = tool(PASSWORD_DIR);
List<FileInfo> files = directory.parseFileList().toCompletionStage().toCompletableFuture()
.get(120, TimeUnit.SECONDS);
assertEquals(3, files.size());
FileInfo zip = null;
for (FileInfo file : files) {
assertNotNull(file.getParserUrl());
assertTrue(file.getParserUrl().contains("pwd=7609") || decodedParam(file).getString("pwd").equals("7609"));
if ("osm_model_20260602_153158.zip".equals(file.getFileName())) {
zip = file;
}
}
assertNotNull(zip);
assertEquals(Long.valueOf(158842L), zip.getSize());
ShareLinkInfo child = ShareLinkInfo.newBuilder()
.type("ct")
.panName("城通网盘")
.shareKey("pending")
.shareUrl("https://ctfile.com/file/pending")
.build();
child.getOtherParam().put("paramJson", decodedParam(zip));
child.getOtherParam().put("domainName", "https://nfd.example");
CtTool downloader = new CtTool(child);
String url = downloader.parseById().toCompletionStage().toCompletableFuture().get(120, TimeUnit.SECONDS);
byte[] body = download(url);
assertEquals(158842, body.length);
assertEquals('P', (char) body[0]);
assertEquals('K', (char) body[1]);
int entries = 0;
try (ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(body))) {
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
byte[] ignored = zipIn.readAllBytes();
assertTrue(entry.getName() != null);
assertTrue(ignored.length >= 0);
zipIn.closeEntry();
entries++;
}
}
assertTrue(entries > 0);
}
@Test
public void missingPasswordAndMissingShareStayDistinct() throws Exception {
liveOnly();
String withoutPassword = failure(tool(PASSWORD_FILE_WITHOUT_PASSWORD).parse());
assertTrue(withoutPassword, withoutPassword.contains("需要访问密码"));
assertFalse(withoutPassword, withoutPassword.contains("未配置城通账号"));
String wrongPassword = failure(tool(PASSWORD_FILE_WRONG).parse());
assertTrue(wrongPassword, wrongPassword.contains("访问密码不正确"));
assertFalse(wrongPassword, wrongPassword.contains("未配置城通账号"));
String missingFile = failure(tool("https://474b.com/file/4015376-1").parse());
assertTrue(missingFile, missingFile.contains("不存在或已过期"));
String missingOwner = failure(tool("https://474b.com/file/0-0").parse());
assertTrue(missingOwner, missingOwner.contains("不存在或已过期"));
}
private static JsonObject decodedParam(FileInfo file) {
String url = file.getParserUrl();
return new JsonObject(decodeUrlBase64(url.substring(url.lastIndexOf('/') + 1)));
}
private static String decodeUrlBase64(String value) {
String padded = value;
int mod = padded.length() % 4;
if (mod != 0) {
padded += "=".repeat(4 - mod);
}
return new String(java.util.Base64.getUrlDecoder().decode(padded), StandardCharsets.UTF_8);
}
private static byte[] download(String url) throws Exception {
HttpResponse<byte[]> response = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(20))
.followRedirects(HttpClient.Redirect.NORMAL)
.build()
.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(120)).GET().build(),
HttpResponse.BodyHandlers.ofByteArray());
assertEquals(200, response.statusCode());
return response.body();
}
private static String sha256(byte[] body) throws Exception {
byte[] digest = MessageDigest.getInstance("SHA-256").digest(body);
StringBuilder hex = new StringBuilder();
for (byte value : digest) {
hex.append(String.format("%02x", value));
}
return hex.toString();
}
private static void liveOnly() {
Assume.assumeTrue("set -Dctfile.live=true to call ctfile", Boolean.getBoolean("ctfile.live"));
if (vertx == null) {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
}
}
private static CtTool tool(String url) {
return (CtTool) ParserCreate.fromShareUrl(url).createTool();
}
private static String failure(io.vertx.core.Future<?> future) throws Exception {
try {
future.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
return "";
} catch (Exception e) {
Throwable current = e;
StringBuilder message = new StringBuilder();
while (current != null) {
if (current.getMessage() != null) {
message.append(current.getMessage()).append('\n');
}
current = current.getCause();
}
if (message.length() == 0) {
throw e;
}
return message.toString();
}
}
}
@@ -1,157 +0,0 @@
package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.impl.CtfileSession.Decision;
import cn.qaiu.parser.impl.CtfileSession.Kind;
import cn.qaiu.parser.impl.CtfileSession.ShareTarget;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CtfileResponseTest {
@Test
public void classifiesNotFoundInvalidPasswordAndCaptcha() {
Decision missing = CtfileSession.classify(json(404, null, "File was not found."), 404, "");
assertEquals(Kind.NOT_FOUND, missing.kind);
assertTrue(missing.message.contains("不存在或已过期"));
assertFalse(missing.message.contains("密码"));
Decision unsigned = CtfileSession.classify(json(403, null, "Unsigned file link is not accepted."), 403, "");
assertEquals(Kind.INVALID, unsigned.kind);
Decision needPassword = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"captcha_type\":\"turnstile\",\"capabilities\":{\"passcodeRequired\":true}},"
+ "\"msg\":\"Share passcode is required.\"}"), 423, "");
assertEquals(Kind.NEED_PASSWORD, needPassword.kind);
assertTrue(needPassword.message.contains("需要访问密码"));
Decision wrong = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"passcode_incorrect\",\"captcha_type\":\"turnstile\","
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"incorrect\"}"), 423, "7609");
assertEquals(Kind.BAD_PASSWORD, wrong.kind);
Decision turnstile = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"turnstile\","
+ "\"capabilities\":{\"passcodeRequired\":true,\"ownerId\":64115194}},"
+ "\"msg\":\"Share passcode needs a new human check.\"}"), 423, "7609");
assertEquals(Kind.TURNSTILE, turnstile.kind);
assertEquals("64115194", turnstile.ownerId);
assertTrue(turnstile.message.contains("Turnstile"));
assertFalse(turnstile.message.contains("密码"));
Decision altcha = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"altcha\","
+ "\"capabilities\":{\"passcodeRequired\":false,\"ownerId\":4015376}},"
+ "\"msg\":\"Share access needs a human check.\"}"), 423, "");
assertEquals(Kind.ALTCHA, altcha.kind);
assertEquals("4015376", altcha.ownerId);
Decision ok = CtfileSession.classify(new JsonObject(
"{\"code\":200,\"data\":{\"access_pass\":\"v1.aaa.bbb\",\"capabilities\":{\"ownerId\":4015376}}}"), 200, "");
assertEquals(Kind.OK, ok.kind);
assertEquals("v1.aaa.bbb", ok.accessPass);
Decision labeledTurnstile = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"turnstile\","
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"Share passcode needs a new human check.\"}"),
423, "pw");
assertTrue(CtfileSession.shouldSolveAltcha(labeledTurnstile));
assertFalse(CtfileSession.shouldSolveAltcha(needPassword));
Decision wrongAfterAltcha = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"passcode_incorrect\",\"captcha_type\":\"turnstile\","
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"Share passcode is incorrect.\"}"),
423, "0000");
assertEquals(Kind.BAD_PASSWORD, wrongAfterAltcha.kind);
assertFalse(CtfileSession.shouldSolveAltcha(wrongAfterAltcha));
ShareLinkInfo passwordShare = ShareLinkInfo.newBuilder()
.type("ct")
.shareKey("11-22-ab")
.sharePassword("pw")
.shareUrl("https://example.test/f/11-22-ab?p=pw")
.build();
assertFalse(CtTool.requiresV4(passwordShare));
passwordShare.getOtherParam().put("ctV4FileId", "f22");
assertTrue(CtTool.requiresV4(passwordShare));
}
@Test
public void resourceQueryKeepsTokensAndEncodesThem() {
Map<String, String> query = CtfileSession.resourceQuery("file", "4015376-131945810",
new ShareTarget("0", "", "0"), "7609", "a+b/c=", "turn stile", "v1.aaa.bbb");
String form = CtfileSession.form(query);
assertTrue(form.contains("kind=file"));
assertTrue(form.contains("passcode=7609"));
assertTrue(form.contains("altcha_token=a%2Bb%2Fc%3D"));
assertTrue(form.contains("turnstile_token=turn+stile") || form.contains("turnstile_token=turn%20stile"));
assertTrue(form.contains("access_pass=v1.aaa.bbb"));
}
@Test
public void listingRowBecomesFileAndFolderLinks() {
ShareLinkInfo info = ShareLinkInfo.newBuilder()
.type("ctd")
.panName("城通网盘-目录")
.shareKey("64115194-164803691-48508c")
.sharePassword("7609")
.shareUrl("https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609")
.build();
info.getOtherParam().put("domainName", "https://nfd.example");
FileInfo folder = CtTool.toFileInfo(new JsonObject()
.put("kind", "folder")
.put("name", "2022")
.put("folderId", 54597713)
.put("folderKey", "bf0603")
.put("date", "2023-02-22"), info);
assertEquals("folder", folder.getFileType());
assertTrue(folder.getParserUrl().contains("dirId="));
assertTrue(folder.getParserUrl().contains("54597713"));
assertTrue(folder.getParserUrl().contains("pwd=7609"));
FileInfo file = CtTool.toFileInfo(new JsonObject()
.put("kind", "file")
.put("name", "notes.pdf")
.put("href", "#/f/t-token")
.put("fileId", 415670738)
.put("extension", "pdf")
.put("size", "1 MB")
.put("size_bytes", 1048576)
.put("date", "2019-12-31"), info);
assertEquals("t-token", fileId(file));
assertEquals(Long.valueOf(1048576L), file.getSize());
assertEquals("pdf", file.getFileType());
assertTrue(file.getParserUrl().startsWith("https://nfd.example/v2/redirectUrl/ctd/"));
}
private static JsonObject json(int code, JsonObject data, String message) {
JsonObject body = new JsonObject().put("code", code).put("msg", message);
if (data != null) {
body.put("data", data);
}
return body;
}
private static String fileId(FileInfo file) {
String url = file.getParserUrl();
String encoded = url.substring(url.lastIndexOf('/') + 1);
return new JsonObject(decodeUrlBase64(encoded)).getString("id");
}
private static String decodeUrlBase64(String value) {
String padded = value;
int mod = padded.length() % 4;
if (mod != 0) {
padded += "=".repeat(4 - mod);
}
byte[] bytes = java.util.Base64.getUrlDecoder().decode(padded);
return new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
}
}
@@ -1,133 +0,0 @@
package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.impl.CtfileV4Client.V4CallException;
import io.vertx.core.MultiMap;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class CtfileV4Test {
private static final String FILE_LINK = "xtc11-f22-ab-pw";
private static final String DIR_LINK = "xtc11-d33-cd-pw";
@Test
public void webShareBecomesXtlink() {
assertEquals(FILE_LINK, CtfileXtlink.fromShare("11-22-ab", "pw", false));
assertEquals(DIR_LINK, CtfileXtlink.fromShare("11-33-cd", "pw", true));
assertEquals("xturl44-f55", CtfileXtlink.fromShare("44-55", "", false));
assertEquals("xturl11-d33-cd", CtfileXtlink.fromShare("11-33-cd", null, true));
assertEquals("xtc1-d2-ab-pw", CtfileXtlink.fromShare("xtc1-d2-ab-pw", "other", true));
assertNull(CtfileXtlink.fromShare("t-signed", "pw", true));
assertEquals("f22", CtfileXtlink.prefixedId("22", false));
assertEquals("22", CtfileXtlink.bareId("f22"));
}
@Test
public void requestBodiesMatchTheClientProtocol() {
JsonObject list = CtfileV4Client.listBody(DIR_LINK, "33", 1, 2);
assertEquals(DIR_LINK, list.getString("xtlink"));
assertEquals(33L, list.getLong("folder_id").longValue());
assertEquals(1, list.getInteger("start").intValue());
assertEquals(2, list.getInteger("pagesize").intValue());
JsonObject auth = CtfileV4Client.authBody(FILE_LINK, "f22");
assertEquals("f22", auth.getString("ids"));
JsonObject fetch = CtfileV4Client.fetchBody(FILE_LINK, "22", "sig");
assertEquals("22", fetch.getString("file_id"));
assertEquals("sig", fetch.getString("download_sign"));
assertEquals(0, fetch.getInteger("carrier").intValue());
assertFalse(CtfileV4Client.refreshBody("rt", false).containsKey("rotate_token"));
assertTrue(CtfileV4Client.refreshBody("rt", true).getBoolean("rotate_token"));
}
@Test
public void errorCodesStaySpecific() {
assertTrue(CtfileV4Client.describeFailure(401, "无效或过期的refresh token", "api.auth.invalid_refresh_token")
.contains("refresh_token 无效或已过期"));
assertTrue(CtfileV4Client.describeFailure(401, "无效的令牌或账户已锁定", "").contains("登录令牌无效或账号已锁定"));
assertEquals("城通账号已锁定", CtfileV4Client.describeFailure(401, "账户已锁定", ""));
assertEquals("访问密码不正确", CtfileV4Client.describeFailure(403, "访问密码不正确", "api.passcode"));
assertTrue(CtfileV4Client.describeFailure(404, "分享不存在", "").contains("不存在或已过期"));
assertTrue(CtfileV4Client.describeFailure(401, "请扫码完成登录保护", "qr_required").contains("扫码"));
V4CallException invalid = new V4CallException(401, "无效的令牌或账户已锁定", "");
assertTrue(invalid.authenticationFailure());
assertFalse(new V4CallException(403, "访问密码不正确", "passcode").authenticationFailure());
}
@Test
public void listRowBecomesDownloadParamWithXtlink() {
ShareLinkInfo info = ShareLinkInfo.newBuilder()
.type("ctd")
.panName("城通网盘-目录")
.shareKey("11-33-cd")
.sharePassword("pw")
.shareUrl("https://example.test/d/11-33-cd?p=pw")
.build();
info.getOtherParam().put("domainName", "https://nfd.example");
FileInfo file = CtfileV4Client.toFileInfo(new JsonObject()
.put("key", "f22")
.put("name", "notes.pdf")
.put("icon", "pdf")
.put("size", 12)
.put("date", "2024-01-02"), info, DIR_LINK);
assertEquals("notes.pdf", file.getFileName());
assertEquals(Long.valueOf(12L), file.getSize());
assertTrue(file.getParserUrl().contains("/v2/redirectUrl/ctd/"));
JsonObject param = new JsonObject(decode(file.getParserUrl().substring(file.getParserUrl().lastIndexOf('/') + 1)));
assertEquals("f22", param.getString("id"));
assertEquals(DIR_LINK, param.getString("xtlink"));
assertEquals("pw", param.getString("pwd"));
ShareLinkInfo download = ShareLinkInfo.newBuilder().type("ctd").sharePassword("").build();
assertTrue(CtTool.applyFileParam(download, param));
assertEquals("f22", download.getOtherParam().get("ctV4FileId"));
assertEquals("11-33-cd", download.getShareKey());
FileInfo folder = CtfileV4Client.toFileInfo(new JsonObject()
.put("fid", "d33")
.put("name", "2022")
.put("is_folder", true), info, DIR_LINK);
assertEquals("folder", folder.getFileType());
assertTrue(folder.getParserUrl().contains("dirId=33"));
assertTrue(folder.getParserUrl().contains("pwd=pw"));
}
@Test
public void credentialsComeFromAuthsAndDoNotTreatSharePasswordAsLogin() {
ShareLinkInfo info = ShareLinkInfo.newBuilder()
.type("ct")
.shareKey("11-22-ab")
.sharePassword("pw")
.build();
assertFalse(CtfileV4Client.hasCredentials(info));
MultiMap auths = MultiMap.caseInsensitiveMultiMap();
auths.set("refresh_token", "refresh-value");
auths.set("authorization", "Bearer access-value");
auths.set("_configId", "home");
info.getOtherParam().put("auths", auths);
CtfileV4Client.Credentials credentials = CtfileV4Client.credentials(info);
assertEquals("refresh-value", credentials.refreshToken);
assertEquals("access-value", credentials.accessToken);
assertTrue(credentials.usable());
assertTrue(CtfileV4Client.missingAccountMessage().contains("auths.ct.refresh_token"));
}
private static String decode(String value) {
String padded = value;
int mod = padded.length() % 4;
if (mod != 0) {
padded += "=".repeat(4 - mod);
}
return new String(java.util.Base64.getUrlDecoder().decode(padded), java.nio.charset.StandardCharsets.UTF_8);
}
}
@@ -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,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.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
@@ -170,55 +167,6 @@ public class LzToolShareUrlTest {
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
public void missingAjaxTargetStillPutsApifileBeforeWwww() {
List<String> origins = LzTool.fileAjaxOrigins("https://www.lanzoux.com/ihLkw1gezutg", null);
+1 -1
View File
@@ -17,7 +17,7 @@
</modules>
<properties>
<revision>0.4.12</revision>
<revision>0.4.10</revision>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "nfd-web",
"version": "0.4.12",
"version": "0.4.10",
"private": true,
"scripts": {
"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:no-compress": "node scripts/sync-version.js && vue-cli-service build",
"lint": "vue-cli-service lint",
"test": "node --test src/utils/batchTreeCollect.spec.js src/utils/folderPaging.spec.js"
"test": "node --test src/utils/batchTreeCollect.spec.js"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.1",
+18 -139
View File
@@ -292,29 +292,6 @@
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;
}
</style>
</head>
<body>
@@ -432,98 +409,6 @@
};
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;
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 || ''}`;
}
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 && entries.some(e => e.isIntersecting)) loadMore();
}).observe(moreEl);
}
// DOM 元素
const breadcrumbEl = document.getElementById('breadcrumb');
const fileGridEl = document.getElementById('file-grid');
@@ -533,7 +418,6 @@
// 初始化
document.addEventListener('DOMContentLoaded', () => {
fileGridEl.insertAdjacentElement('afterend', moreEl);
renderBreadcrumb();
fetchFileList(currentDir.url);
@@ -574,9 +458,6 @@
// 获取文件列表
async function fetchFileList(url) {
const seq = ++loadSeq;
more = null;
renderMore();
try {
// 显示加载状态
fileGridEl.innerHTML = `
@@ -585,15 +466,18 @@
</div>
`;
const pageUrl = toPageUrl(url, 1);
const data = await fetchJson(pageUrl || url);
if (seq !== loadSeq) return;
const page = readPage(data.data);
renderFileList(page.list);
more = pageUrl && page.hasMore ? { listUrl: url, nextPage: page.nextPage, nextCursor: page.nextCursor } : null;
renderMore();
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.code === 200 && data.success) {
renderFileList(data.data);
} else {
throw new Error(data.msg || '获取文件列表失败');
}
} catch (error) {
if (seq !== loadSeq) return;
console.error('获取文件列表失败:', error);
fileGridEl.innerHTML = `
<div class="empty-state">
@@ -606,15 +490,10 @@
}
// 渲染文件列表
function renderFileList(files, append = false) {
if (!append) {
fileGridEl.innerHTML = '';
seenKeys = new Set();
folderCount = 0;
fileCount = 0;
}
function renderFileList(files) {
fileGridEl.innerHTML = '';
if (!append && (!files || files.length === 0)) {
if (!files || files.length === 0) {
fileGridEl.innerHTML = `
<div class="empty-state">
<i class="fas fa-folder-open"></i>
@@ -627,10 +506,10 @@
return;
}
(files || []).forEach(file => {
const key = fileKey(file);
if (seenKeys.has(key)) return;
seenKeys.add(key);
let folderCount = 0;
let fileCount = 0;
files.forEach(file => {
const item = document.createElement('div');
const metaText = fileMetaText(file);
+10 -188
View File
@@ -19,7 +19,7 @@
<div class="file-grid" v-loading="loading">
<div
v-for="file in currentFileList"
:key="fileKey(file)"
:key="file.fileName"
class="file-item"
:class="[getFileTypeClass(file), { 'selected': batchMode && isFileSelected(file) }]"
@click="batchMode ? onBatchClick(file) : handleFileClick(file)"
@@ -42,12 +42,6 @@
<p>暂无文件或文件夹</p>
</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 -->
<div v-if="batchMode" class="action-bar batch-action-bar">
<div class="batch-left">
@@ -461,7 +455,6 @@ import fileTypeUtils from '@/utils/fileTypeUtils'
import DownloadDialog from '@/components/DownloadDialog.vue'
import { testConnection, autoDetect, addDownload, batchAddDownload, getConfig, saveConfig } from '@/utils/downloaderService'
import batchTreeCollect from '@/utils/batchTreeCollect'
import folderPaging from '@/utils/folderPaging'
import { openNoReferrer } from '@/utils/openNoReferrer'
const {
@@ -471,7 +464,6 @@ const {
uniqueFiles,
collectFolderFiles
} = batchTreeCollect
const { toPageUrl, readPage, appendUnique, nextState, makeMoreNode, isMoreNode } = folderPaging
export default {
name: 'DirectoryTree',
@@ -481,11 +473,6 @@ export default {
type: Array,
default: () => []
},
// 根目录分页信息(/v2/getFileListPage 的返回),null 表示不分页
rootPageInfo: {
type: Object,
default: null
},
shareUrl: {
type: String,
required: true
@@ -514,10 +501,6 @@ export default {
loading: false,
pathStack: [{ name: '全部文件', url: '' }],
currentFileList: [],
// 当前窗格目录的下一页状态;null 表示已全部加载
paneMore: null,
rootMore: null,
rootExtra: [],
fileDialogVisible: false,
selectedFile: null,
isDarkTheme: false,
@@ -536,8 +519,7 @@ export default {
treeProps: {
label: 'fileName',
children: 'children',
isLeaf: 'isLeaf',
disabled: 'disabled'
isLeaf: 'isLeaf'
},
isMobile: false,
// 批量下载相关
@@ -588,42 +570,24 @@ export default {
}
},
watch: {
paneMore() {
this.$nextTick(() => this.observeLoadMore())
},
viewMode() {
this.$nextTick(() => this.observeLoadMore())
},
fileList: {
immediate: true,
handler(newList) {
this.rootExtra = []
this.rootMore = nextState(this.buildApiUrl(), readPage(this.rootPageInfo || []))
this.treeMoreFolders = new Set()
const children = (newList || []).map(item => normalizeTreeItem(item))
if (this.rootMore) {
children.push(makeMoreNode('root', { ...this.rootMore }))
this.treeMoreFolders.add('root')
}
// 根节点children为当前目录下所有文件/文件夹
this.treeData = [
{
id: 'root',
fileName: '全部文件',
fileType: 'folder',
children,
children: (newList || []).map(item => normalizeTreeItem(item)),
isLeaf: false
}
]
this.pathStack = [{ name: '全部文件', url: '' }]
this.currentFileList = newList
this.paneMore = this.rootMore
}
}
},
created() {
this.treeMoreFolders = this.treeMoreFolders || new Set()
this._paneLoadSeq = 0
this.resetTreeCollectState()
},
methods: {
@@ -658,20 +622,9 @@ export default {
if (node.level === 0) {
resolve((this.treeData[0]?.children || []).map(item => normalizeTreeItem(item)))
} else if (node.data.fileType === 'folder' && node.data.parserUrl) {
const listUrl = this.withAuth(node.data.parserUrl)
const pageUrl = toPageUrl(listUrl, 1)
axios.get(pageUrl || listUrl, { headers: this.apiKeyHeaders() }).then(res => {
axios.get(this.withAuth(node.data.parserUrl), { headers: this.apiKeyHeaders() }).then(res => {
if (res.data.code === 200) {
const page = readPage(res.data.data)
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)
}
const children = (res.data.data || []).map(item => normalizeTreeItem(item))
resolve(children)
} else {
this.$message.error(res.data.msg || '获取子节点失败')
@@ -687,93 +640,8 @@ export default {
}
},
onNodeClick(data) {
if (isMoreNode(data)) {
this.loadMoreTreeNode(data)
return
}
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') 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.paneMore = next
} 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
try {
const page = await this.fetchPage(state)
const parentKey = getTreeNodeId(parent.data) || 'root'
const existing = new Set((parent.childNodes || []).map(n => getTreeNodeId(n.data)))
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)
}
const next = nextState(state.listUrl, page)
if (next) {
tree.append(makeMoreNode(parentKey, next), parent)
} else {
this.treeMoreFolders.delete(parentKey)
}
} catch (error) {
state.loading = false
this.$message.error(`${error.response?.data?.msg || error.message || '加载下一页失败'},可再次点击「加载更多」重试`)
}
},
// 处理文件点击
handleFileClick(file) {
if (file.fileType === 'folder') {
@@ -794,19 +662,14 @@ export default {
try {
this.loading = true
const folderUrl = this.withAuth(folder.parserUrl)
const seq = ++this._paneLoadSeq
const pageUrl = toPageUrl(folderUrl, 1)
const response = await axios.get(pageUrl || folderUrl, { headers: this.apiKeyHeaders() })
if (seq !== this._paneLoadSeq) return
const response = await axios.get(folderUrl, { headers: this.apiKeyHeaders() })
if (response.data.code === 200) {
const newDir = {
url: folderUrl,
name: folder.fileName || '未命名文件夹'
}
const page = readPage(response.data.data)
this.pathStack.push(newDir)
this.currentFileList = page.list
this.paneMore = pageUrl ? nextState(folderUrl, page) : null
this.currentFileList = response.data.data || []
} else {
this.$message.error(response.data.msg || '获取文件夹内容失败')
}
@@ -830,23 +693,15 @@ export default {
},
async loadCurrentDirectory() {
const currentDir = this.pathStack[this.pathStack.length - 1]
const seq = ++this._paneLoadSeq
if (!currentDir.url) {
this.currentFileList = appendUnique(this.fileList, this.rootExtra)
this.paneMore = this.rootMore
this.currentFileList = this.fileList
return
}
this.paneMore = null
try {
this.loading = true
const listUrl = this.withAuth(currentDir.url)
const pageUrl = toPageUrl(listUrl, 1)
const response = await axios.get(pageUrl || listUrl, { headers: this.apiKeyHeaders() })
if (seq !== this._paneLoadSeq) return
const response = await axios.get(this.withAuth(currentDir.url), { headers: this.apiKeyHeaders() })
if (response.data.code === 200) {
const page = readPage(response.data.data)
this.currentFileList = page.list
this.paneMore = pageUrl ? nextState(listUrl, page) : null
this.currentFileList = response.data.data || []
} else {
this.$message.error(response.data.msg || '加载目录失败')
}
@@ -1280,9 +1135,6 @@ export default {
visitedKeys: this._visitedInCollect
})
this.syncSelectedFilesFromTree(ctx.files)
if ([...this._visitedInCollect].some(key => this.treeMoreFolders.has(key))) {
this.$message.warning('部分文件夹还有未加载的分页,只勾选了已加载的文件;请先点击「加载更多」后再勾选')
}
if (ctx.depthExceeded) {
this.$message.warning(
`已达到最大展开深度(${this.effectiveBatchMaxDepth} 层),部分深层文件未勾选`
@@ -1324,9 +1176,6 @@ export default {
},
selectAll() {
this.selectedFiles = this.currentFileList.filter(f => this.isDownloadableFile(f))
if (this.paneMore) {
this.$message.warning(`仅选中已加载的 ${this.selectedFiles.length} 个文件,当前目录还有未加载的分页`)
}
},
deselectAll() {
this.selectedFiles = []
@@ -1442,12 +1291,6 @@ export default {
}
},
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 isUrl = data.fileType === 'url'
return h('div', {
@@ -1485,9 +1328,6 @@ export default {
if (this._observer) {
this._observer.disconnect()
}
if (this._moreObserver) {
this._moreObserver.disconnect()
}
if (this._onResize) {
window.removeEventListener('resize', this._onResize)
}
@@ -1669,24 +1509,6 @@ html, body, #app, .main-container, .directory-tree, .content-card {
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 {
text-align: center;
padding: 30px 10px;
-83
View File
@@ -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
}
-80
View File
@@ -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)
})
})
+5 -11
View File
@@ -432,7 +432,6 @@
</div>
<DirectoryTree
:file-list="directoryData"
:root-page-info="directoryPageInfo"
:share-url="link"
:password="password"
:auth="directoryAuth"
@@ -671,7 +670,6 @@ export default {
// 目录树
showDirectoryTree: false,
directoryData: [],
directoryPageInfo: null,
directoryAuth: '', // 目录解析时的加密 auth,透传给子目录/下载
// 统计信息
@@ -779,7 +777,7 @@ export default {
},
folderParseMeta() {
if (!this.showDirectoryTree) return []
const meta = [`${this.directoryData.length}${this.directoryPageInfo?.hasMore ? '+' : ''} 个文件/文件夹`]
const meta = [`${this.directoryData.length} 个文件/文件夹`]
const recognized = parserUrl.parseLink(this.link || '')
const panType = this.getCurrentPanType()
const name = recognized?.name || (panType ? parseResultMeta.panDisplayName(panType.toLowerCase(), this.panList) : '')
@@ -1244,7 +1242,6 @@ export default {
this.statisticsData = {}
this.showDirectoryTree = false
this.directoryData = []
this.directoryPageInfo = null
this.directoryAuth = ''
},
@@ -1379,17 +1376,14 @@ export default {
params.auth = this.directoryAuth
}
// 直接调用 getFileListPage,让后端返回错误(不做客户端类型检查)
const directoryResult = await this.callAPI('/v2/getFileListPage', params)
const page = directoryResult.data || {}
this.directoryPageInfo = Array.isArray(page) ? null : page
this.directoryData = Array.isArray(page) ? page : (page.list || [])
// 直接调用 getFileList,让后端返回错误(不做客户端类型检查)
const directoryResult = await this.callAPI('/v2/getFileList', params)
this.directoryData = directoryResult.data || []
this.showDirectoryTree = true
// 自动赋值分享链接
this.showListLink = `${this.baseUrl}/showList?url=${encodeURIComponent(this.link)}`
const more = this.directoryPageInfo?.hasMore ? '(当前为第 1 页,可在列表底部加载更多)' : ''
this.$message.success(`目录解析成功!共找到 ${this.directoryData.length} 个文件/文件夹${more}`)
this.$message.success(`目录解析成功!共找到 ${this.directoryData.length} 个文件/文件夹`)
} catch (error) {
console.error('目录解析失败:', error)
}
+2 -6
View File
@@ -20,7 +20,6 @@
<div v-else>
<DirectoryTree
:file-list="directoryData"
:root-page-info="pageInfo"
:share-url="url"
:password="''"
:view-mode="viewMode"
@@ -43,7 +42,6 @@ export default {
loading: true,
error: '',
directoryData: [],
pageInfo: null,
url: '',
viewMode: 'pane'
}
@@ -57,10 +55,8 @@ export default {
return
}
try {
const res = await axios.get('/v2/getFileListPage', { params: { url: this.url } })
const page = res.data.data || {}
this.pageInfo = Array.isArray(page) ? null : page
this.directoryData = Array.isArray(page) ? page : (page.list || [])
const res = await axios.get('/v2/getFileList', { params: { url: this.url } })
this.directoryData = res.data.data || []
} catch (e) {
this.error = e.response?.data?.msg || e.response?.data?.error || '目录解析失败'
} finally {
@@ -54,7 +54,6 @@ public class AppMain {
deploy.addPostShutdownTask(cn.qaiu.parser.PanBase::shutdownSharedClients);
deploy.addPostShutdownTask(cn.qaiu.parser.IPanTool::shutdownCloseAfterScheduler);
deploy.addPostShutdownTask(cn.qaiu.parser.impl.PodTool::shutdownWorkerExecutor);
deploy.addPostShutdownTask(cn.qaiu.parser.impl.CtTool::shutdownWorkerExecutor);
// start
deploy.start(args, AppMain::exec);
}
@@ -71,9 +71,7 @@ public class URLParamUtil {
// 忽略单独处理的参数,不应拼接到分享URL中
if (!paramName.equals("url") && !paramName.equals("pwd") && !paramName.equals("dirId")
&& !paramName.equals("uuid") && !paramName.equals("auth")
&& !paramName.equals("stoken") && !paramName.equals("zml")
&& !paramName.equals("page") && !paramName.equals("pg")
&& !paramName.equals("pageCursor")) {
&& !paramName.equals("stoken") && !paramName.equals("zml")) {
if (firstParam) {
urlBuilder.append("?");
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.CacheLinkInfo;
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.StatisticsInfo;
import cn.qaiu.lz.web.service.DbService;
import cn.qaiu.parser.FolderPaging;
import cn.qaiu.parser.PanDomainTemplate;
import cn.qaiu.parser.IPanTool;
import cn.qaiu.parser.ParserCreate;
@@ -164,50 +162,9 @@ public class ParserApi {
}}).collect(Collectors.toList());
}
/**
* 目录列表。不带 page 时行为与旧版一致;带 page 时返回该页(结构不变)。pg 是 page 的别名。
* 需要 hasMore / nextCursor 时用 {@link #getFileListPage}。
*/
@RouteMapping("/getFileList")
public Future<List<FileInfo>> getFileList(HttpServerRequest request, String pwd, String dirId, String uuid,
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 stoken, String zml, String auth) {
String url = URLParamUtil.parserParams(request);
ParserCreate parserCreate;
try {
@@ -215,16 +172,6 @@ public class ParserApi {
} catch (Exception 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);
JsonObject otherParam = ParserAuthUtil.buildOtherParam(request, auth, linkPrefix);
parserCreate.getShareLinkInfo().getOtherParam().put("domainName", linkPrefix);
@@ -251,8 +198,7 @@ public class ParserApi {
ParserAuthUtil.recordAutoDonatedFailureIfNeeded(dbService,
parserCreate.getShareLinkInfo(), t);
});
})
.map(list -> new FolderListResult(list, info, false));
});
}
// 目录解析下载文件
@@ -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);
}
}
@@ -145,12 +145,3 @@ auths:
username:
password:
# authorization:
# 城通:免密和带访问密码的分享都先匿名解 ALTCHA,通常不用登录。
# 只有匿名结果仍是 Turnstile 时,下面的令牌才会作为可选回退。
# 浏览器打开 https://pan.ctfile.com 并登录,F12 → Application → Session Storage,
# 复制 refresh_token。token 可空,填了就当作当前 access token,过期后用 refresh_token 刷新。
# 刷新若轮换了 refresh_token,进程内会写回这份配置和 TokenCache;重启前请把新值保存回本文件。
# 目录分享类型是 ctd,这里只配 ct 也会被目录解析回退使用。
# ct:
# refresh_token:
# token:
@@ -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"));
}
}