mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-11-27 07:37:00 +00:00
Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d6d66b62f | ||
|
|
4361d96c52 | ||
|
|
971cdcd067 | ||
|
|
4b9339072a | ||
|
|
6b6394e61f | ||
|
|
ba1c429508 | ||
|
|
69ef9c5bbb | ||
|
|
e91c08548a | ||
|
|
e794b34982 | ||
|
|
0a631e75ea | ||
|
|
72194dddc9 | ||
|
|
0d5014ad40 | ||
|
|
1d7836c1bd | ||
|
|
6ed8ae2e28 | ||
|
|
b5a0155dd0 | ||
|
|
8f372e5dd0 | ||
|
|
e9bfe14488 | ||
|
|
cbd10962c0 | ||
|
|
2bb66cfc82 | ||
|
|
fbfb760b3a |
No files matched your search
@@ -25,8 +25,8 @@ body:
|
|||||||
id: version
|
id: version
|
||||||
attributes:
|
attributes:
|
||||||
label: 版本号
|
label: 版本号
|
||||||
description: 页面上的版本,或发布包名里的版本,例如 0.4.11。
|
description: 页面上的版本,或发布包名里的版本,例如 0.4.13。
|
||||||
placeholder: "0.4.11"
|
placeholder: "0.4.13"
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: dropdown
|
- type: dropdown
|
||||||
|
|||||||
@@ -25,8 +25,8 @@ body:
|
|||||||
id: version
|
id: version
|
||||||
attributes:
|
attributes:
|
||||||
label: 版本号
|
label: 版本号
|
||||||
description: 例如 0.4.11。不确定就写获取方式。
|
description: 例如 0.4.13。不确定就写获取方式。
|
||||||
placeholder: "0.4.11"
|
placeholder: "0.4.13"
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: dropdown
|
- type: dropdown
|
||||||
|
|||||||
@@ -1,8 +1,22 @@
|
|||||||
## 更新内容
|
## 更新内容
|
||||||
|
|
||||||
- 城通网盘:免密分享,以及带访问密码的单文件和目录,都先走匿名 ALTCHA。已用项目解析器实测带密码 PDF(4005749 字节,文件头 `%PDF-`、文件尾 `%%EOF`)和目录内 zip(158842 字节,文件头 `PK`,可解压)。官方 `/v4` 只在匿名结果仍是 Cloudflare Turnstile、且自己配置了登录令牌时作为可选回退。登录态没有实测。
|
- 蓝奏文件页识别 `ajaxfiles.php`(#310):
|
||||||
- 永硕 E 盘:适配新版密码入口页。`ys168.com` 会跟随重定向到对应的 `ysepan.com` 后再验证密码。已实测 `sohehe4.ysepan.com`(密码 `1234`)列出目录,并通过 `parseById` 下载 134041 字节的 MRPG 文件和 128 字节的文本文件。
|
- 单文件页 iframe 里的下载 ajax 写成了 `/ajaxfiles.php`。解析器原来只认 `ajaxm.php` 和 `ajaxfile.php`,匹配不上就报「获取失败0, 可能分享已失效」。表单字段没有改。
|
||||||
|
- `https://njkn.lanzouw.com/winx123`(无密码)没有失效。修复后本机完整下载 1,197,569 字节,`unzip -t` 无错误。
|
||||||
|
- 另外三个同样改成 `ajaxfiles.php` 的对照只各下载了 1 MiB Range,返回 206,文件头分别是 7z、zip、zip,没有做完整下载:
|
||||||
|
- `wwn.lanzouy.com/ihLkw1gezutg`
|
||||||
|
- b66477 目录下的 `pan.lanzoui.com/io4y41i3zq5e`
|
||||||
|
- 密码目录 `b00yaejvte` 里的子文件 `w1.lanzn.com/i4VjZ332qzwh`
|
||||||
|
- 带密码的单文件分享没有找到公开样例,没有实测。
|
||||||
|
- 目录按已加载文件名筛选(#311):
|
||||||
|
- 分享目录浏览器和首页解析后的目录共用目录树。两套视图以及独立的 `list.html` 按文件名做大小写不敏感的子串匹配,只筛已经加载的行,不把后续页自动拉完。
|
||||||
|
- 目录树底部「全选 / 取消全选」只作用于当前关键字命中的、已经加载的可选文件。不勾选被筛掉的项,不拉取未加载分页,也不清掉范围外原来的选择。
|
||||||
|
- 分页仍走现有的 `nextCursor` / `pageCursor`。
|
||||||
|
- 界面验收跑在本机开发服务和本机夹具,不是线上分享页。
|
||||||
|
|
||||||
## 限制
|
## 限制
|
||||||
|
|
||||||
这次只修复并实测了上述城通和永硕样例,不表示所有分享都可用。服务端不能解开 Cloudflare Turnstile。没有配置城通登录令牌时,如果匿名 ALTCHA 之后仍然返回 Turnstile,带密码分享会失败。永硕 `ysupan.com` 旧接口,以及部分直链端口,这次没有改。
|
- 没有把这次界面验收当成线上分享页或全站界面已验。
|
||||||
|
- 三个对照链接只验证了 1 MiB Range,不能据此说这些文件已经完整下载并核对。
|
||||||
|
- 带密码的单文件分享未测。
|
||||||
|
- 本机访问部分蓝奏下载域时连接时好时坏。winx123 曾连续超时,重试后完整下载成功。
|
||||||
@@ -9,8 +9,9 @@ on:
|
|||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- 'v*'
|
- 'v*'
|
||||||
|
# '*' 不匹配含 / 的分支名(如 cursor/xxx),会让功能分支推送也发布 :latest 镜像
|
||||||
branches-ignore:
|
branches-ignore:
|
||||||
- '*'
|
- '**'
|
||||||
paths-ignore:
|
paths-ignore:
|
||||||
- 'bin/**'
|
- 'bin/**'
|
||||||
- '.github/**'
|
- '.github/**'
|
||||||
|
|||||||
@@ -470,7 +470,7 @@ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtow
|
|||||||
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
|
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
|
||||||
```shell
|
```shell
|
||||||
cd ~
|
cd ~
|
||||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.11/netdisk-fast-download-linux-amd64.zip
|
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.13/netdisk-fast-download-linux-amd64.zip
|
||||||
unzip netdisk-fast-download.zip
|
unzip netdisk-fast-download.zip
|
||||||
cd netdisk-fast-download
|
cd netdisk-fast-download
|
||||||
bash service-install.sh
|
bash service-install.sh
|
||||||
|
|||||||
+18
-4
@@ -4,26 +4,26 @@ NFD 解析器模块:聚合各类网盘/分享页解析,统一输出文件列
|
|||||||
|
|
||||||
- 语言:Java 17
|
- 语言:Java 17
|
||||||
- 构建:Maven
|
- 构建:Maven
|
||||||
- 模块版本:10.2.5
|
- 模块版本:10.2.6(独立于应用 `<revision>`,当前应用版本仍是 0.4.13)
|
||||||
|
|
||||||
## 依赖(Maven Central)
|
## 依赖(Maven Central)
|
||||||
```xml
|
```xml
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cn.qaiu</groupId>
|
<groupId>cn.qaiu</groupId>
|
||||||
<artifactId>parser</artifactId>
|
<artifactId>parser</artifactId>
|
||||||
<version>10.2.5</version>
|
<version>10.2.6</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
- Gradle Groovy DSL:
|
- Gradle Groovy DSL:
|
||||||
```groovy
|
```groovy
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation 'cn.qaiu:parser:10.2.5'
|
implementation 'cn.qaiu:parser:10.2.6'
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
- Gradle Kotlin DSL:
|
- Gradle Kotlin DSL:
|
||||||
```kotlin
|
```kotlin
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("cn.qaiu:parser:10.2.5")
|
implementation("cn.qaiu:parser:10.2.6")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -56,6 +56,20 @@ mvn -pl parser -am install
|
|||||||
mvn -pl parser test
|
mvn -pl parser test
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 发布到 Maven Central(手动)
|
||||||
|
|
||||||
|
`cn.qaiu:parser` 不由 `.github/workflows/maven.yml` 发布。该 workflow 只在推送 `v*` tag 时构建 GitHub Release 压缩包和 Docker 镜像。
|
||||||
|
|
||||||
|
Central 上的 `10.2.5` 已发布,不能覆盖。下一版只发布 `10.2.6`。在仓库根目录执行:
|
||||||
|
|
||||||
|
```
|
||||||
|
mvn -pl parser -am clean deploy -DskipTests
|
||||||
|
```
|
||||||
|
|
||||||
|
本机需要 JDK 17+、Maven 3.9+、可用于签名的 GPG 私钥,以及 `~/.m2/settings.xml` 中 id 为 `sonatype` 的 Central Portal 用户名和 token。密钥口令放在本机 settings 的 `gpg.passphrase`(插件已使用 `--pinentry-mode loopback`),不要写进仓库,也不要放在命令行参数里。
|
||||||
|
|
||||||
|
`parser/pom.xml` 已配置 `central-publishing-maven-plugin`(`publishingServerId=sonatype`,`autoPublish=true`)、`maven-gpg-plugin` 和 `flatten-maven-plugin`(`flattenMode=ossrh`)。上面的 `deploy` 会使用打平后的 POM 签名并自动发布,坐标仍是 `cn.qaiu:parser`,许可证 MIT。
|
||||||
|
|
||||||
## 自定义解析器扩展
|
## 自定义解析器扩展
|
||||||
本模块支持用户自定义解析器扩展。通过简单的配置和注册,你可以添加自己的网盘解析实现:
|
本模块支持用户自定义解析器扩展。通过简单的配置和注册,你可以添加自己的网盘解析实现:
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cn.qaiu</groupId>
|
<groupId>cn.qaiu</groupId>
|
||||||
<artifactId>parser</artifactId>
|
<artifactId>parser</artifactId>
|
||||||
<version>10.2.5</version>
|
<version>10.2.6</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>cn.qaiu</groupId>
|
<groupId>cn.qaiu</groupId>
|
||||||
<artifactId>parser</artifactId>
|
<artifactId>parser</artifactId>
|
||||||
<version>10.2.5</version>
|
<version>10.2.6</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
package cn.qaiu.parser;
|
||||||
|
|
||||||
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目录列表分页约定(解析器与 API 共用)。
|
||||||
|
* <p>
|
||||||
|
* 入参写在 {@link ShareLinkInfo#getOtherParam()}:
|
||||||
|
* <ul>
|
||||||
|
* <li>{@link #PAGE}:从 1 开始的页码;不传时解析器按原逻辑只取第一页</li>
|
||||||
|
* <li>{@link #CURSOR}:上一页返回的 {@code nextCursor},可选,只是加速,不可信</li>
|
||||||
|
* </ul>
|
||||||
|
* 解析器取完一页后写回 {@link #PAGE_INFO},见 {@link #pageInfo}。
|
||||||
|
* 没写 {@link #PAGE_INFO} 的解析器视为不分页,整份列表就是第 1 页。
|
||||||
|
*/
|
||||||
|
public final class FolderPaging {
|
||||||
|
|
||||||
|
public static final String PAGE = "page";
|
||||||
|
public static final String CURSOR = "pageCursor";
|
||||||
|
public static final String PAGE_INFO = "pageInfo";
|
||||||
|
|
||||||
|
/** 页码上限。蓝奏无游标时要从第 1 页顺序翻到目标页,必须有界。 */
|
||||||
|
public static final int MAX_PAGE = 500;
|
||||||
|
|
||||||
|
private static final Set<String> PAGED_TYPES = Set.of("lz", "fj", "iz");
|
||||||
|
|
||||||
|
private FolderPaging() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 该网盘的目录解析是否支持按页取。 */
|
||||||
|
public static boolean supports(String type) {
|
||||||
|
return type != null && PAGED_TYPES.contains(type.toLowerCase(Locale.ROOT));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析页码参数。空值返回 null(保持旧行为);非法值抛 IllegalArgumentException。
|
||||||
|
*/
|
||||||
|
public static Integer parsePage(String raw) {
|
||||||
|
if (raw == null || raw.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
int page;
|
||||||
|
try {
|
||||||
|
page = Integer.parseInt(raw.trim());
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
throw new IllegalArgumentException("page 必须是正整数: " + raw);
|
||||||
|
}
|
||||||
|
if (page < 1 || page > MAX_PAGE) {
|
||||||
|
throw new IllegalArgumentException("page 超出范围 1-" + MAX_PAGE + ": " + raw);
|
||||||
|
}
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 本次请求的页码;没传返回 null。 */
|
||||||
|
public static Integer requestedPage(ShareLinkInfo info) {
|
||||||
|
Object v = info.getOtherParam().get(PAGE);
|
||||||
|
if (v instanceof Number n) {
|
||||||
|
return n.intValue();
|
||||||
|
}
|
||||||
|
return v == null ? null : parsePage(v.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 本次请求的页码;没传按第 1 页。 */
|
||||||
|
public static int pageOrFirst(ShareLinkInfo info) {
|
||||||
|
Integer page = requestedPage(info);
|
||||||
|
return page == null ? 1 : page;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String cursor(ShareLinkInfo info) {
|
||||||
|
Object v = info.getOtherParam().get(CURSOR);
|
||||||
|
return v == null || v.toString().isBlank() ? null : v.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写回分页结果。
|
||||||
|
*
|
||||||
|
* @param pageSize 上游每页条数(原始条数口径,含被过滤的占位项)
|
||||||
|
* @param hasMore 上游明确还有下一页
|
||||||
|
* @param total 上游给出的总条数,未知传 null
|
||||||
|
* @param totalPage 上游给出的总页数,未知传 null
|
||||||
|
* @param nextCursor 取下一页可直接复用的游标,没有传 null
|
||||||
|
*/
|
||||||
|
public static JsonObject pageInfo(ShareLinkInfo info, int page, int pageSize, boolean hasMore,
|
||||||
|
Integer total, Integer totalPage, String nextCursor) {
|
||||||
|
JsonObject json = new JsonObject()
|
||||||
|
.put("paged", true)
|
||||||
|
.put("page", page)
|
||||||
|
.put("pageSize", pageSize)
|
||||||
|
.put("hasMore", hasMore)
|
||||||
|
.put("nextPage", hasMore ? page + 1 : null)
|
||||||
|
.put("total", total)
|
||||||
|
.put("totalPage", totalPage)
|
||||||
|
.put("nextCursor", hasMore ? nextCursor : null);
|
||||||
|
info.getOtherParam().put(PAGE_INFO, json);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上游给了总页数就以它为准;没给时整页满才认为可能还有。空页一律结束,避免无限翻页。
|
||||||
|
*/
|
||||||
|
public static boolean hasMore(int page, int rawCount, int pageSize, Integer totalPage) {
|
||||||
|
if (rawCount <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (totalPage != null && totalPage > 0) {
|
||||||
|
return page < totalPage;
|
||||||
|
}
|
||||||
|
return rawCount >= pageSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 小飞机 / 蓝奏优享 share/list 响应:offset 为页码,带 total / totalPage。 */
|
||||||
|
public static JsonObject offsetListPage(ShareLinkInfo info, JsonObject resp, int rawCount, int pageSize) {
|
||||||
|
int page = pageOrFirst(info);
|
||||||
|
Integer total = intOrNull(resp, "total");
|
||||||
|
Integer totalPage = intOrNull(resp, "totalPage");
|
||||||
|
return pageInfo(info, page, pageSize, hasMore(page, rawCount, pageSize, totalPage), total, totalPage, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Integer intOrNull(JsonObject json, String key) {
|
||||||
|
if (json == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Object v = json.getValue(key);
|
||||||
|
if (v instanceof Number n) {
|
||||||
|
return n.intValue();
|
||||||
|
}
|
||||||
|
if (v instanceof CharSequence s) {
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(s.toString().trim());
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static JsonObject pageInfo(ShareLinkInfo info) {
|
||||||
|
Object v = info.getOtherParam().get(PAGE_INFO);
|
||||||
|
return v instanceof JsonObject json ? json : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package cn.qaiu.parser.impl;
|
|||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import cn.qaiu.parser.FolderPaging;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.util.*;
|
import cn.qaiu.util.*;
|
||||||
import io.vertx.core.Future;
|
import io.vertx.core.Future;
|
||||||
@@ -60,7 +61,10 @@ public class FjTool extends PanBase {
|
|||||||
|
|
||||||
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
||||||
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
||||||
"={folderId}&offset=1&limit=60";
|
"={folderId}&offset={offset}&limit={limit}";
|
||||||
|
|
||||||
|
/** share/list 每页条数;offset 是从 1 开始的页码。 */
|
||||||
|
static final int LIST_LIMIT = 60;
|
||||||
|
|
||||||
private static final MultiMap header;
|
private static final MultiMap header;
|
||||||
private static final MultiMap header0;
|
private static final MultiMap header0;
|
||||||
@@ -492,7 +496,11 @@ public class FjTool extends PanBase {
|
|||||||
.setParserUrl(id)
|
.setParserUrl(id)
|
||||||
.setPanType(shareLinkInfo.getType());
|
.setPanType(shareLinkInfo.getType());
|
||||||
List<FileInfo> result = new ArrayList<>();
|
List<FileInfo> result = new ArrayList<>();
|
||||||
result.add(fileInfo);
|
int page = FolderPaging.pageOrFirst(shareLinkInfo);
|
||||||
|
if (page == 1) {
|
||||||
|
result.add(fileInfo);
|
||||||
|
}
|
||||||
|
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -506,86 +514,101 @@ public class FjTool extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
|
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
||||||
|
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
JsonArray list;
|
JsonArray list;
|
||||||
|
JsonObject jsonObject;
|
||||||
try {
|
try {
|
||||||
JsonObject jsonObject = asJson(res);
|
jsonObject = asJson(res);
|
||||||
log.debug("目录列表: {}", jsonObject.encodePrettily());
|
log.debug("目录列表: {}", jsonObject.encodePrettily());
|
||||||
list = jsonObject.getJsonArray("list");
|
list = jsonObject.getJsonArray("list");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("解析目录失败: {}", res.bodyAsString());
|
log.error("解析目录失败: {}", res.bodyAsString());
|
||||||
|
promise.tryFail("目录解析失败: 响应不是 JSON");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (list == null) {
|
||||||
|
promise.tryFail("目录解析失败: 响应缺少 list 字段: " + jsonObject);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ArrayList<FileInfo> result = new ArrayList<>();
|
ArrayList<FileInfo> result = new ArrayList<>();
|
||||||
list.forEach(item->{
|
try {
|
||||||
JsonObject fileJson = (JsonObject) item;
|
list.forEach(item->{
|
||||||
FileInfo fileInfo = new FileInfo();
|
JsonObject fileJson = (JsonObject) item;
|
||||||
|
FileInfo fileInfo = new FileInfo();
|
||||||
|
|
||||||
// 映射已知字段fileInfo
|
// 映射已知字段fileInfo
|
||||||
String fileId = fileJson.getString("fileId");
|
String fileId = fileJson.getString("fileId");
|
||||||
String userId = fileJson.getString("userId");
|
String userId = fileJson.getString("userId");
|
||||||
|
|
||||||
// 其他参数
|
// 其他参数
|
||||||
long nowTs2 = System.currentTimeMillis();
|
long nowTs2 = System.currentTimeMillis();
|
||||||
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
||||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
||||||
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
||||||
|
|
||||||
// 回传用到的参数
|
// 回传用到的参数
|
||||||
//"fidEncode", paramJson.getString("fidEncode"))
|
//"fidEncode", paramJson.getString("fidEncode"))
|
||||||
//"uuid", paramJson.getString("uuid"))
|
//"uuid", paramJson.getString("uuid"))
|
||||||
//"ts", paramJson.getString("ts"))
|
//"ts", paramJson.getString("ts"))
|
||||||
//"auth", paramJson.getString("auth"))
|
//"auth", paramJson.getString("auth"))
|
||||||
//"shareId", paramJson.getString("shareId"))
|
//"shareId", paramJson.getString("shareId"))
|
||||||
JsonObject entries = JsonObject.of(
|
JsonObject entries = JsonObject.of(
|
||||||
"fileId", fileId,
|
"fileId", fileId,
|
||||||
"userId", userId,
|
"userId", userId,
|
||||||
"fidEncode", fidEncode,
|
"fidEncode", fidEncode,
|
||||||
"uuid", uuid,
|
"uuid", uuid,
|
||||||
"ts", tsEncode2,
|
"ts", tsEncode2,
|
||||||
"auth", auth,
|
"auth", auth,
|
||||||
"shareId", shareId);
|
"shareId", shareId);
|
||||||
String param = CommonUtils.urlBase64Encode(entries.encode());
|
String param = CommonUtils.urlBase64Encode(entries.encode());
|
||||||
|
|
||||||
if (fileJson.getInteger("fileType") == 2) {
|
if (fileJson.getInteger("fileType") == 2) {
|
||||||
// 如果是目录
|
// 如果是目录
|
||||||
fileInfo.setFileName(fileJson.getString("name"))
|
fileInfo.setFileName(fileJson.getString("name"))
|
||||||
.setFileId(fileJson.getString("folderId"))
|
.setFileId(fileJson.getString("folderId"))
|
||||||
.setCreateTime(fileJson.getString("updTime"))
|
.setCreateTime(fileJson.getString("updTime"))
|
||||||
.setFileType("folder")
|
.setFileType("folder")
|
||||||
.setSize(0L)
|
.setSize(0L)
|
||||||
.setSizeStr("0B")
|
.setSizeStr("0B")
|
||||||
|
.setCreateBy(fileJson.getLong("userId").toString())
|
||||||
|
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
||||||
|
.setCreateTime(fileJson.getString("updTime"))
|
||||||
|
.setFileIcon(fileJson.getString("fileIcon"))
|
||||||
|
.setPanType(shareLinkInfo.getType())
|
||||||
|
// 设置目录解析的URL
|
||||||
|
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&uuid=%s", getDomainName(),
|
||||||
|
shareLinkInfo.getShareUrl(), fileJson.getString("folderId"), uuid));
|
||||||
|
result.add(fileInfo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
long fileSize = fileJson.getLong("fileSize") * 1024;
|
||||||
|
fileInfo.setFileName(fileJson.getString("fileName"))
|
||||||
|
.setFileId(fileJson.getString("fileId"))
|
||||||
|
.setCreateTime(fileJson.getString("createTime"))
|
||||||
|
.setFileType("file")
|
||||||
|
.setSize(fileSize)
|
||||||
|
.setSizeStr(FileSizeConverter.convertToReadableSize(fileSize))
|
||||||
.setCreateBy(fileJson.getLong("userId").toString())
|
.setCreateBy(fileJson.getLong("userId").toString())
|
||||||
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
||||||
.setCreateTime(fileJson.getString("updTime"))
|
.setCreateTime(fileJson.getString("updTime"))
|
||||||
.setFileIcon(fileJson.getString("fileIcon"))
|
.setFileIcon(fileJson.getString("fileIcon"))
|
||||||
.setPanType(shareLinkInfo.getType())
|
.setPanType(shareLinkInfo.getType())
|
||||||
// 设置目录解析的URL
|
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(),
|
||||||
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s&uuid=%s", getDomainName(),
|
shareLinkInfo.getType(), param))
|
||||||
shareLinkInfo.getShareUrl(), fileJson.getString("folderId"), uuid));
|
.setPreviewUrl(String.format("%s/v2/viewUrl/%s/%s", getDomainName(),
|
||||||
|
shareLinkInfo.getType(), param));
|
||||||
result.add(fileInfo);
|
result.add(fileInfo);
|
||||||
return;
|
});
|
||||||
}
|
} catch (Exception e) {
|
||||||
long fileSize = fileJson.getLong("fileSize") * 1024;
|
log.error("目录列表条目解析失败: {}", jsonObject, e);
|
||||||
fileInfo.setFileName(fileJson.getString("fileName"))
|
promise.tryFail("目录解析失败: 列表条目格式异常 " + e);
|
||||||
.setFileId(fileJson.getString("fileId"))
|
return;
|
||||||
.setCreateTime(fileJson.getString("createTime"))
|
}
|
||||||
.setFileType("file")
|
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
|
||||||
.setSize(fileSize)
|
|
||||||
.setSizeStr(FileSizeConverter.convertToReadableSize(fileSize))
|
|
||||||
.setCreateBy(fileJson.getLong("userId").toString())
|
|
||||||
.setDownloadCount(fileJson.getInteger("fileDownloads"))
|
|
||||||
.setCreateTime(fileJson.getString("updTime"))
|
|
||||||
.setFileIcon(fileJson.getString("fileIcon"))
|
|
||||||
.setPanType(shareLinkInfo.getType())
|
|
||||||
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(),
|
|
||||||
shareLinkInfo.getType(), param))
|
|
||||||
.setPreviewUrl(String.format("%s/v2/viewUrl/%s/%s", getDomainName(),
|
|
||||||
shareLinkInfo.getType(), param));
|
|
||||||
result.add(fileInfo);
|
|
||||||
});
|
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
});
|
}).onFailure(err -> promise.tryFail("目录解析失败: " + err.getMessage()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package cn.qaiu.parser.impl;
|
|||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import cn.qaiu.parser.FolderPaging;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.parser.TokenCache;
|
import cn.qaiu.parser.TokenCache;
|
||||||
import cn.qaiu.util.AESUtils;
|
import cn.qaiu.util.AESUtils;
|
||||||
@@ -56,7 +57,10 @@ public class IzTool extends PanBase {
|
|||||||
|
|
||||||
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
||||||
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
||||||
"={folderId}&offset=1&limit=60";
|
"={folderId}&offset={offset}&limit={limit}";
|
||||||
|
|
||||||
|
/** share/list 每页条数;offset 是从 1 开始的页码。 */
|
||||||
|
static final int LIST_LIMIT = 60;
|
||||||
|
|
||||||
|
|
||||||
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
||||||
@@ -569,7 +573,11 @@ public class IzTool extends PanBase {
|
|||||||
.setParserUrl(id)
|
.setParserUrl(id)
|
||||||
.setPanType(shareLinkInfo.getType());
|
.setPanType(shareLinkInfo.getType());
|
||||||
List<FileInfo> result = new ArrayList<>();
|
List<FileInfo> result = new ArrayList<>();
|
||||||
result.add(fileInfo);
|
int page = FolderPaging.pageOrFirst(shareLinkInfo);
|
||||||
|
if (page == 1) {
|
||||||
|
result.add(fileInfo);
|
||||||
|
}
|
||||||
|
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -586,6 +594,8 @@ public class IzTool extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
|
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
||||||
|
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
String resBody = asText(res);
|
String resBody = asText(res);
|
||||||
// 检查是否包含 cookie 验证
|
// 检查是否包含 cookie 验证
|
||||||
@@ -600,6 +610,8 @@ public class IzTool extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
|
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
||||||
|
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
||||||
.send().onSuccess(res2 -> {
|
.send().onSuccess(res2 -> {
|
||||||
processDirResponse(res2, shareId, promise);
|
processDirResponse(res2, shareId, promise);
|
||||||
}).onFailure(err -> {
|
}).onFailure(err -> {
|
||||||
@@ -691,6 +703,7 @@ public class IzTool extends PanBase {
|
|||||||
shareLinkInfo.getType(), param));
|
shareLinkInfo.getType(), param));
|
||||||
result.add(fileInfo);
|
result.add(fileInfo);
|
||||||
});
|
});
|
||||||
|
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package cn.qaiu.parser.impl;
|
|||||||
|
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import cn.qaiu.parser.FolderPaging;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.util.AESUtils;
|
import cn.qaiu.util.AESUtils;
|
||||||
import cn.qaiu.util.AcwScV2Generator;
|
import cn.qaiu.util.AcwScV2Generator;
|
||||||
@@ -54,7 +55,10 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
|
|
||||||
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
private static final String FILE_LIST_URL = API_URL_PREFIX + "/share/list?devType=6&devModel=Chrome&uuid" +
|
||||||
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
"={uuid}&extra=2×tamp={ts}&shareId={shareId}&folderId" +
|
||||||
"={folderId}&offset=1&limit=60";
|
"={folderId}&offset={offset}&limit={limit}";
|
||||||
|
|
||||||
|
/** share/list 每页条数;offset 是从 1 开始的页码。 */
|
||||||
|
static final int LIST_LIMIT = 60;
|
||||||
|
|
||||||
|
|
||||||
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
|
||||||
@@ -512,7 +516,11 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
.setParserUrl(id)
|
.setParserUrl(id)
|
||||||
.setPanType(shareLinkInfo.getType());
|
.setPanType(shareLinkInfo.getType());
|
||||||
List<FileInfo> result = new ArrayList<>();
|
List<FileInfo> result = new ArrayList<>();
|
||||||
result.add(fileInfo);
|
int page = FolderPaging.pageOrFirst(shareLinkInfo);
|
||||||
|
if (page == 1) {
|
||||||
|
result.add(fileInfo);
|
||||||
|
}
|
||||||
|
FolderPaging.pageInfo(shareLinkInfo, page, LIST_LIMIT, false, 1, 1, null);
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -565,6 +573,8 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
|
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
||||||
|
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
||||||
.send().onSuccess(res -> {
|
.send().onSuccess(res -> {
|
||||||
String resBody = asText(res);
|
String resBody = asText(res);
|
||||||
// 检查是否包含 cookie 验证
|
// 检查是否包含 cookie 验证
|
||||||
@@ -579,6 +589,8 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
.setTemplateParam("uuid", uuid)
|
.setTemplateParam("uuid", uuid)
|
||||||
.setTemplateParam("ts", tsEncode)
|
.setTemplateParam("ts", tsEncode)
|
||||||
.setTemplateParam("folderId", id)
|
.setTemplateParam("folderId", id)
|
||||||
|
.setTemplateParam("offset", String.valueOf(FolderPaging.pageOrFirst(shareLinkInfo)))
|
||||||
|
.setTemplateParam("limit", String.valueOf(LIST_LIMIT))
|
||||||
.send().onSuccess(res2 -> {
|
.send().onSuccess(res2 -> {
|
||||||
processDirResponse(res2, shareId, promise);
|
processDirResponse(res2, shareId, promise);
|
||||||
}).onFailure(err -> {
|
}).onFailure(err -> {
|
||||||
@@ -671,6 +683,7 @@ public class IzToolWithAuth extends PanBase {
|
|||||||
shareLinkInfo.getType(), param));
|
shareLinkInfo.getType(), param));
|
||||||
result.add(fileInfo);
|
result.add(fileInfo);
|
||||||
});
|
});
|
||||||
|
FolderPaging.offsetListPage(shareLinkInfo, jsonObject, list.size(), LIST_LIMIT);
|
||||||
promise.complete(result);
|
promise.complete(result);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
log.error("处理目录响应异常: {}", e.getMessage(), e);
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.util.CommonUtils;
|
||||||
|
import io.vertx.core.json.JsonObject;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 蓝奏目录「下一页」游标。
|
||||||
|
* <p>
|
||||||
|
* filemoreajax 的 t/k 由分享页下发,上游按这组令牌记录已翻到第几页:同一组令牌可以取
|
||||||
|
* 「已取过的最大页 + 1」以内的任意页;换一组新令牌直接跳到第 N 页会返回 zt=4「请刷新,重试」。
|
||||||
|
* 所以加载更多时把上一页用过的表单(不含密码和页码)交还给客户端,下次直接续翻。
|
||||||
|
* <p>
|
||||||
|
* 游标来自客户端,不可信:只用于表单字段,POST 主机仍由服务端按分享链接决定;
|
||||||
|
* 分享 key、页码、路径对不上一律当作没有游标,回退到从第 1 页顺序翻。
|
||||||
|
*/
|
||||||
|
final class LzFolderCursor {
|
||||||
|
|
||||||
|
private static final int VERSION = 1;
|
||||||
|
private static final Pattern PATH = Pattern.compile("/filemoreajax\\.php\\?file=(\\d+)");
|
||||||
|
private static final Pattern KEY = Pattern.compile("\\w{1,32}");
|
||||||
|
private static final int MAX_VALUE_LENGTH = 256;
|
||||||
|
private static final int MAX_FIELDS = 32;
|
||||||
|
|
||||||
|
final String path;
|
||||||
|
final Map<String, String> form;
|
||||||
|
final String webpage;
|
||||||
|
|
||||||
|
private LzFolderCursor(String path, Map<String, String> form, String webpage) {
|
||||||
|
this.path = path;
|
||||||
|
this.form = form;
|
||||||
|
this.webpage = webpage;
|
||||||
|
}
|
||||||
|
|
||||||
|
static String encode(String shareKey, String path, Map<String, String> form, int nextPage, String webpage) {
|
||||||
|
JsonObject f = new JsonObject();
|
||||||
|
form.forEach((k, v) -> {
|
||||||
|
if (!"pwd".equals(k) && !"pg".equals(k)) {
|
||||||
|
f.put(k, v);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
JsonObject json = new JsonObject()
|
||||||
|
.put("v", VERSION)
|
||||||
|
.put("s", shareKey)
|
||||||
|
.put("p", path)
|
||||||
|
.put("n", nextPage)
|
||||||
|
.put("f", f);
|
||||||
|
if (webpage != null && !webpage.isBlank()) {
|
||||||
|
json.put("w", webpage);
|
||||||
|
}
|
||||||
|
return CommonUtils.urlBase64Encode(json.encode());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return 校验通过的游标;任何不匹配或格式问题都返回 null
|
||||||
|
*/
|
||||||
|
static LzFolderCursor decode(String raw, String shareKey, int page) {
|
||||||
|
if (raw == null || raw.isBlank() || raw.length() > 4096) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
JsonObject json = new JsonObject(CommonUtils.urlBase64Decode(raw));
|
||||||
|
if (json.getInteger("v", 0) != VERSION) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (shareKey == null || !shareKey.equals(json.getString("s"))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (json.getInteger("n", -1) != page) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String path = json.getString("p");
|
||||||
|
var m = path == null ? null : PATH.matcher(path);
|
||||||
|
if (m == null || !m.matches()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
JsonObject f = json.getJsonObject("f");
|
||||||
|
if (f == null || f.size() > MAX_FIELDS) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Map<String, String> form = new LinkedHashMap<>();
|
||||||
|
for (String key : f.fieldNames()) {
|
||||||
|
Object v = f.getValue(key);
|
||||||
|
if (!KEY.matcher(key).matches() || v == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String s = String.valueOf(v);
|
||||||
|
if (s.length() > MAX_VALUE_LENGTH || s.chars().anyMatch(c -> c < 0x20)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
form.put(key, s);
|
||||||
|
}
|
||||||
|
if (!m.group(1).equals(form.get("fid")) || !form.containsKey("t") || !form.containsKey("k")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String webpage = json.getString("w");
|
||||||
|
if (webpage != null && (webpage.length() > MAX_VALUE_LENGTH || !webpage.matches("[\\w\\-=.%]+"))) {
|
||||||
|
webpage = null;
|
||||||
|
}
|
||||||
|
return new LzFolderCursor(path, form, webpage);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 本次请求用的表单:游标字段 + 当前密码 + 目标页。 */
|
||||||
|
Map<String, String> formFor(String pwd, int page) {
|
||||||
|
Map<String, String> out = new LinkedHashMap<>(form);
|
||||||
|
out.put("pg", String.valueOf(page));
|
||||||
|
out.put("pwd", pwd == null ? "" : pwd);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package cn.qaiu.parser.impl;
|
|||||||
import cn.qaiu.WebClientVertxInit;
|
import cn.qaiu.WebClientVertxInit;
|
||||||
import cn.qaiu.entity.FileInfo;
|
import cn.qaiu.entity.FileInfo;
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import cn.qaiu.parser.FolderPaging;
|
||||||
import cn.qaiu.parser.PanBase;
|
import cn.qaiu.parser.PanBase;
|
||||||
import cn.qaiu.util.*;
|
import cn.qaiu.util.*;
|
||||||
import io.netty.handler.codec.http.cookie.DefaultCookie;
|
import io.netty.handler.codec.http.cookie.DefaultCookie;
|
||||||
@@ -11,6 +12,7 @@ import io.vertx.core.Handler;
|
|||||||
import io.vertx.core.MultiMap;
|
import io.vertx.core.MultiMap;
|
||||||
import io.vertx.core.Promise;
|
import io.vertx.core.Promise;
|
||||||
import io.vertx.core.buffer.Buffer;
|
import io.vertx.core.buffer.Buffer;
|
||||||
|
import io.vertx.core.json.JsonArray;
|
||||||
import io.vertx.core.json.JsonObject;
|
import io.vertx.core.json.JsonObject;
|
||||||
import io.vertx.core.net.ProxyOptions;
|
import io.vertx.core.net.ProxyOptions;
|
||||||
import io.vertx.core.net.ProxyType;
|
import io.vertx.core.net.ProxyType;
|
||||||
@@ -25,9 +27,11 @@ import java.io.ByteArrayInputStream;
|
|||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
@@ -73,6 +77,18 @@ public class LzTool extends PanBase {
|
|||||||
"https://www.lanzoux.com",
|
"https://www.lanzoux.com",
|
||||||
"https://wwww.lanzoux.com"
|
"https://wwww.lanzoux.com"
|
||||||
);
|
);
|
||||||
|
/** filemoreajax.php 每页条数(含 id=-1 占位项),不足即最后一页。 */
|
||||||
|
static final int LZ_FOLDER_PAGE_SIZE = 50;
|
||||||
|
/** 目录页不渲染的占位项 id。 */
|
||||||
|
static final String LZ_PLACEHOLDER_ID = "-1";
|
||||||
|
/** 同一组 t/k 两次 filemoreajax 间隔不足约 1.5 秒时返回 zt=4「请刷新,重试」。 */
|
||||||
|
static final int LZ_ZT_REFRESH = 4;
|
||||||
|
static final long LZ_PAGE_INTERVAL_MS = 1500;
|
||||||
|
/** zt=4 时同页重试的等待时间:实测多数 2 秒内恢复,个别需要约 5 秒。 */
|
||||||
|
static final long[] LZ_REFRESH_RETRY_DELAYS_MS = {2000, 5000};
|
||||||
|
static final int LZ_REFRESH_RETRIES = LZ_REFRESH_RETRY_DELAYS_MS.length;
|
||||||
|
/** 无游标时从第 1 页顺序翻的最大页数,保证一次请求能在路由超时(默认 15 秒)内完成。 */
|
||||||
|
static final int LZ_MAX_WALK_PAGES = 6;
|
||||||
/** 分享页 / ajax 请求超时 */
|
/** 分享页 / ajax 请求超时 */
|
||||||
private static final long REQUEST_TIMEOUT = 8000;
|
private static final long REQUEST_TIMEOUT = 8000;
|
||||||
/** 下载域跳转与二次验证超时,链路更长 */
|
/** 下载域跳转与二次验证超时,链路更长 */
|
||||||
@@ -83,11 +99,14 @@ public class LzTool extends PanBase {
|
|||||||
private static final Pattern P_AJAXDATA = Pattern.compile("ajaxdata\\s*=\\s*'([^']+)'");
|
private static final Pattern P_AJAXDATA = Pattern.compile("ajaxdata\\s*=\\s*'([^']+)'");
|
||||||
private static final Pattern P_WEBSIGN = Pattern.compile("'websign'\\s*:\\s*'([^']*)'");
|
private static final Pattern P_WEBSIGN = Pattern.compile("'websign'\\s*:\\s*'([^']*)'");
|
||||||
private static final Pattern P_WEBPAGE = Pattern.compile("[?&]webpage=([^&\"'\\s#]+)");
|
private static final Pattern P_WEBPAGE = Pattern.compile("[?&]webpage=([^&\"'\\s#]+)");
|
||||||
/** 页面脚本里的绝对 ajax,例如 https://apifile.lanzouw.com/ajaxfile.php?file=123 */
|
/**
|
||||||
|
* 页面脚本里的绝对 ajax,例如 https://apifile.lanzouw.com/ajaxfile.php?file=123。
|
||||||
|
* 文件名有 ajaxm / ajaxfile / ajaxfiles 三种,2026-11 起文件页 iframe 改用 ajaxfiles.php。
|
||||||
|
*/
|
||||||
private static final Pattern P_AJAX_ABSOLUTE = Pattern.compile(
|
private static final Pattern P_AJAX_ABSOLUTE = Pattern.compile(
|
||||||
"['\"]((?:https?:)?//[^'\"\\s<>]+/ajax(?:m|file)\\.php\\?file=\\d+)['\"]",
|
"['\"]((?:https?:)?//[^'\"\\s<>]+/ajax(?:m|files?)\\.php\\?file=\\d+)['\"]",
|
||||||
Pattern.CASE_INSENSITIVE);
|
Pattern.CASE_INSENSITIVE);
|
||||||
private static final Pattern P_AJAX_PATH = Pattern.compile("(?:['\"/]|^)(ajax(?:m|file)\\.php\\?file=\\d+)");
|
private static final Pattern P_AJAX_PATH = Pattern.compile("(?:['\"/]|^)(ajax(?:m|files?)\\.php\\?file=\\d+)");
|
||||||
private static final Pattern P_SIGN = Pattern.compile("'sign'\\s*:\\s*'([^']+)'");
|
private static final Pattern P_SIGN = Pattern.compile("'sign'\\s*:\\s*'([^']+)'");
|
||||||
private static final Pattern P_ISNGIS = Pattern.compile("var\\s+isngis\\s*=\\s*'([^']+)'");
|
private static final Pattern P_ISNGIS = Pattern.compile("var\\s+isngis\\s*=\\s*'([^']+)'");
|
||||||
private static final Pattern P_VERIFY_FILE = Pattern.compile("'file'\\s*:\\s*'([^']+)'");
|
private static final Pattern P_VERIFY_FILE = Pattern.compile("'file'\\s*:\\s*'([^']+)'");
|
||||||
@@ -727,6 +746,16 @@ public class LzTool extends PanBase {
|
|||||||
return new AjaxCall(block.group(1), data);
|
return new AjaxCall(block.group(1), data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static Map<String, String> folderAjaxForm(String html, String pwd) {
|
||||||
|
AjaxCall call = extractFolderAjax(html, pwd);
|
||||||
|
return call == null ? null : call.form();
|
||||||
|
}
|
||||||
|
|
||||||
|
static String folderAjaxPath(String html, String pwd) {
|
||||||
|
AjaxCall call = extractFolderAjax(html, pwd);
|
||||||
|
return call == null ? null : call.path();
|
||||||
|
}
|
||||||
|
|
||||||
private static String resolveJsValue(String html, String raw) {
|
private static String resolveJsValue(String html, String raw) {
|
||||||
if (raw == null) {
|
if (raw == null) {
|
||||||
return "";
|
return "";
|
||||||
@@ -1075,7 +1104,7 @@ public class LzTool extends PanBase {
|
|||||||
private static String originOf(String url, String fallback) {
|
private static String originOf(String url, String fallback) {
|
||||||
try {
|
try {
|
||||||
URL u = new URL(url);
|
URL u = new URL(url);
|
||||||
return u.getProtocol() + "://" + u.getHost();
|
return u.getProtocol() + "://" + u.getHost() + (u.getPort() == -1 ? "" : ":" + u.getPort());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
@@ -1127,6 +1156,14 @@ public class LzTool extends PanBase {
|
|||||||
complete(downloadUrl);
|
complete(downloadUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 目录分享页和 filemoreajax.php 都用移动端 UA。文件页仍走桌面 UA,才能拿到 iframe。 */
|
||||||
|
private static MultiMap folderPageHeaders(String referer) {
|
||||||
|
MultiMap headers = folderListHeaders(referer);
|
||||||
|
headers.set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
|
||||||
|
headers.set("Accept-Encoding", "identity");
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
|
|
||||||
/** 目录列表 filemoreajax.php 用移动端 UA。 */
|
/** 目录列表 filemoreajax.php 用移动端 UA。 */
|
||||||
private static MultiMap folderListHeaders(String referer) {
|
private static MultiMap folderListHeaders(String referer) {
|
||||||
MultiMap headers = MultiMap.caseInsensitiveMultiMap();
|
MultiMap headers = MultiMap.caseInsensitiveMultiMap();
|
||||||
@@ -1146,18 +1183,77 @@ public class LzTool extends PanBase {
|
|||||||
|
|
||||||
final String sUrl = resolveShareUrl();
|
final String sUrl = resolveShareUrl();
|
||||||
final String pwd = shareLinkInfo.getSharePassword();
|
final String pwd = shareLinkInfo.getSharePassword();
|
||||||
|
final int page;
|
||||||
|
try {
|
||||||
|
page = FolderPaging.pageOrFirst(shareLinkInfo);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
listPromise.fail(baseMsg() + e.getMessage());
|
||||||
|
return listPromise.future();
|
||||||
|
}
|
||||||
|
|
||||||
getWithArg1Retry(sUrl, PAGE_HEADERS)
|
LzFolderCursor cursor = page > 1
|
||||||
.onSuccess(html -> handleFileListParse(html, pwd, sUrl, listPromise))
|
? LzFolderCursor.decode(FolderPaging.cursor(shareLinkInfo), shareLinkInfo.getShareKey(), page)
|
||||||
.onFailure(listPromise::fail);
|
: 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));
|
||||||
return listPromise.future();
|
return listPromise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleFileListParse(String html, String pwd, String sUrl, Promise<List<FileInfo>> listPromise) {
|
/** 游标过期(令牌约 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) {
|
||||||
if (!isLzFolderShare(sUrl, html)) {
|
if (!isLzFolderShare(sUrl, html)) {
|
||||||
listPromise.fail(baseMsg() + "该链接为蓝奏云文件分享,请使用文件解析接口");
|
listPromise.fail(baseMsg() + "该链接为蓝奏云文件分享,请使用文件解析接口");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (isAccessRiskPage(html)) {
|
||||||
|
listPromise.fail(baseMsg() + "蓝奏云返回了访问风控页,不能据此判断分享已失效,请稍后重试");
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
String webpage = extractWebpage(sUrl, html);
|
String webpage = extractWebpage(sUrl, html);
|
||||||
if (webpage != null) {
|
if (webpage != null) {
|
||||||
@@ -1169,14 +1265,106 @@ public class LzTool extends PanBase {
|
|||||||
}
|
}
|
||||||
log.debug("解析参数: {}", call.form());
|
log.debug("解析参数: {}", call.form());
|
||||||
|
|
||||||
postAjaxWithFallback(sUrl, call, folderListHeaders(sUrl),
|
walkFolderPages(sUrl, call, 1, page, listPromise);
|
||||||
body -> handleFileListResponse(body, listPromise),
|
|
||||||
listPromise::fail);
|
|
||||||
} catch (ScriptException | NoSuchMethodException | RuntimeException e) {
|
} catch (ScriptException | NoSuchMethodException | RuntimeException e) {
|
||||||
listPromise.fail(e);
|
listPromise.fail(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同一组 t/k 从第 {@code pg} 页顺序翻到 {@code target} 页。新令牌不能跳页,
|
||||||
|
* 两次请求间隔不足约 1.5 秒会返回 zt=4,所以逐页间隔 {@link #LZ_PAGE_INTERVAL_MS};
|
||||||
|
* 次数受 {@link #LZ_MAX_WALK_PAGES} 限制。
|
||||||
|
*/
|
||||||
|
private void walkFolderPages(String sUrl, AjaxCall call, int pg, int target,
|
||||||
|
Promise<List<FileInfo>> listPromise) {
|
||||||
|
postFolderPage(sUrl, call, pg, 0, reply -> {
|
||||||
|
if (reply.zt() == 1) {
|
||||||
|
if (pg == target) {
|
||||||
|
finishFolderPage(call, target, reply, listPromise);
|
||||||
|
} else if (reply.rawCount() < LZ_FOLDER_PAGE_SIZE) {
|
||||||
|
finishEmptyFolderPage(target, listPromise);
|
||||||
|
} else {
|
||||||
|
WebClientVertxInit.get().setTimer(LZ_PAGE_INTERVAL_MS,
|
||||||
|
id -> walkFolderPages(sUrl, call, pg + 1, target, listPromise));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (target == 1) {
|
||||||
|
listPromise.tryFail(baseMsg() + reply.info());
|
||||||
|
} else if (reply.zt() == 2) {
|
||||||
|
finishEmptyFolderPage(target, listPromise);
|
||||||
|
} else {
|
||||||
|
listPromise.tryFail(baseMsg() + "蓝奏云目录第 " + pg + " 页获取失败: " + reply.info()
|
||||||
|
+ ";未取到第 " + target + " 页,目录列表不完整,请稍后重试");
|
||||||
|
}
|
||||||
|
}, listPromise::tryFail);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取一页;zt=4(请求过快)时同一令牌等一会儿重试,最多 {@link #LZ_REFRESH_RETRIES} 次。 */
|
||||||
|
private void postFolderPage(String sUrl, AjaxCall call, int pg, int attempt,
|
||||||
|
Handler<FolderReply> onReply, Handler<Throwable> onFailure) {
|
||||||
|
call.form().put("pg", String.valueOf(pg));
|
||||||
|
postAjaxWithFallback(sUrl, call, folderListHeaders(sUrl), body -> {
|
||||||
|
FolderReply reply = FolderReply.parse(body);
|
||||||
|
if (reply == null) {
|
||||||
|
onFailure.handle(new RuntimeException(baseMsg() + "目录列表返回非JSON"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (reply.zt() == LZ_ZT_REFRESH && attempt < LZ_REFRESH_RETRIES) {
|
||||||
|
long delay = LZ_REFRESH_RETRY_DELAYS_MS[attempt];
|
||||||
|
log.debug("蓝奏目录第 {} 页返回 {},{}ms 后重试", pg, reply.info(), delay);
|
||||||
|
WebClientVertxInit.get().setTimer(delay,
|
||||||
|
id -> postFolderPage(sUrl, call, pg, attempt + 1, onReply, onFailure));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onReply.handle(reply);
|
||||||
|
}, onFailure);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishEmptyFolderPage(int page, Promise<List<FileInfo>> listPromise) {
|
||||||
|
FolderPaging.pageInfo(shareLinkInfo, page, LZ_FOLDER_PAGE_SIZE, false, null, null, null);
|
||||||
|
listPromise.tryComplete(new ArrayList<>());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishFolderPage(AjaxCall call, int page, FolderReply reply, Promise<List<FileInfo>> listPromise) {
|
||||||
|
try {
|
||||||
|
List<FileInfo> list = toFolderFileInfos(reply.items());
|
||||||
|
boolean hasMore = reply.rawCount() >= LZ_FOLDER_PAGE_SIZE;
|
||||||
|
String next = hasMore
|
||||||
|
? LzFolderCursor.encode(shareLinkInfo.getShareKey(), call.path(), call.form(), page + 1,
|
||||||
|
currentWebpage())
|
||||||
|
: null;
|
||||||
|
FolderPaging.pageInfo(shareLinkInfo, page, LZ_FOLDER_PAGE_SIZE, hasMore, null, null, next);
|
||||||
|
listPromise.tryComplete(list);
|
||||||
|
} catch (Exception e) {
|
||||||
|
listPromise.tryFail(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** filemoreajax.php 单页响应;text 不是数组时 items 为空。 */
|
||||||
|
record FolderReply(int zt, String info, List<JsonObject> items, int rawCount) {
|
||||||
|
static FolderReply parse(String body) {
|
||||||
|
JsonObject json = parseLzJson(body);
|
||||||
|
if (json == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Integer zt = jsonInt(json, "zt");
|
||||||
|
Object info = json.getValue("info");
|
||||||
|
List<JsonObject> items = new ArrayList<>();
|
||||||
|
Object text = json.getValue("text");
|
||||||
|
if (text instanceof JsonArray arr) {
|
||||||
|
for (Object o : arr) {
|
||||||
|
if (o instanceof JsonObject item) {
|
||||||
|
items.add(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new FolderReply(zt == null ? -1 : zt, info == null ? null : String.valueOf(info),
|
||||||
|
items, items.size());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 正则匹配不到 filemoreajax 块时,回退到执行页面 JS 取参数。 */
|
/** 正则匹配不到 filemoreajax 块时,回退到执行页面 JS 取参数。 */
|
||||||
private AjaxCall folderAjaxFromJs(String html, String pwd) throws ScriptException, NoSuchMethodException {
|
private AjaxCall folderAjaxFromJs(String html, String pwd) throws ScriptException, NoSuchMethodException {
|
||||||
String jsText = getJsByPwd(pwd, html, "var urls =window.location.href");
|
String jsText = getJsByPwd(pwd, html, "var urls =window.location.href");
|
||||||
@@ -1213,6 +1401,26 @@ public class LzTool extends PanBase {
|
|||||||
return path.charAt(0) == 'b' || path.charAt(0) == 'B';
|
return path.charAt(0) == 'b' || path.charAt(0) == 'B';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 桌面 UA 下的空白提示页:有 off1,隐藏块里是 folder 编号和访问 IP,没有取消分享文案,
|
||||||
|
* 也没有目录参数。这是访问风控,不是分享失效。
|
||||||
|
*/
|
||||||
|
static boolean isAccessRiskPage(String html) {
|
||||||
|
if (html == null || html.isBlank()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (html.contains("filemoreajax") || html.contains(ARG1_MARK)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!html.contains("off1")) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (html.contains("取消分享") || html.contains("不存在") || html.contains("地址错误")) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return html.contains("folder") && html.contains("ip");
|
||||||
|
}
|
||||||
|
|
||||||
private static boolean isLzFolderHtml(String html) {
|
private static boolean isLzFolderHtml(String html) {
|
||||||
if (html == null || html.isBlank()) {
|
if (html == null || html.isBlank()) {
|
||||||
return false;
|
return false;
|
||||||
@@ -1249,66 +1457,59 @@ public class LzTool extends PanBase {
|
|||||||
return u;
|
return u;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleFileListResponse(String responseBody, Promise<List<FileInfo>> listPromise) {
|
/**
|
||||||
try {
|
* 目录页 JS 不渲染 id 为 -1 的占位项(如「***.apk」),这里同样跳过;它仍计入每页 50 条。
|
||||||
JsonObject fileListJson = parseLzJson(responseBody);
|
* 同一页里重复的 id 只保留第一条。
|
||||||
if (fileListJson == null) {
|
*/
|
||||||
listPromise.fail(baseMsg() + "目录列表返回非JSON");
|
private List<FileInfo> toFolderFileInfos(List<JsonObject> items) {
|
||||||
return;
|
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
|
||||||
}
|
}
|
||||||
Integer zt = fileListJson.getInteger("zt");
|
*/
|
||||||
if (zt == null || zt != 1) {
|
String id = fileJson.getString("id");
|
||||||
listPromise.fail(baseMsg() + fileListJson.getString("info"));
|
if (id == null || id.isBlank() || LZ_PLACEHOLDER_ID.equals(id) || !seen.add(id)) {
|
||||||
return;
|
continue;
|
||||||
}
|
}
|
||||||
List<FileInfo> list = new ArrayList<>();
|
FileInfo fileInfo = new FileInfo();
|
||||||
fileListJson.getJsonArray("text").forEach(item -> {
|
String size = fileJson.getString("size");
|
||||||
/*
|
Long sizeNum = FileSizeConverter.convertToBytes(size);
|
||||||
{
|
String panType = shareLinkInfo.getType();
|
||||||
"icon": "apk",
|
String fileName = fileJson.getString("name_all");
|
||||||
"t": 0,
|
// 构建 base64 参数,用于 /v2/redirectUrl 接口
|
||||||
"id": "iULV2n4361c",
|
JsonObject paramJson = new JsonObject()
|
||||||
"name_all": "xx.apk",
|
.put("id", id)
|
||||||
"size": "49.8 M",
|
.put("fileName", fileName)
|
||||||
"time": "2021-03-19",
|
.put("shareKey", shareLinkInfo.getShareKey());
|
||||||
"duan": "in4361",
|
String webpage = currentWebpage();
|
||||||
"p_ico": 0
|
if (webpage != null) {
|
||||||
}
|
paramJson.put("webpage", webpage);
|
||||||
*/
|
}
|
||||||
JsonObject fileJson = (JsonObject) item;
|
String param = CommonUtils.urlBase64Encode(paramJson.encode());
|
||||||
FileInfo fileInfo = new FileInfo();
|
fileInfo.setFileName(fileName)
|
||||||
String size = fileJson.getString("size");
|
.setFileId(id)
|
||||||
Long sizeNum = FileSizeConverter.convertToBytes(size);
|
.setCreateTime(fileJson.getString("time"))
|
||||||
String panType = shareLinkInfo.getType();
|
.setFileType(fileJson.getString("icon"))
|
||||||
String id = fileJson.getString("id");
|
.setSizeStr(fileJson.getString("size"))
|
||||||
String fileName = fileJson.getString("name_all");
|
.setSize(sizeNum)
|
||||||
// 构建 base64 参数,用于 /v2/redirectUrl 接口
|
.setPanType(panType)
|
||||||
JsonObject paramJson = new JsonObject()
|
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(), panType, param))
|
||||||
.put("id", id)
|
.setPreviewUrl(String.format("%s/v2/view/%s/%s", getDomainName(),
|
||||||
.put("fileName", fileName)
|
shareLinkInfo.getType(), id));
|
||||||
.put("shareKey", shareLinkInfo.getShareKey());
|
log.debug("文件信息: {}", fileInfo);
|
||||||
String webpage = currentWebpage();
|
list.add(fileInfo);
|
||||||
if (webpage != null) {
|
|
||||||
paramJson.put("webpage", webpage);
|
|
||||||
}
|
|
||||||
String param = CommonUtils.urlBase64Encode(paramJson.encode());
|
|
||||||
fileInfo.setFileName(fileName)
|
|
||||||
.setFileId(id)
|
|
||||||
.setCreateTime(fileJson.getString("time"))
|
|
||||||
.setFileType(fileJson.getString("icon"))
|
|
||||||
.setSizeStr(fileJson.getString("size"))
|
|
||||||
.setSize(sizeNum)
|
|
||||||
.setPanType(panType)
|
|
||||||
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(), panType, param))
|
|
||||||
.setPreviewUrl(String.format("%s/v2/view/%s/%s", getDomainName(),
|
|
||||||
shareLinkInfo.getType(), id));
|
|
||||||
log.debug("文件信息: {}", fileInfo);
|
|
||||||
list.add(fileInfo);
|
|
||||||
});
|
|
||||||
listPromise.complete(list);
|
|
||||||
} catch (Exception e) {
|
|
||||||
listPromise.fail(e);
|
|
||||||
}
|
}
|
||||||
|
return list;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
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; }};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package cn.qaiu.parser.impl;
|
||||||
|
|
||||||
|
import cn.qaiu.WebClientVertxInit;
|
||||||
|
import cn.qaiu.entity.ShareLinkInfo;
|
||||||
|
import io.vertx.core.MultiMap;
|
||||||
|
import io.vertx.core.Vertx;
|
||||||
|
import io.vertx.core.http.HttpServer;
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CopyOnWriteArrayList;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 蓝奏文件页离线回归:2026-11 起文件页 iframe 的下载 ajax 改名为 ajaxfiles.php,
|
||||||
|
* 其余字段(wp_sign / ajaxdata / kd / ves)不变。本地模拟 分享页 → /fn iframe → ajaxfiles.php → 下载域 302。
|
||||||
|
*/
|
||||||
|
public class LzToolAjaxfilesTest {
|
||||||
|
|
||||||
|
private static final String SHARE_KEY = "winx123";
|
||||||
|
private static final String FILE_ID = "333017612";
|
||||||
|
|
||||||
|
private Vertx vertx;
|
||||||
|
private HttpServer server;
|
||||||
|
private final List<String> ajaxPaths = new CopyOnWriteArrayList<>();
|
||||||
|
private final List<MultiMap> ajaxForms = new CopyOnWriteArrayList<>();
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws Exception {
|
||||||
|
vertx = Vertx.vertx();
|
||||||
|
WebClientVertxInit.init(vertx);
|
||||||
|
server = vertx.createHttpServer().requestHandler(req -> {
|
||||||
|
String path = req.path();
|
||||||
|
if ("GET".equals(req.method().name()) && path.equals("/" + SHARE_KEY)) {
|
||||||
|
html(req.response(), sharePage());
|
||||||
|
} else if ("GET".equals(req.method().name()) && path.equals("/fn")) {
|
||||||
|
html(req.response(), iframePage());
|
||||||
|
} else if ("POST".equals(req.method().name()) && path.startsWith("/ajax")) {
|
||||||
|
req.setExpectMultipart(true);
|
||||||
|
req.endHandler(v -> {
|
||||||
|
ajaxPaths.add(req.uri());
|
||||||
|
ajaxForms.add(MultiMap.caseInsensitiveMultiMap().addAll(req.formAttributes()));
|
||||||
|
String dom = "http://127.0.0.1:" + server.actualPort();
|
||||||
|
req.response().putHeader("Content-Type", "application/json")
|
||||||
|
.end("{\"zt\":1,\"dom\":\"" + dom + "\",\"url\":\"?mock-token\",\"inf\":0}");
|
||||||
|
});
|
||||||
|
} else if (path.equals("/file/")) {
|
||||||
|
req.response().setStatusCode(302)
|
||||||
|
.putHeader("Location", "http://cdn.test/2026/11/25/steam.zip")
|
||||||
|
.end();
|
||||||
|
} else {
|
||||||
|
req.response().setStatusCode(404).end();
|
||||||
|
}
|
||||||
|
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void cleanup() throws Exception {
|
||||||
|
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||||
|
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void filePageWithAjaxfilesIframeResolvesDirectLink() throws Exception {
|
||||||
|
String url = "http://127.0.0.1:" + server.actualPort() + "/" + SHARE_KEY;
|
||||||
|
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("lz").panName("蓝奏云").shareKey(SHARE_KEY)
|
||||||
|
.shareUrl(url).standardUrl(url).build();
|
||||||
|
|
||||||
|
String link = new LzTool(info).parse().toCompletionStage().toCompletableFuture()
|
||||||
|
.get(30, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
assertEquals("http://cdn.test/2026/11/25/steam.zip", link);
|
||||||
|
assertEquals(List.of("/ajaxfiles.php?file=" + FILE_ID), ajaxPaths);
|
||||||
|
MultiMap form = ajaxForms.get(0);
|
||||||
|
assertEquals("downprocess", form.get("action"));
|
||||||
|
assertEquals("test-wp-sign", form.get("sign"));
|
||||||
|
assertEquals("test-ajaxdata", form.get("websignkey"));
|
||||||
|
assertEquals("test-ajaxdata", form.get("signs"));
|
||||||
|
assertEquals("1", form.get("ves"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void html(io.vertx.core.http.HttpServerResponse res, String body) {
|
||||||
|
res.putHeader("Content-Type", "text/html; charset=utf-8").end(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String sharePage() {
|
||||||
|
return """
|
||||||
|
<!DOCTYPE html><html><head><title>steam.zip - 蓝奏云</title>
|
||||||
|
<meta name="description" content="文件大小:1.1 M" /></head><body>
|
||||||
|
<div class="n_box_3fn" id="filenajax">steam.zip</div>
|
||||||
|
<div class="n_file"><div class="n_filesize">大小:1.1 M</div>
|
||||||
|
<iframe class="n_downlink" name="1795620352" src="/fn?mock-fn-query" frameborder="0" scrolling="no"></iframe></div>
|
||||||
|
</body></html>
|
||||||
|
""";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String iframePage() {
|
||||||
|
return """
|
||||||
|
<html><body><div id="tourl"></div>
|
||||||
|
<script type="text/javascript">
|
||||||
|
var wsk_sign = 'c20230908';
|
||||||
|
var wp_sign = 'test-wp-sign';
|
||||||
|
var ajaxdata = 'test-ajaxdata';
|
||||||
|
var kdns =1;
|
||||||
|
$.ajax({
|
||||||
|
type : 'post',
|
||||||
|
url : '/ajaxfiles.php?file=%s',
|
||||||
|
data : { 'action':'downprocess','websignkey':ajaxdata,'signs':ajaxdata,'sign':wp_sign,'websign':'','kd':kdns,'ves':1 },
|
||||||
|
dataType : 'json'
|
||||||
|
});
|
||||||
|
</script></body></html>
|
||||||
|
""".formatted(FILE_ID);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
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,8 +4,11 @@ import org.junit.Test;
|
|||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -153,6 +156,16 @@ public class LzToolShareUrlTest {
|
|||||||
assertEquals("https://apifile.lanzouw.com/ajaxm.php?file=42", LzTool.fileAjaxTarget(html));
|
assertEquals("https://apifile.lanzouw.com/ajaxm.php?file=42", LzTool.fileAjaxTarget(html));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ajaxfilesEndpointIsRecognized() {
|
||||||
|
assertEquals("/ajaxfiles.php?file=333017612",
|
||||||
|
LzTool.fileAjaxTarget("url : '/ajaxfiles.php?file=333017612',"));
|
||||||
|
assertEquals("https://apifile.lanzouw.com/ajaxfiles.php?file=7",
|
||||||
|
LzTool.fileAjaxTarget("url : 'https://apifile.lanzouw.com/ajaxfiles.php?file=7',"));
|
||||||
|
assertEquals("/ajaxm.php?file=5", LzTool.fileAjaxTarget("url : '/ajaxm.php?file=5',"));
|
||||||
|
assertNull(LzTool.fileAjaxTarget("url : '/ajaxfilex.php?file=5',"));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void relativeFileAjaxFallsThroughToApifileBeforeWwww() {
|
public void relativeFileAjaxFallsThroughToApifileBeforeWwww() {
|
||||||
String html = "url : '/ajaxfile.php?file=150233466',";
|
String html = "url : '/ajaxfile.php?file=150233466',";
|
||||||
@@ -167,6 +180,55 @@ public class LzToolShareUrlTest {
|
|||||||
assertFalse(LzTool.ajaxOrigins("https://a.lanzouw.com/xxx").contains("https://apifile.lanzouw.com"));
|
assertFalse(LzTool.ajaxOrigins("https://a.lanzouw.com/xxx").contains("https://apifile.lanzouw.com"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void oldFolderPageSuppliesFilemoreParameters() {
|
||||||
|
String html = """
|
||||||
|
<script type="text/javascript">
|
||||||
|
var ibb6kj = '111';
|
||||||
|
var demoKey = 'abc';
|
||||||
|
function file(){
|
||||||
|
$.ajax({
|
||||||
|
url : '/filemoreajax.php?file=66477',
|
||||||
|
data : {
|
||||||
|
'lx':2,
|
||||||
|
'fid':66477,
|
||||||
|
'uid':'11',
|
||||||
|
'pg':pgs,
|
||||||
|
't':ibb6kj,
|
||||||
|
'k':demoKey,
|
||||||
|
'up':1,
|
||||||
|
'pwd':pwd
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
""";
|
||||||
|
Map<String, String> form = LzTool.folderAjaxForm(html, "1234");
|
||||||
|
assertEquals("66477", form.get("fid"));
|
||||||
|
assertEquals("111", form.get("t"));
|
||||||
|
assertEquals("abc", form.get("k"));
|
||||||
|
assertEquals("1", form.get("pg"));
|
||||||
|
assertEquals("1234", form.get("pwd"));
|
||||||
|
assertEquals("/filemoreajax.php?file=66477", LzTool.folderAjaxPath(html, "1234"));
|
||||||
|
assertFalse(LzTool.isAccessRiskPage(html));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void blankOffPageIsRiskControlNotExpiry() {
|
||||||
|
String html = """
|
||||||
|
<div class="off"><div class="off0"><div class="off1"></div></div></div>
|
||||||
|
<div style="display:none ">folder66477ufolder66477ip203.0.113.8</div>
|
||||||
|
""";
|
||||||
|
assertTrue(LzTool.isAccessRiskPage(html));
|
||||||
|
assertNull(LzTool.folderAjaxForm(html, null));
|
||||||
|
|
||||||
|
String cancelled = """
|
||||||
|
<div class="off"><div class="off1"></div></div>
|
||||||
|
文件取消分享了
|
||||||
|
""";
|
||||||
|
assertFalse(LzTool.isAccessRiskPage(cancelled));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void missingAjaxTargetStillPutsApifileBeforeWwww() {
|
public void missingAjaxTargetStillPutsApifileBeforeWwww() {
|
||||||
List<String> origins = LzTool.fileAjaxOrigins("https://www.lanzoux.com/ihLkw1gezutg", null);
|
List<String> origins = LzTool.fileAjaxOrigins("https://www.lanzoux.com/ihLkw1gezutg", null);
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<revision>0.4.11</revision>
|
<revision>0.4.13</revision>
|
||||||
<java.version>17</java.version>
|
<java.version>17</java.version>
|
||||||
<maven.compiler.source>17</maven.compiler.source>
|
<maven.compiler.source>17</maven.compiler.source>
|
||||||
<maven.compiler.target>17</maven.compiler.target>
|
<maven.compiler.target>17</maven.compiler.target>
|
||||||
@@ -32,7 +32,7 @@
|
|||||||
<slf4j.version>2.0.16</slf4j.version>
|
<slf4j.version>2.0.16</slf4j.version>
|
||||||
<commons-lang3.version>3.18.0</commons-lang3.version>
|
<commons-lang3.version>3.18.0</commons-lang3.version>
|
||||||
<commons-beanutils2.version>2.0.0</commons-beanutils2.version>
|
<commons-beanutils2.version>2.0.0</commons-beanutils2.version>
|
||||||
<parserVersion>10.2.5</parserVersion>
|
<parserVersion>10.2.6</parserVersion>
|
||||||
<jackson.version>2.18.9</jackson.version>
|
<jackson.version>2.18.9</jackson.version>
|
||||||
<!-- Logback 最新稳定版 -->
|
<!-- Logback 最新稳定版 -->
|
||||||
<logback.version>1.5.34</logback.version>
|
<logback.version>1.5.34</logback.version>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "nfd-web",
|
"name": "nfd-web",
|
||||||
"version": "0.4.11",
|
"version": "0.4.13",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"serve": "vue-cli-service serve",
|
"serve": "vue-cli-service serve",
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
"build": "node scripts/sync-version.js && vue-cli-service build && node scripts/compress-vs.js",
|
"build": "node scripts/sync-version.js && vue-cli-service build && node scripts/compress-vs.js",
|
||||||
"build:no-compress": "node scripts/sync-version.js && vue-cli-service build",
|
"build:no-compress": "node scripts/sync-version.js && vue-cli-service build",
|
||||||
"lint": "vue-cli-service lint",
|
"lint": "vue-cli-service lint",
|
||||||
"test": "node --test src/utils/batchTreeCollect.spec.js"
|
"test": "node --test src/utils/batchTreeCollect.spec.js src/utils/folderPaging.spec.js src/utils/nameFilter.spec.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@element-plus/icons-vue": "^2.3.1",
|
"@element-plus/icons-vue": "^2.3.1",
|
||||||
|
|||||||
+273
-31
@@ -292,6 +292,96 @@
|
|||||||
gap: 10px;
|
gap: 10px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.load-more {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 12px 0 4px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: #7f8c8d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.load-more button {
|
||||||
|
padding: 6px 14px;
|
||||||
|
border: 1px solid #3498db;
|
||||||
|
background: #fff;
|
||||||
|
color: #3498db;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.load-more button:disabled {
|
||||||
|
opacity: .6;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.name-filter-bar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px 14px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
padding: 12px 24px;
|
||||||
|
background: #fff;
|
||||||
|
border-bottom: 1px solid #eaeaea;
|
||||||
|
}
|
||||||
|
|
||||||
|
.name-filter-input {
|
||||||
|
flex: 1 1 220px;
|
||||||
|
max-width: 420px;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
border: 1px solid #dcdfe6;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0 10px;
|
||||||
|
min-height: 36px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.name-filter-input i {
|
||||||
|
color: #909399;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.name-filter-input input {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
border: 0;
|
||||||
|
outline: none;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.4;
|
||||||
|
padding: 8px 0;
|
||||||
|
background: transparent;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-hint {
|
||||||
|
flex: 1 1 200px;
|
||||||
|
min-width: 0;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.45;
|
||||||
|
color: #909399;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.name-filter-bar {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
padding: 10px 12px;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
.name-filter-input,
|
||||||
|
.filter-hint {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
max-width: none;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.name-filter-input {
|
||||||
|
min-height: 40px;
|
||||||
|
}
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -306,6 +396,14 @@
|
|||||||
<!-- 面包屑导航会通过JS动态生成 -->
|
<!-- 面包屑导航会通过JS动态生成 -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="name-filter-bar">
|
||||||
|
<label class="name-filter-input">
|
||||||
|
<i class="fas fa-search" aria-hidden="true"></i>
|
||||||
|
<input id="name-filter" type="search" placeholder="按文件名筛选" autocomplete="off" autocorrect="off" spellcheck="false" aria-label="按文件名筛选" />
|
||||||
|
</label>
|
||||||
|
<span id="filter-hint" class="filter-hint" hidden></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="content">
|
<div class="content">
|
||||||
<div class="grid-view" id="file-grid">
|
<div class="grid-view" id="file-grid">
|
||||||
<!-- 文件列表会通过JS动态生成 -->
|
<!-- 文件列表会通过JS动态生成 -->
|
||||||
@@ -409,6 +507,113 @@
|
|||||||
};
|
};
|
||||||
const pathStack = [currentDir];
|
const pathStack = [currentDir];
|
||||||
|
|
||||||
|
// 目录分页:/v2/getFileList 链接换成 /v2/getFileListPage 并带 page / pageCursor
|
||||||
|
let more = null;
|
||||||
|
let loadSeq = 0;
|
||||||
|
let seenKeys = new Set();
|
||||||
|
let folderCount = 0;
|
||||||
|
let fileCount = 0;
|
||||||
|
// 已加载的完整列表。筛选只看这里,规则与 src/utils/nameFilter.js 一致。
|
||||||
|
let loadedFiles = [];
|
||||||
|
let nameFilter = '';
|
||||||
|
const moreEl = document.createElement('div');
|
||||||
|
moreEl.className = 'load-more';
|
||||||
|
moreEl.style.display = 'none';
|
||||||
|
|
||||||
|
function toPageUrl(listUrl, page, cursor) {
|
||||||
|
const m = String(listUrl || '').match(/^(.*?\/v2\/getFileList)(\?.*)?$/);
|
||||||
|
if (!m) return null;
|
||||||
|
let url = `${m[1]}Page${m[2] || ''}`;
|
||||||
|
url += (url.includes('?') ? '&' : '?') + `page=${encodeURIComponent(page)}`;
|
||||||
|
if (cursor) url += `&pageCursor=${encodeURIComponent(cursor)}`;
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readPage(data) {
|
||||||
|
if (Array.isArray(data)) return { list: data, hasMore: false };
|
||||||
|
const d = data || {};
|
||||||
|
const hasMore = !!d.hasMore && Number.isInteger(d.nextPage);
|
||||||
|
return { list: Array.isArray(d.list) ? d.list : [], hasMore, nextPage: d.nextPage, nextCursor: d.nextCursor || null };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchJson(url) {
|
||||||
|
const response = await fetch(url);
|
||||||
|
let data = null;
|
||||||
|
try {
|
||||||
|
data = await response.json();
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
|
}
|
||||||
|
if (data && data.code === 200 && data.success) return data;
|
||||||
|
throw new Error((data && data.msg) || `获取文件列表失败 (HTTP ${response.status})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fileKey(file) {
|
||||||
|
return `${file.parserUrl || ''}::${file.fileName || ''}::${file.fileId || file.id || ''}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeQuery(keyword) {
|
||||||
|
return String(keyword == null ? '' : keyword).trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function filterByFileName(list, keyword) {
|
||||||
|
const rows = list || [];
|
||||||
|
const query = normalizeQuery(keyword);
|
||||||
|
if (!query) return rows.slice();
|
||||||
|
return rows.filter(file => String((file && file.fileName) || '').toLowerCase().includes(query));
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderMore() {
|
||||||
|
if (!more) {
|
||||||
|
moreEl.style.display = 'none';
|
||||||
|
moreEl.innerHTML = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
moreEl.style.display = '';
|
||||||
|
const total = folderCount + fileCount;
|
||||||
|
const label = more.loading ? '加载中…' : (more.error ? '加载失败,点击重试' : '加载更多');
|
||||||
|
const hint = more.error ? `已加载 ${total} 项:${more.error}` : `已加载 ${total} 项,滚动到底部自动加载`;
|
||||||
|
moreEl.innerHTML = '';
|
||||||
|
const btn = document.createElement('button');
|
||||||
|
btn.textContent = label;
|
||||||
|
btn.disabled = !!more.loading;
|
||||||
|
btn.addEventListener('click', loadMore);
|
||||||
|
const span = document.createElement('span');
|
||||||
|
span.textContent = hint;
|
||||||
|
moreEl.appendChild(btn);
|
||||||
|
moreEl.appendChild(span);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 加载失败只提示重试,已加载的条目保留;失败后暂停滚动自动加载
|
||||||
|
async function loadMore() {
|
||||||
|
const state = more;
|
||||||
|
if (!state || state.loading) return;
|
||||||
|
const seq = loadSeq;
|
||||||
|
state.loading = true;
|
||||||
|
state.error = '';
|
||||||
|
renderMore();
|
||||||
|
try {
|
||||||
|
const data = await fetchJson(toPageUrl(state.listUrl, state.nextPage, state.nextCursor));
|
||||||
|
if (seq !== loadSeq || more !== state) return;
|
||||||
|
const page = readPage(data.data);
|
||||||
|
renderFileList(page.list, true);
|
||||||
|
more = page.hasMore ? { listUrl: state.listUrl, nextPage: page.nextPage, nextCursor: page.nextCursor } : null;
|
||||||
|
} catch (error) {
|
||||||
|
if (seq !== loadSeq || more !== state) return;
|
||||||
|
state.error = error.message || '加载下一页失败';
|
||||||
|
} finally {
|
||||||
|
state.loading = false;
|
||||||
|
renderMore();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof IntersectionObserver !== 'undefined') {
|
||||||
|
new IntersectionObserver(entries => {
|
||||||
|
// 有关键字时不自动翻页,避免筛选结果变短后把后续页一次拉完
|
||||||
|
if (more && !more.loading && !more.error && !normalizeQuery(nameFilter) && entries.some(e => e.isIntersecting)) loadMore();
|
||||||
|
}).observe(moreEl);
|
||||||
|
}
|
||||||
|
|
||||||
// DOM 元素
|
// DOM 元素
|
||||||
const breadcrumbEl = document.getElementById('breadcrumb');
|
const breadcrumbEl = document.getElementById('breadcrumb');
|
||||||
const fileGridEl = document.getElementById('file-grid');
|
const fileGridEl = document.getElementById('file-grid');
|
||||||
@@ -418,6 +623,14 @@
|
|||||||
|
|
||||||
// 初始化
|
// 初始化
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
fileGridEl.insertAdjacentElement('afterend', moreEl);
|
||||||
|
const nameInput = document.getElementById('name-filter');
|
||||||
|
if (nameInput) {
|
||||||
|
nameInput.addEventListener('input', () => {
|
||||||
|
nameFilter = nameInput.value;
|
||||||
|
renderLoadedFiles();
|
||||||
|
});
|
||||||
|
}
|
||||||
renderBreadcrumb();
|
renderBreadcrumb();
|
||||||
fetchFileList(currentDir.url);
|
fetchFileList(currentDir.url);
|
||||||
|
|
||||||
@@ -458,6 +671,9 @@
|
|||||||
|
|
||||||
// 获取文件列表
|
// 获取文件列表
|
||||||
async function fetchFileList(url) {
|
async function fetchFileList(url) {
|
||||||
|
const seq = ++loadSeq;
|
||||||
|
more = null;
|
||||||
|
renderMore();
|
||||||
try {
|
try {
|
||||||
// 显示加载状态
|
// 显示加载状态
|
||||||
fileGridEl.innerHTML = `
|
fileGridEl.innerHTML = `
|
||||||
@@ -466,18 +682,15 @@
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const response = await fetch(url);
|
const pageUrl = toPageUrl(url, 1);
|
||||||
if (!response.ok) {
|
const data = await fetchJson(pageUrl || url);
|
||||||
throw new Error(`HTTP error! status: ${response.status}`);
|
if (seq !== loadSeq) return;
|
||||||
}
|
const page = readPage(data.data);
|
||||||
const data = await response.json();
|
renderFileList(page.list);
|
||||||
|
more = pageUrl && page.hasMore ? { listUrl: url, nextPage: page.nextPage, nextCursor: page.nextCursor } : null;
|
||||||
if (data.code === 200 && data.success) {
|
renderMore();
|
||||||
renderFileList(data.data);
|
|
||||||
} else {
|
|
||||||
throw new Error(data.msg || '获取文件列表失败');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (seq !== loadSeq) return;
|
||||||
console.error('获取文件列表失败:', error);
|
console.error('获取文件列表失败:', error);
|
||||||
fileGridEl.innerHTML = `
|
fileGridEl.innerHTML = `
|
||||||
<div class="empty-state">
|
<div class="empty-state">
|
||||||
@@ -489,32 +702,50 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 渲染文件列表
|
function updateFilterHint(matchedCount) {
|
||||||
function renderFileList(files) {
|
const hint = document.getElementById('filter-hint');
|
||||||
fileGridEl.innerHTML = '';
|
if (!hint) return;
|
||||||
|
const query = normalizeQuery(nameFilter);
|
||||||
|
if (!query) {
|
||||||
|
hint.hidden = true;
|
||||||
|
hint.textContent = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hint.hidden = false;
|
||||||
|
hint.textContent = `仅筛选已加载的 ${loadedFiles.length} 项,匹配 ${matchedCount} 项`;
|
||||||
|
}
|
||||||
|
|
||||||
if (!files || files.length === 0) {
|
// 按当前关键字重绘已加载列表。加载更多按钮在网格外面,无匹配时仍然在。
|
||||||
fileGridEl.innerHTML = `
|
function renderLoadedFiles() {
|
||||||
<div class="empty-state">
|
const visible = filterByFileName(loadedFiles, nameFilter);
|
||||||
|
fileGridEl.innerHTML = '';
|
||||||
|
folderCount = 0;
|
||||||
|
fileCount = 0;
|
||||||
|
|
||||||
|
if (!visible.length) {
|
||||||
|
const filtering = normalizeQuery(nameFilter) && loadedFiles.length;
|
||||||
|
fileGridEl.innerHTML = filtering
|
||||||
|
? `<div class="empty-state">
|
||||||
|
<i class="fas fa-search"></i>
|
||||||
|
<h3>没有匹配的文件</h3>
|
||||||
|
<p>换个关键字,或加载更多后再筛</p>
|
||||||
|
</div>`
|
||||||
|
: `<div class="empty-state">
|
||||||
<i class="fas fa-folder-open"></i>
|
<i class="fas fa-folder-open"></i>
|
||||||
<h3>此文件夹为空</h3>
|
<h3>此文件夹为空</h3>
|
||||||
<p>暂无文件或文件夹</p>
|
<p>暂无文件或文件夹</p>
|
||||||
</div>
|
</div>`;
|
||||||
`;
|
|
||||||
folderCountEl.textContent = '0';
|
folderCountEl.textContent = '0';
|
||||||
fileCountEl.textContent = '0';
|
fileCountEl.textContent = '0';
|
||||||
|
updateFilterHint(0);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let folderCount = 0;
|
visible.forEach(file => {
|
||||||
let fileCount = 0;
|
|
||||||
|
|
||||||
files.forEach(file => {
|
|
||||||
const item = document.createElement('div');
|
const item = document.createElement('div');
|
||||||
const metaText = fileMetaText(file);
|
const metaText = fileMetaText(file);
|
||||||
|
|
||||||
if (file.fileType === 'folder') {
|
if (file.fileType === 'folder') {
|
||||||
// 文件夹
|
|
||||||
item.className = 'item folder';
|
item.className = 'item folder';
|
||||||
item.innerHTML = `
|
item.innerHTML = `
|
||||||
<div class="item-icon">
|
<div class="item-icon">
|
||||||
@@ -524,16 +755,12 @@
|
|||||||
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
||||||
`;
|
`;
|
||||||
folderCount++;
|
folderCount++;
|
||||||
|
|
||||||
// 添加点击事件
|
|
||||||
item.addEventListener('click', () => {
|
item.addEventListener('click', () => {
|
||||||
enterFolder(file);
|
enterFolder(file);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// 文件
|
|
||||||
const fileExt = getFileExtension(file.fileName);
|
const fileExt = getFileExtension(file.fileName);
|
||||||
const fileTypeInfo = fileTypeIcons[fileExt.toLowerCase()] || fileTypeIcons['default'];
|
const fileTypeInfo = fileTypeIcons[fileExt.toLowerCase()] || fileTypeIcons['default'];
|
||||||
|
|
||||||
item.className = `item ${fileTypeInfo.type}`;
|
item.className = `item ${fileTypeInfo.type}`;
|
||||||
item.innerHTML = `
|
item.innerHTML = `
|
||||||
<div class="item-icon">
|
<div class="item-icon">
|
||||||
@@ -543,8 +770,6 @@
|
|||||||
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
||||||
`;
|
`;
|
||||||
fileCount++;
|
fileCount++;
|
||||||
|
|
||||||
// 添加点击事件
|
|
||||||
item.addEventListener('click', () => {
|
item.addEventListener('click', () => {
|
||||||
handleFileClick(file);
|
handleFileClick(file);
|
||||||
});
|
});
|
||||||
@@ -553,9 +778,26 @@
|
|||||||
fileGridEl.appendChild(item);
|
fileGridEl.appendChild(item);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 更新统计信息
|
|
||||||
folderCountEl.textContent = folderCount;
|
folderCountEl.textContent = folderCount;
|
||||||
fileCountEl.textContent = fileCount;
|
fileCountEl.textContent = fileCount;
|
||||||
|
updateFilterHint(visible.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 渲染文件列表
|
||||||
|
function renderFileList(files, append = false) {
|
||||||
|
if (!append) {
|
||||||
|
seenKeys = new Set();
|
||||||
|
loadedFiles = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
(files || []).forEach(file => {
|
||||||
|
const key = fileKey(file);
|
||||||
|
if (seenKeys.has(key)) return;
|
||||||
|
seenKeys.add(key);
|
||||||
|
loadedFiles.push(file);
|
||||||
|
});
|
||||||
|
|
||||||
|
renderLoadedFiles();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取文件扩展名
|
// 获取文件扩展名
|
||||||
|
|||||||
@@ -1,6 +1,20 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="main-container">
|
<div class="main-container">
|
||||||
<div class="directory-tree" :class="{ 'dark-theme': isDarkTheme }">
|
<div class="directory-tree" :class="{ 'dark-theme': isDarkTheme }">
|
||||||
|
<div class="dir-filter-bar">
|
||||||
|
<el-input
|
||||||
|
v-model="nameFilter"
|
||||||
|
class="dir-name-filter"
|
||||||
|
clearable
|
||||||
|
placeholder="按文件名筛选"
|
||||||
|
aria-label="按文件名筛选"
|
||||||
|
>
|
||||||
|
<template #prefix>
|
||||||
|
<i class="fas fa-search" aria-hidden="true"></i>
|
||||||
|
</template>
|
||||||
|
</el-input>
|
||||||
|
<p v-if="nameQuery" class="dir-filter-hint">仅筛选已加载的 {{ loadedCount }} 项,匹配 {{ matchedCount }} 项</p>
|
||||||
|
</div>
|
||||||
<template v-if="viewMode === 'pane'">
|
<template v-if="viewMode === 'pane'">
|
||||||
<!-- 窗格模式(原有) -->
|
<!-- 窗格模式(原有) -->
|
||||||
<div class="breadcrumb">
|
<div class="breadcrumb">
|
||||||
@@ -18,8 +32,8 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="file-grid" v-loading="loading">
|
<div class="file-grid" v-loading="loading">
|
||||||
<div
|
<div
|
||||||
v-for="file in currentFileList"
|
v-for="file in visibleFileList"
|
||||||
:key="file.fileName"
|
:key="fileKey(file)"
|
||||||
class="file-item"
|
class="file-item"
|
||||||
:class="[getFileTypeClass(file), { 'selected': batchMode && isFileSelected(file) }]"
|
:class="[getFileTypeClass(file), { 'selected': batchMode && isFileSelected(file) }]"
|
||||||
@click="batchMode ? onBatchClick(file) : handleFileClick(file)"
|
@click="batchMode ? onBatchClick(file) : handleFileClick(file)"
|
||||||
@@ -36,12 +50,18 @@
|
|||||||
{{ fileMetaText(file) }}
|
{{ fileMetaText(file) }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!loading && (!currentFileList || currentFileList.length === 0)" class="empty-state">
|
<div v-if="!loading && visibleFileList.length === 0" class="empty-state">
|
||||||
<i class="fas fa-folder-open"></i>
|
<i class="fas" :class="nameQuery && currentFileList.length ? 'fa-search' : 'fa-folder-open'"></i>
|
||||||
<h3>此文件夹为空</h3>
|
<h3>{{ nameQuery && currentFileList.length ? '没有匹配的文件' : '此文件夹为空' }}</h3>
|
||||||
<p>暂无文件或文件夹</p>
|
<p>{{ nameQuery && currentFileList.length ? '换个关键字,或加载更多后再筛' : '暂无文件或文件夹' }}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div v-if="paneMore" ref="loadMoreBar" class="load-more-bar">
|
||||||
|
<el-button size="small" :loading="paneMore.loading" @click="loadMorePane">
|
||||||
|
{{ paneMore.error ? '加载失败,点击重试' : '加载更多' }}
|
||||||
|
</el-button>
|
||||||
|
<span class="load-more-hint">已加载 {{ currentFileList.length }} 项{{ paneMore.error ? `:${paneMore.error}` : ',滚动到底部自动加载' }}</span>
|
||||||
|
</div>
|
||||||
<!-- 批量模式 action-bar -->
|
<!-- 批量模式 action-bar -->
|
||||||
<div v-if="batchMode" class="action-bar batch-action-bar">
|
<div v-if="batchMode" class="action-bar batch-action-bar">
|
||||||
<div class="batch-left">
|
<div class="batch-left">
|
||||||
@@ -120,6 +140,11 @@
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
||||||
|
<div v-if="treeFilterEmpty" class="empty-state tree-filter-empty">
|
||||||
|
<i class="fas fa-search"></i>
|
||||||
|
<h3>没有匹配的文件</h3>
|
||||||
|
<p>换个关键字,或加载更多后再筛</p>
|
||||||
|
</div>
|
||||||
<el-tree
|
<el-tree
|
||||||
ref="fileTree"
|
ref="fileTree"
|
||||||
:data="treeData"
|
:data="treeData"
|
||||||
@@ -130,16 +155,20 @@
|
|||||||
:highlight-current="!batchMode"
|
:highlight-current="!batchMode"
|
||||||
:show-checkbox="batchMode"
|
:show-checkbox="batchMode"
|
||||||
:check-strictly="false"
|
:check-strictly="false"
|
||||||
|
:filter-node-method="filterTreeNode"
|
||||||
@node-click="onNodeClick"
|
@node-click="onNodeClick"
|
||||||
@check="onTreeCheck"
|
@check="onTreeCheck"
|
||||||
@check-change="onTreeCheckChange"
|
@check-change="onTreeCheckChange"
|
||||||
:default-expand-all="false"
|
:default-expand-all="false"
|
||||||
:default-expanded-keys="['root']"
|
|
||||||
:render-content="renderContent"
|
:render-content="renderContent"
|
||||||
style="background:transparent;"
|
style="background:transparent;"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="batchMode" class="tree-sidebar-footer">
|
<div v-if="batchMode" class="tree-sidebar-footer">
|
||||||
|
<div class="tree-select-row">
|
||||||
|
<el-button size="small" @click="selectAll">全选</el-button>
|
||||||
|
<el-button size="small" @click="deselectAll">取消全选</el-button>
|
||||||
|
</div>
|
||||||
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
||||||
<div class="tree-sidebar-actions">
|
<div class="tree-sidebar-actions">
|
||||||
<el-button
|
<el-button
|
||||||
@@ -270,6 +299,11 @@
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
||||||
|
<div v-if="treeFilterEmpty" class="empty-state tree-filter-empty">
|
||||||
|
<i class="fas fa-search"></i>
|
||||||
|
<h3>没有匹配的文件</h3>
|
||||||
|
<p>换个关键字,或加载更多后再筛</p>
|
||||||
|
</div>
|
||||||
<el-tree
|
<el-tree
|
||||||
ref="fileTree"
|
ref="fileTree"
|
||||||
:data="treeData"
|
:data="treeData"
|
||||||
@@ -280,11 +314,11 @@
|
|||||||
:highlight-current="!batchMode"
|
:highlight-current="!batchMode"
|
||||||
:show-checkbox="batchMode"
|
:show-checkbox="batchMode"
|
||||||
:check-strictly="false"
|
:check-strictly="false"
|
||||||
|
:filter-node-method="filterTreeNode"
|
||||||
@node-click="onNodeClick"
|
@node-click="onNodeClick"
|
||||||
@check="onTreeCheck"
|
@check="onTreeCheck"
|
||||||
@check-change="onTreeCheckChange"
|
@check-change="onTreeCheckChange"
|
||||||
:default-expand-all="false"
|
:default-expand-all="false"
|
||||||
:default-expanded-keys="['root']"
|
|
||||||
:render-content="renderContent"
|
:render-content="renderContent"
|
||||||
style="background:transparent;"
|
style="background:transparent;"
|
||||||
/>
|
/>
|
||||||
@@ -360,6 +394,10 @@
|
|||||||
</el-button>
|
</el-button>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="batchMode" class="mobile-batch-footer">
|
<div v-if="batchMode" class="mobile-batch-footer">
|
||||||
|
<div class="tree-select-row">
|
||||||
|
<el-button size="small" @click="selectAll">全选</el-button>
|
||||||
|
<el-button size="small" @click="deselectAll">取消全选</el-button>
|
||||||
|
</div>
|
||||||
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
||||||
<div class="tree-sidebar-actions">
|
<div class="tree-sidebar-actions">
|
||||||
<el-button type="primary" size="small" :disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding || batchBrowserDownloadDisabled" :loading="batchDownloading" @click="batchBrowserDownload" :title="batchBrowserDownloadDisabled ? '所选文件需使用下载器下载' : ''">浏览器下载</el-button>
|
<el-button type="primary" size="small" :disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding || batchBrowserDownloadDisabled" :loading="batchDownloading" @click="batchBrowserDownload" :title="batchBrowserDownloadDisabled ? '所选文件需使用下载器下载' : ''">浏览器下载</el-button>
|
||||||
@@ -455,15 +493,27 @@ import fileTypeUtils from '@/utils/fileTypeUtils'
|
|||||||
import DownloadDialog from '@/components/DownloadDialog.vue'
|
import DownloadDialog from '@/components/DownloadDialog.vue'
|
||||||
import { testConnection, autoDetect, addDownload, batchAddDownload, getConfig, saveConfig } from '@/utils/downloaderService'
|
import { testConnection, autoDetect, addDownload, batchAddDownload, getConfig, saveConfig } from '@/utils/downloaderService'
|
||||||
import batchTreeCollect from '@/utils/batchTreeCollect'
|
import batchTreeCollect from '@/utils/batchTreeCollect'
|
||||||
|
import folderPaging from '@/utils/folderPaging'
|
||||||
|
import nameFilter from '@/utils/nameFilter'
|
||||||
import { openNoReferrer } from '@/utils/openNoReferrer'
|
import { openNoReferrer } from '@/utils/openNoReferrer'
|
||||||
|
|
||||||
const {
|
const {
|
||||||
DEFAULT_BATCH_MAX_DEPTH,
|
DEFAULT_BATCH_MAX_DEPTH,
|
||||||
getTreeNodeId,
|
getTreeNodeId,
|
||||||
normalizeTreeItem,
|
normalizeTreeItem,
|
||||||
|
fileIdentity,
|
||||||
uniqueFiles,
|
uniqueFiles,
|
||||||
collectFolderFiles
|
collectFolderFiles
|
||||||
} = batchTreeCollect
|
} = batchTreeCollect
|
||||||
|
const { toPageUrl, readPage, appendUnique, nextState, makeMoreNode, isMoreNode } = folderPaging
|
||||||
|
const {
|
||||||
|
matchesFileName,
|
||||||
|
filterByFileName,
|
||||||
|
filterSummary,
|
||||||
|
selectMatching,
|
||||||
|
deselectMatching,
|
||||||
|
collectLoadedNodes
|
||||||
|
} = nameFilter
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'DirectoryTree',
|
name: 'DirectoryTree',
|
||||||
@@ -473,6 +523,11 @@ export default {
|
|||||||
type: Array,
|
type: Array,
|
||||||
default: () => []
|
default: () => []
|
||||||
},
|
},
|
||||||
|
// 根目录分页信息(/v2/getFileListPage 的返回),null 表示不分页
|
||||||
|
rootPageInfo: {
|
||||||
|
type: Object,
|
||||||
|
default: null
|
||||||
|
},
|
||||||
shareUrl: {
|
shareUrl: {
|
||||||
type: String,
|
type: String,
|
||||||
required: true
|
required: true
|
||||||
@@ -501,6 +556,13 @@ export default {
|
|||||||
loading: false,
|
loading: false,
|
||||||
pathStack: [{ name: '全部文件', url: '' }],
|
pathStack: [{ name: '全部文件', url: '' }],
|
||||||
currentFileList: [],
|
currentFileList: [],
|
||||||
|
nameFilter: '',
|
||||||
|
rootLoadedFiles: [],
|
||||||
|
treeLoadVersion: 0,
|
||||||
|
// 当前窗格目录的下一页状态;null 表示已全部加载
|
||||||
|
paneMore: null,
|
||||||
|
rootMore: null,
|
||||||
|
rootExtra: [],
|
||||||
fileDialogVisible: false,
|
fileDialogVisible: false,
|
||||||
selectedFile: null,
|
selectedFile: null,
|
||||||
isDarkTheme: false,
|
isDarkTheme: false,
|
||||||
@@ -519,7 +581,8 @@ export default {
|
|||||||
treeProps: {
|
treeProps: {
|
||||||
label: 'fileName',
|
label: 'fileName',
|
||||||
children: 'children',
|
children: 'children',
|
||||||
isLeaf: 'isLeaf'
|
isLeaf: 'isLeaf',
|
||||||
|
disabled: 'disabled'
|
||||||
},
|
},
|
||||||
isMobile: false,
|
isMobile: false,
|
||||||
// 批量下载相关
|
// 批量下载相关
|
||||||
@@ -531,11 +594,26 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
|
nameQuery() {
|
||||||
|
return String(this.nameFilter || '').trim()
|
||||||
|
},
|
||||||
|
visibleFileList() {
|
||||||
|
return filterByFileName(this.currentFileList, this.nameFilter)
|
||||||
|
},
|
||||||
|
loadedCount() {
|
||||||
|
return filterSummary(this.entriesForCount(), this.nameFilter).loaded
|
||||||
|
},
|
||||||
|
matchedCount() {
|
||||||
|
return filterSummary(this.entriesForCount(), this.nameFilter).matched
|
||||||
|
},
|
||||||
|
treeFilterEmpty() {
|
||||||
|
return this.viewMode === 'tree' && !!this.nameQuery && this.matchedCount === 0 && this.loadedCount > 0
|
||||||
|
},
|
||||||
folderCount() {
|
folderCount() {
|
||||||
return this.currentFileList.filter(file => file.fileType === 'folder').length
|
return this.visibleFileList.filter(file => file.fileType === 'folder').length
|
||||||
},
|
},
|
||||||
fileCount() {
|
fileCount() {
|
||||||
return this.currentFileList.filter(file => file.fileType !== 'folder').length
|
return this.visibleFileList.filter(file => file.fileType !== 'folder').length
|
||||||
},
|
},
|
||||||
batchProgressPercent() {
|
batchProgressPercent() {
|
||||||
if (this.batchProgress.total === 0) return 0
|
if (this.batchProgress.total === 0) return 0
|
||||||
@@ -570,24 +648,39 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
|
paneMore() {
|
||||||
|
this.$nextTick(() => this.observeLoadMore())
|
||||||
|
},
|
||||||
|
viewMode(next, prev) {
|
||||||
|
if (prev === 'tree' && next !== 'tree') this.snapshotTreeRoot()
|
||||||
|
this.$nextTick(() => {
|
||||||
|
this.observeLoadMore()
|
||||||
|
if (next === 'tree') this.applyTreeFilter()
|
||||||
|
})
|
||||||
|
},
|
||||||
|
nameFilter() {
|
||||||
|
this.$nextTick(() => this.applyTreeFilter())
|
||||||
|
},
|
||||||
fileList: {
|
fileList: {
|
||||||
immediate: true,
|
immediate: true,
|
||||||
handler(newList) {
|
handler(newList) {
|
||||||
// 根节点children为当前目录下所有文件/文件夹
|
this.rootExtra = []
|
||||||
this.treeData = [
|
this.rootMore = nextState(this.buildApiUrl(), readPage(this.rootPageInfo || []))
|
||||||
{
|
this.treeMoreFolders = new Set()
|
||||||
id: 'root',
|
this.rootLoadedFiles = (newList || []).slice()
|
||||||
fileName: '全部文件',
|
this.nameFilter = ''
|
||||||
fileType: 'folder',
|
this.treeLoadVersion += 1
|
||||||
children: (newList || []).map(item => normalizeTreeItem(item)),
|
this.syncTreeDataChildren()
|
||||||
isLeaf: false
|
this.pathStack = [{ name: '全部文件', url: '' }]
|
||||||
}
|
this.currentFileList = newList || []
|
||||||
]
|
this.paneMore = this.rootMore
|
||||||
this.currentFileList = newList
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
|
this.treeMoreFolders = this.treeMoreFolders || new Set()
|
||||||
|
this._paneLoadSeq = 0
|
||||||
|
this._syncingChecks = false
|
||||||
this.resetTreeCollectState()
|
this.resetTreeCollectState()
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
@@ -617,15 +710,124 @@ export default {
|
|||||||
}
|
}
|
||||||
return this.withAuth(`${baseUrl}?${params.toString()}`)
|
return this.withAuth(`${baseUrl}?${params.toString()}`)
|
||||||
},
|
},
|
||||||
|
entriesForCount() {
|
||||||
|
// 树节点不是响应式数据,翻页后靠 treeLoadVersion 让「已加载 / 匹配」重新计算
|
||||||
|
void this.treeLoadVersion
|
||||||
|
return this.activeLoadedEntries()
|
||||||
|
},
|
||||||
|
activeLoadedEntries() {
|
||||||
|
if (this.viewMode !== 'tree') return this.currentFileList || []
|
||||||
|
const tree = this.getFileTree()
|
||||||
|
const storeRoot = tree && tree.store ? tree.store.root : null
|
||||||
|
if (storeRoot) return collectLoadedNodes(storeRoot)
|
||||||
|
return this.rootLoadedFiles || []
|
||||||
|
},
|
||||||
|
// 加载更多占位和虚拟根始终留下,否则无匹配时无法继续翻页
|
||||||
|
filterTreeNode(value, data) {
|
||||||
|
if (!data || data.id === 'root') return false
|
||||||
|
if (isMoreNode(data) || !value) return true
|
||||||
|
return matchesFileName(data, value)
|
||||||
|
},
|
||||||
|
displayRootNodes() {
|
||||||
|
const nodes = (this.rootLoadedFiles || []).map(item => normalizeTreeItem(item))
|
||||||
|
if (this.rootMore) nodes.push(makeMoreNode('root', { ...this.rootMore }))
|
||||||
|
return nodes
|
||||||
|
},
|
||||||
|
revealFilter() {
|
||||||
|
const tree = this.getFileTree()
|
||||||
|
if (tree && typeof tree.filter === 'function') tree.filter(this.nameQuery || '')
|
||||||
|
},
|
||||||
|
applyTreeFilter() {
|
||||||
|
this.revealFilter()
|
||||||
|
this.syncChecksFromSelection()
|
||||||
|
},
|
||||||
|
syncTreeDataChildren() {
|
||||||
|
const children = this.displayRootNodes()
|
||||||
|
if (this.rootMore) {
|
||||||
|
if (this.treeMoreFolders) this.treeMoreFolders.add('root')
|
||||||
|
} else if (this.treeMoreFolders) {
|
||||||
|
this.treeMoreFolders.delete('root')
|
||||||
|
}
|
||||||
|
// 树的数据就是当前已加载列表,不包一层「全部文件」,避免懒加载把根节点再插进列表
|
||||||
|
this.treeData = children
|
||||||
|
},
|
||||||
|
snapshotTreeRoot() {
|
||||||
|
const tree = this.getFileTree()
|
||||||
|
const root = tree && tree.store ? tree.store.root : null
|
||||||
|
if (!root) return
|
||||||
|
const files = []
|
||||||
|
let more = null
|
||||||
|
let sawMore = false
|
||||||
|
const pushNode = (child) => {
|
||||||
|
if (!child || !child.data || isMoreNode(child.data)) {
|
||||||
|
if (child && child.data && isMoreNode(child.data)) {
|
||||||
|
sawMore = true
|
||||||
|
more = child.data.paging || null
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (child.data.id === 'root') {
|
||||||
|
for (const grand of child.childNodes || []) pushNode(grand)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
files.push(child.data)
|
||||||
|
}
|
||||||
|
for (const child of root.childNodes || []) pushNode(child)
|
||||||
|
if (files.length || sawMore) {
|
||||||
|
this.rootLoadedFiles = appendUnique([], files)
|
||||||
|
this.rootMore = more
|
||||||
|
}
|
||||||
|
if (this.pathStack.length <= 1) {
|
||||||
|
this.currentFileList = (this.rootLoadedFiles || []).slice()
|
||||||
|
this.paneMore = this.rootMore
|
||||||
|
? { ...this.rootMore, loading: false, error: this.rootMore.error || '' }
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
this.$nextTick(() => {
|
||||||
|
if (this.viewMode !== 'tree') this.syncTreeDataChildren()
|
||||||
|
})
|
||||||
|
},
|
||||||
|
syncChecksFromSelection() {
|
||||||
|
const tree = this.getFileTree()
|
||||||
|
if (!tree || !this.batchMode || typeof tree.setChecked !== 'function') return
|
||||||
|
const root = tree.store ? tree.store.root : null
|
||||||
|
if (!root) return
|
||||||
|
this._syncingChecks = true
|
||||||
|
try {
|
||||||
|
const selectedKeys = new Set(this.selectedFiles.map(fileIdentity))
|
||||||
|
for (const file of collectLoadedNodes(root)) {
|
||||||
|
if (!this.isDownloadableFile(file)) continue
|
||||||
|
if (this.nameQuery && !matchesFileName(file, this.nameQuery)) continue
|
||||||
|
tree.setChecked(getTreeNodeId(file), selectedKeys.has(fileIdentity(file)), false)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this._syncingChecks = false
|
||||||
|
}
|
||||||
|
},
|
||||||
// 懒加载子节点(批量勾选文件夹时会通过 node.expand → store.load 复用此方法)
|
// 懒加载子节点(批量勾选文件夹时会通过 node.expand → store.load 复用此方法)
|
||||||
loadNode(node, resolve) {
|
loadNode(node, resolve) {
|
||||||
if (node.level === 0) {
|
if (node.level === 0) {
|
||||||
resolve((this.treeData[0]?.children || []).map(item => normalizeTreeItem(item)))
|
resolve(this.displayRootNodes())
|
||||||
|
this.treeLoadVersion += 1
|
||||||
|
this.$nextTick(() => this.revealFilter())
|
||||||
} else if (node.data.fileType === 'folder' && node.data.parserUrl) {
|
} else if (node.data.fileType === 'folder' && node.data.parserUrl) {
|
||||||
axios.get(this.withAuth(node.data.parserUrl), { headers: this.apiKeyHeaders() }).then(res => {
|
const listUrl = this.withAuth(node.data.parserUrl)
|
||||||
|
const pageUrl = toPageUrl(listUrl, 1)
|
||||||
|
axios.get(pageUrl || listUrl, { headers: this.apiKeyHeaders() }).then(res => {
|
||||||
if (res.data.code === 200) {
|
if (res.data.code === 200) {
|
||||||
const children = (res.data.data || []).map(item => normalizeTreeItem(item))
|
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)
|
||||||
|
}
|
||||||
resolve(children)
|
resolve(children)
|
||||||
|
this.treeLoadVersion += 1
|
||||||
|
this.$nextTick(() => this.revealFilter())
|
||||||
} else {
|
} else {
|
||||||
this.$message.error(res.data.msg || '获取子节点失败')
|
this.$message.error(res.data.msg || '获取子节点失败')
|
||||||
resolve([])
|
resolve([])
|
||||||
@@ -640,8 +842,125 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
onNodeClick(data) {
|
onNodeClick(data) {
|
||||||
|
if (isMoreNode(data)) {
|
||||||
|
this.loadMoreTreeNode(data)
|
||||||
|
return
|
||||||
|
}
|
||||||
this.selectedNode = data
|
this.selectedNode = data
|
||||||
},
|
},
|
||||||
|
fileKey(file) {
|
||||||
|
return getTreeNodeId(file)
|
||||||
|
},
|
||||||
|
// 滚动到底部自动加载;失败后暂停,等用户点击重试
|
||||||
|
observeLoadMore() {
|
||||||
|
if (typeof IntersectionObserver === 'undefined') return
|
||||||
|
if (!this._moreObserver) {
|
||||||
|
this._moreObserver = new IntersectionObserver((entries) => {
|
||||||
|
const state = this.paneMore
|
||||||
|
// 有关键字时列表变短,哨兵会露出来;这时不自动翻页,避免把未加载页一次拉完
|
||||||
|
if (!state || state.loading || state.error || this.viewMode !== 'pane' || this.nameQuery) return
|
||||||
|
if (entries.some(e => e.isIntersecting)) this.loadMorePane()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
this._moreObserver.disconnect()
|
||||||
|
if (this.$refs.loadMoreBar) this._moreObserver.observe(this.$refs.loadMoreBar)
|
||||||
|
},
|
||||||
|
async fetchPage(state) {
|
||||||
|
const res = await axios.get(toPageUrl(state.listUrl, state.nextPage, state.nextCursor), {
|
||||||
|
headers: this.apiKeyHeaders()
|
||||||
|
})
|
||||||
|
if (res.data.code !== 200) {
|
||||||
|
throw new Error(res.data.msg || '加载下一页失败')
|
||||||
|
}
|
||||||
|
return readPage(res.data.data)
|
||||||
|
},
|
||||||
|
// 加载失败(如上游限流)只保留重试入口,已加载的条目不清除
|
||||||
|
async loadMorePane() {
|
||||||
|
const state = this.paneMore
|
||||||
|
if (!state || state.loading) return
|
||||||
|
const seq = this._paneLoadSeq
|
||||||
|
state.loading = true
|
||||||
|
state.error = ''
|
||||||
|
try {
|
||||||
|
const page = await this.fetchPage(state)
|
||||||
|
if (seq !== this._paneLoadSeq || this.paneMore !== state) return
|
||||||
|
const before = this.currentFileList.length
|
||||||
|
this.currentFileList = appendUnique(this.currentFileList, page.list)
|
||||||
|
const added = this.currentFileList.slice(before)
|
||||||
|
const next = nextState(state.listUrl, page)
|
||||||
|
if (this.pathStack.length === 1) {
|
||||||
|
this.rootExtra = appendUnique(this.rootExtra, added)
|
||||||
|
this.rootMore = next
|
||||||
|
this.rootLoadedFiles = appendUnique(this.rootLoadedFiles, added)
|
||||||
|
if (this.viewMode !== 'tree') this.syncTreeDataChildren()
|
||||||
|
}
|
||||||
|
this.paneMore = next
|
||||||
|
this.treeLoadVersion += 1
|
||||||
|
} catch (error) {
|
||||||
|
if (seq !== this._paneLoadSeq || this.paneMore !== state) return
|
||||||
|
state.error = error.response?.data?.msg || error.message || '加载下一页失败'
|
||||||
|
this.$message.error(state.error)
|
||||||
|
} finally {
|
||||||
|
state.loading = false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async loadMoreTreeNode(moreData) {
|
||||||
|
const state = moreData.paging
|
||||||
|
const tree = this.getFileTree()
|
||||||
|
if (!state || state.loading || !tree) return
|
||||||
|
const moreNode = tree.getNode(moreData.id)
|
||||||
|
const parent = moreNode?.parent
|
||||||
|
if (!parent) return
|
||||||
|
state.loading = true
|
||||||
|
state.error = ''
|
||||||
|
try {
|
||||||
|
const page = await this.fetchPage(state)
|
||||||
|
const parentKey = getTreeNodeId(parent.data) || 'root'
|
||||||
|
const parentIsRoot = parent.level === 0
|
||||||
|
const next = nextState(state.listUrl, page)
|
||||||
|
if (parentIsRoot) {
|
||||||
|
// 换一份根数据,而不是 append 到 el-tree 正在监听的数组上,避免根节点被插进两遍
|
||||||
|
this.rootLoadedFiles = appendUnique(this.rootLoadedFiles, page.list)
|
||||||
|
this.rootMore = next
|
||||||
|
if (next) this.treeMoreFolders.add('root')
|
||||||
|
else this.treeMoreFolders.delete('root')
|
||||||
|
this.treeData = this.displayRootNodes()
|
||||||
|
} else {
|
||||||
|
const existing = new Set((parent.childNodes || []).map(n => getTreeNodeId(n.data)))
|
||||||
|
const selectedKeys = new Set(this.selectedFiles.map(fileIdentity))
|
||||||
|
this._syncingChecks = true
|
||||||
|
try {
|
||||||
|
tree.remove(moreNode)
|
||||||
|
for (const item of page.list.map(normalizeTreeItem)) {
|
||||||
|
if (existing.has(item.id)) continue
|
||||||
|
existing.add(item.id)
|
||||||
|
tree.append(item, parent)
|
||||||
|
if (this.isDownloadableFile(item) && typeof tree.setChecked === 'function') {
|
||||||
|
tree.setChecked(item.id, selectedKeys.has(fileIdentity(item)), false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (next) {
|
||||||
|
tree.append(makeMoreNode(parentKey, next), parent)
|
||||||
|
this.treeMoreFolders.add(parentKey)
|
||||||
|
} else {
|
||||||
|
this.treeMoreFolders.delete(parentKey)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this._syncingChecks = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state.loading = false
|
||||||
|
this.treeLoadVersion += 1
|
||||||
|
this.$nextTick(() => {
|
||||||
|
this.revealFilter()
|
||||||
|
this.syncChecksFromSelection()
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
state.loading = false
|
||||||
|
state.error = error.response?.data?.msg || error.message || '加载下一页失败'
|
||||||
|
this.$message.error(`${state.error},可再次点击「加载更多」重试`)
|
||||||
|
}
|
||||||
|
},
|
||||||
// 处理文件点击
|
// 处理文件点击
|
||||||
handleFileClick(file) {
|
handleFileClick(file) {
|
||||||
if (file.fileType === 'folder') {
|
if (file.fileType === 'folder') {
|
||||||
@@ -662,14 +981,19 @@ export default {
|
|||||||
try {
|
try {
|
||||||
this.loading = true
|
this.loading = true
|
||||||
const folderUrl = this.withAuth(folder.parserUrl)
|
const folderUrl = this.withAuth(folder.parserUrl)
|
||||||
const response = await axios.get(folderUrl, { headers: this.apiKeyHeaders() })
|
const seq = ++this._paneLoadSeq
|
||||||
|
const pageUrl = toPageUrl(folderUrl, 1)
|
||||||
|
const response = await axios.get(pageUrl || folderUrl, { headers: this.apiKeyHeaders() })
|
||||||
|
if (seq !== this._paneLoadSeq) return
|
||||||
if (response.data.code === 200) {
|
if (response.data.code === 200) {
|
||||||
const newDir = {
|
const newDir = {
|
||||||
url: folderUrl,
|
url: folderUrl,
|
||||||
name: folder.fileName || '未命名文件夹'
|
name: folder.fileName || '未命名文件夹'
|
||||||
}
|
}
|
||||||
|
const page = readPage(response.data.data)
|
||||||
this.pathStack.push(newDir)
|
this.pathStack.push(newDir)
|
||||||
this.currentFileList = response.data.data || []
|
this.currentFileList = page.list
|
||||||
|
this.paneMore = pageUrl ? nextState(folderUrl, page) : null
|
||||||
} else {
|
} else {
|
||||||
this.$message.error(response.data.msg || '获取文件夹内容失败')
|
this.$message.error(response.data.msg || '获取文件夹内容失败')
|
||||||
}
|
}
|
||||||
@@ -693,15 +1017,23 @@ export default {
|
|||||||
},
|
},
|
||||||
async loadCurrentDirectory() {
|
async loadCurrentDirectory() {
|
||||||
const currentDir = this.pathStack[this.pathStack.length - 1]
|
const currentDir = this.pathStack[this.pathStack.length - 1]
|
||||||
|
const seq = ++this._paneLoadSeq
|
||||||
if (!currentDir.url) {
|
if (!currentDir.url) {
|
||||||
this.currentFileList = this.fileList
|
this.currentFileList = appendUnique(this.fileList, this.rootExtra)
|
||||||
|
this.paneMore = this.rootMore
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
this.paneMore = null
|
||||||
try {
|
try {
|
||||||
this.loading = true
|
this.loading = true
|
||||||
const response = await axios.get(this.withAuth(currentDir.url), { headers: this.apiKeyHeaders() })
|
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
|
||||||
if (response.data.code === 200) {
|
if (response.data.code === 200) {
|
||||||
this.currentFileList = response.data.data || []
|
const page = readPage(response.data.data)
|
||||||
|
this.currentFileList = page.list
|
||||||
|
this.paneMore = pageUrl ? nextState(listUrl, page) : null
|
||||||
} else {
|
} else {
|
||||||
this.$message.error(response.data.msg || '加载目录失败')
|
this.$message.error(response.data.msg || '加载目录失败')
|
||||||
}
|
}
|
||||||
@@ -1098,7 +1430,21 @@ export default {
|
|||||||
const fromTree = tree
|
const fromTree = tree
|
||||||
? tree.getCheckedNodes().filter(n => this.isDownloadableFile(n))
|
? tree.getCheckedNodes().filter(n => this.isDownloadableFile(n))
|
||||||
: []
|
: []
|
||||||
this.selectedFiles = uniqueFiles([...fromTree, ...extraFiles])
|
const visibleKeys = new Set(
|
||||||
|
filterByFileName(this.activeLoadedEntries(), this.nameFilter)
|
||||||
|
.filter(file => this.isDownloadableFile(file))
|
||||||
|
.map(fileIdentity)
|
||||||
|
)
|
||||||
|
const extraKeys = new Set((extraFiles || []).map(fileIdentity))
|
||||||
|
const kept = this.selectedFiles.filter(file => {
|
||||||
|
const key = fileIdentity(file)
|
||||||
|
return !visibleKeys.has(key) && !extraKeys.has(key)
|
||||||
|
})
|
||||||
|
const checkedVisible = fromTree.filter(file => {
|
||||||
|
const key = fileIdentity(file)
|
||||||
|
return visibleKeys.has(key) || extraKeys.has(key)
|
||||||
|
})
|
||||||
|
this.selectedFiles = uniqueFiles([...kept, ...checkedVisible, ...(extraFiles || [])])
|
||||||
},
|
},
|
||||||
enqueueFolderCollect(folderData) {
|
enqueueFolderCollect(folderData) {
|
||||||
const key = getTreeNodeId(folderData)
|
const key = getTreeNodeId(folderData)
|
||||||
@@ -1135,6 +1481,9 @@ export default {
|
|||||||
visitedKeys: this._visitedInCollect
|
visitedKeys: this._visitedInCollect
|
||||||
})
|
})
|
||||||
this.syncSelectedFilesFromTree(ctx.files)
|
this.syncSelectedFilesFromTree(ctx.files)
|
||||||
|
if ([...this._visitedInCollect].some(key => this.treeMoreFolders.has(key))) {
|
||||||
|
this.$message.warning('部分文件夹还有未加载的分页,只勾选了已加载的文件;请先点击「加载更多」后再勾选')
|
||||||
|
}
|
||||||
if (ctx.depthExceeded) {
|
if (ctx.depthExceeded) {
|
||||||
this.$message.warning(
|
this.$message.warning(
|
||||||
`已达到最大展开深度(${this.effectiveBatchMaxDepth} 层),部分深层文件未勾选`
|
`已达到最大展开深度(${this.effectiveBatchMaxDepth} 层),部分深层文件未勾选`
|
||||||
@@ -1154,11 +1503,13 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
isFileSelected(file) {
|
isFileSelected(file) {
|
||||||
return this.selectedFiles.some(f => f.fileName === file.fileName && f.parserUrl === file.parserUrl)
|
const key = fileIdentity(file)
|
||||||
|
return this.selectedFiles.some(item => fileIdentity(item) === key)
|
||||||
},
|
},
|
||||||
toggleFileSelect(file) {
|
toggleFileSelect(file) {
|
||||||
if (file.fileType === 'folder') return
|
if (!file || file.fileType === 'folder' || isMoreNode(file)) return
|
||||||
const idx = this.selectedFiles.findIndex(f => f.fileName === file.fileName && f.parserUrl === file.parserUrl)
|
const key = fileIdentity(file)
|
||||||
|
const idx = this.selectedFiles.findIndex(item => fileIdentity(item) === key)
|
||||||
if (idx >= 0) {
|
if (idx >= 0) {
|
||||||
this.selectedFiles.splice(idx, 1)
|
this.selectedFiles.splice(idx, 1)
|
||||||
} else {
|
} else {
|
||||||
@@ -1175,13 +1526,32 @@ export default {
|
|||||||
this.toggleFileSelect(file)
|
this.toggleFileSelect(file)
|
||||||
},
|
},
|
||||||
selectAll() {
|
selectAll() {
|
||||||
this.selectedFiles = this.currentFileList.filter(f => this.isDownloadableFile(f))
|
const loaded = this.activeLoadedEntries()
|
||||||
|
this.selectedFiles = selectMatching(
|
||||||
|
this.selectedFiles,
|
||||||
|
loaded,
|
||||||
|
this.nameFilter,
|
||||||
|
file => this.isDownloadableFile(file)
|
||||||
|
)
|
||||||
|
const hasMore = this.viewMode === 'tree'
|
||||||
|
? !!(this.rootMore || (this.treeMoreFolders && this.treeMoreFolders.size))
|
||||||
|
: !!this.paneMore
|
||||||
|
if (hasMore) {
|
||||||
|
this.$message.warning('仅选中已加载且匹配筛选的文件,未继续拉取后续分页')
|
||||||
|
}
|
||||||
|
this.$nextTick(() => this.syncChecksFromSelection())
|
||||||
},
|
},
|
||||||
deselectAll() {
|
deselectAll() {
|
||||||
this.selectedFiles = []
|
this.selectedFiles = deselectMatching(
|
||||||
|
this.selectedFiles,
|
||||||
|
this.activeLoadedEntries(),
|
||||||
|
this.nameFilter,
|
||||||
|
file => this.isDownloadableFile(file)
|
||||||
|
)
|
||||||
|
this.$nextTick(() => this.syncChecksFromSelection())
|
||||||
},
|
},
|
||||||
onTreeCheckChange() {
|
onTreeCheckChange() {
|
||||||
if (!this.batchMode || this._treeCollecting) return
|
if (!this.batchMode || this._treeCollecting || this._syncingChecks) return
|
||||||
this.syncSelectedFilesFromTree()
|
this.syncSelectedFilesFromTree()
|
||||||
},
|
},
|
||||||
extractTypeParam(file) {
|
extractTypeParam(file) {
|
||||||
@@ -1291,6 +1661,12 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
renderContent(h, { node, data, store }) {
|
renderContent(h, { node, data, store }) {
|
||||||
|
if (isMoreNode(data)) {
|
||||||
|
return h('div', { class: 'custom-tree-node tree-load-more' }, [
|
||||||
|
h('i', { class: 'fas fa-angle-double-down' }),
|
||||||
|
h('span', { class: 'node-label' }, node.label)
|
||||||
|
])
|
||||||
|
}
|
||||||
const isFolder = data.fileType === 'folder'
|
const isFolder = data.fileType === 'folder'
|
||||||
const isUrl = data.fileType === 'url'
|
const isUrl = data.fileType === 'url'
|
||||||
return h('div', {
|
return h('div', {
|
||||||
@@ -1328,6 +1704,9 @@ export default {
|
|||||||
if (this._observer) {
|
if (this._observer) {
|
||||||
this._observer.disconnect()
|
this._observer.disconnect()
|
||||||
}
|
}
|
||||||
|
if (this._moreObserver) {
|
||||||
|
this._moreObserver.disconnect()
|
||||||
|
}
|
||||||
if (this._onResize) {
|
if (this._onResize) {
|
||||||
window.removeEventListener('resize', this._onResize)
|
window.removeEventListener('resize', this._onResize)
|
||||||
}
|
}
|
||||||
@@ -1362,6 +1741,56 @@ html, body, #app, .main-container, .directory-tree, .content-card {
|
|||||||
border: 1px solid #404040;
|
border: 1px solid #404040;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.dir-filter-bar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px 14px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
padding: 10px 12px;
|
||||||
|
background: #fff;
|
||||||
|
border-bottom: 1px solid #eaeaea;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark-theme .dir-filter-bar {
|
||||||
|
background: #2d2d2d;
|
||||||
|
border-bottom-color: #404040;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dir-name-filter {
|
||||||
|
flex: 1 1 220px;
|
||||||
|
max-width: 420px;
|
||||||
|
min-width: 0;
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dir-name-filter .el-input__wrapper {
|
||||||
|
min-height: 36px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dir-filter-hint {
|
||||||
|
margin: 0;
|
||||||
|
flex: 1 1 200px;
|
||||||
|
min-width: 0;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.45;
|
||||||
|
color: #909399;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark-theme .dir-filter-hint {
|
||||||
|
color: #bdc3c7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tree-filter-empty {
|
||||||
|
padding: 16px 8px 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tree-select-row {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
.breadcrumb {
|
.breadcrumb {
|
||||||
background: #f8f9fa;
|
background: #f8f9fa;
|
||||||
padding: 16px 24px;
|
padding: 16px 24px;
|
||||||
@@ -1509,6 +1938,24 @@ html, body, #app, .main-container, .directory-tree, .content-card {
|
|||||||
color: #bdc3c7;
|
color: #bdc3c7;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.load-more-bar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 0 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.load-more-hint {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #909399;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tree-load-more {
|
||||||
|
color: #409eff;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
.empty-state {
|
.empty-state {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
padding: 30px 10px;
|
padding: 30px 10px;
|
||||||
@@ -2176,6 +2623,27 @@ html, body, #app, .main-container, .directory-tree, .content-card {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
|
.dir-filter-bar {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
}
|
||||||
|
.dir-name-filter {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
max-width: none;
|
||||||
|
width: 100%;
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
.dir-name-filter .el-input__wrapper {
|
||||||
|
min-height: 40px;
|
||||||
|
}
|
||||||
|
.dir-filter-hint {
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
.tree-select-row .el-button {
|
||||||
|
flex: 1 1 0;
|
||||||
|
}
|
||||||
.file-grid {
|
.file-grid {
|
||||||
grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
|
grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
/**
|
||||||
|
* 目录分页(/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
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
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)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
/**
|
||||||
|
* 目录文件名筛选与批量勾选范围。
|
||||||
|
*
|
||||||
|
* 只处理已经加载的行,不发起下一页请求。分页仍由 folderPaging 的
|
||||||
|
* nextCursor / pageCursor 推进;这里只决定新页里哪些行可见、哪些会被全选。
|
||||||
|
*/
|
||||||
|
const { fileIdentity, uniqueFiles } = require('./batchTreeCollect')
|
||||||
|
const { appendUnique, nextState } = require('./folderPaging')
|
||||||
|
|
||||||
|
function normalizeQuery(keyword) {
|
||||||
|
return String(keyword == null ? '' : keyword).trim().toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
function matchesFileName(file, keyword) {
|
||||||
|
const query = normalizeQuery(keyword)
|
||||||
|
if (!query) return true
|
||||||
|
return String((file && file.fileName) || '').toLowerCase().includes(query)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 空关键字返回副本,不清空调用方持有的已加载数组。 */
|
||||||
|
function filterByFileName(list, keyword) {
|
||||||
|
const rows = list || []
|
||||||
|
const query = normalizeQuery(keyword)
|
||||||
|
if (!query) return rows.slice()
|
||||||
|
return rows.filter(file => matchesFileName(file, keyword))
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSelectableFile(file) {
|
||||||
|
return !!(
|
||||||
|
file
|
||||||
|
&& file.parserUrl
|
||||||
|
&& file.fileType !== 'folder'
|
||||||
|
&& file.fileType !== 'url'
|
||||||
|
&& file.fileType !== 'more'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function countableEntries(list) {
|
||||||
|
return (list || []).filter(file => file && file.fileType !== 'more' && file.id !== 'root')
|
||||||
|
}
|
||||||
|
|
||||||
|
function filterSummary(loaded, keyword) {
|
||||||
|
const rows = countableEntries(loaded)
|
||||||
|
const matched = filterByFileName(rows, keyword)
|
||||||
|
return {
|
||||||
|
loaded: rows.length,
|
||||||
|
matched: matched.length,
|
||||||
|
text: `仅筛选已加载的 ${rows.length} 项,匹配 ${matched.length} 项`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全选:只并入当前关键字命中的已加载可选文件。
|
||||||
|
* 不在这份可见集合里的原选择保留,隐藏项不会被加进来。
|
||||||
|
*/
|
||||||
|
function selectMatching(selected, loaded, keyword, isSelectable = isSelectableFile) {
|
||||||
|
const visible = filterByFileName(loaded, keyword).filter(file => isSelectable(file))
|
||||||
|
const visibleKeys = new Set(visible.map(fileIdentity))
|
||||||
|
const kept = (selected || []).filter(file => !visibleKeys.has(fileIdentity(file)))
|
||||||
|
return uniqueFiles(kept.concat(visible))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取消全选:只移出当前可见可选文件,范围外的选择不动。 */
|
||||||
|
function deselectMatching(selected, loaded, keyword, isSelectable = isSelectableFile) {
|
||||||
|
const visibleKeys = new Set(
|
||||||
|
filterByFileName(loaded, keyword)
|
||||||
|
.filter(file => isSelectable(file))
|
||||||
|
.map(fileIdentity)
|
||||||
|
)
|
||||||
|
return (selected || []).filter(file => !visibleKeys.has(fileIdentity(file)))
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleSelected(selected, file, isSelectable = isSelectableFile) {
|
||||||
|
const list = (selected || []).slice()
|
||||||
|
if (!isSelectable(file)) return list
|
||||||
|
const key = fileIdentity(file)
|
||||||
|
const index = list.findIndex(item => fileIdentity(item) === key)
|
||||||
|
if (index >= 0) {
|
||||||
|
list.splice(index, 1)
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
list.push(file)
|
||||||
|
return list
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSelected(selected, file) {
|
||||||
|
const key = fileIdentity(file)
|
||||||
|
return (selected || []).some(item => fileIdentity(item) === key)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 已加载树节点。未展开的文件夹不往下走,因此不会把未请求的子项算进全选范围。
|
||||||
|
* 「加载更多」占位节点跳过。
|
||||||
|
*/
|
||||||
|
function collectLoadedNodes(node) {
|
||||||
|
const out = []
|
||||||
|
for (const child of (node && node.childNodes) || []) {
|
||||||
|
const data = child && child.data
|
||||||
|
if (!data || data.fileType === 'more') continue
|
||||||
|
out.push(data)
|
||||||
|
if (child.loaded) {
|
||||||
|
out.push(...collectLoadedNodes(child))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用目录分页的 nextCursor 追加一页。
|
||||||
|
* 已有选择原样保留:新页即使命中关键字也不会被静默勾上。
|
||||||
|
*/
|
||||||
|
function applyCursorPage(state, page) {
|
||||||
|
const loaded = appendUnique(state.loaded, (page && page.list) || [])
|
||||||
|
const listUrl = (state.more && state.more.listUrl) || state.listUrl
|
||||||
|
return {
|
||||||
|
keyword: state.keyword,
|
||||||
|
view: state.view,
|
||||||
|
loaded,
|
||||||
|
selected: (state.selected || []).slice(),
|
||||||
|
listUrl,
|
||||||
|
more: nextState(listUrl, page)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function switchView(state, view) {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
view,
|
||||||
|
keyword: state.keyword,
|
||||||
|
selected: (state.selected || []).slice()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearKeyword(state) {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
keyword: ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
normalizeQuery,
|
||||||
|
matchesFileName,
|
||||||
|
filterByFileName,
|
||||||
|
isSelectableFile,
|
||||||
|
filterSummary,
|
||||||
|
selectMatching,
|
||||||
|
deselectMatching,
|
||||||
|
toggleSelected,
|
||||||
|
isSelected,
|
||||||
|
collectLoadedNodes,
|
||||||
|
applyCursorPage,
|
||||||
|
switchView,
|
||||||
|
clearKeyword
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
const { describe, it } = require('node:test')
|
||||||
|
const assert = require('node:assert/strict')
|
||||||
|
|
||||||
|
const { readPage } = require('./folderPaging')
|
||||||
|
const {
|
||||||
|
normalizeQuery,
|
||||||
|
filterByFileName,
|
||||||
|
filterSummary,
|
||||||
|
selectMatching,
|
||||||
|
deselectMatching,
|
||||||
|
toggleSelected,
|
||||||
|
isSelected,
|
||||||
|
collectLoadedNodes,
|
||||||
|
applyCursorPage,
|
||||||
|
switchView,
|
||||||
|
clearKeyword
|
||||||
|
} = require('./nameFilter')
|
||||||
|
|
||||||
|
function file(name, id, extra = {}) {
|
||||||
|
return {
|
||||||
|
fileName: name,
|
||||||
|
fileId: id,
|
||||||
|
fileType: 'file',
|
||||||
|
parserUrl: '/v2/redirectUrl/lz/same',
|
||||||
|
...extra
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function folder(name, id) {
|
||||||
|
return {
|
||||||
|
fileName: name,
|
||||||
|
fileId: id,
|
||||||
|
fileType: 'folder',
|
||||||
|
parserUrl: `/v2/getFileList?dir=${id}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function baseState(overrides = {}) {
|
||||||
|
return {
|
||||||
|
keyword: '',
|
||||||
|
view: 'pane',
|
||||||
|
loaded: [],
|
||||||
|
selected: [],
|
||||||
|
listUrl: '/v2/getFileList?url=share',
|
||||||
|
more: null,
|
||||||
|
...overrides
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('filename filter', () => {
|
||||||
|
const loaded = [
|
||||||
|
file('Alpha.TXT', '1'),
|
||||||
|
file('notes.md', '2'),
|
||||||
|
file(' photo.JPG', '3'),
|
||||||
|
folder('Albums', '4')
|
||||||
|
]
|
||||||
|
|
||||||
|
it('trims and matches a case-insensitive substring', () => {
|
||||||
|
assert.equal(normalizeQuery(' ApK '), 'apk')
|
||||||
|
const matched = filterByFileName(loaded, ' aL ')
|
||||||
|
assert.deepEqual(matched.map(item => item.fileId), ['1', '4'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('blank keyword restores the loaded list without dropping rows', () => {
|
||||||
|
const cleared = filterByFileName(loaded, ' ')
|
||||||
|
assert.deepEqual(cleared.map(item => item.fileId), ['1', '2', '3', '4'])
|
||||||
|
assert.notEqual(cleared, loaded)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('describes loaded N and matched M', () => {
|
||||||
|
const summary = filterSummary(loaded, 'photo')
|
||||||
|
assert.equal(summary.loaded, 4)
|
||||||
|
assert.equal(summary.matched, 1)
|
||||||
|
assert.equal(summary.text, '仅筛选已加载的 4 项,匹配 1 项')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('select and deselect scope', () => {
|
||||||
|
const outside = file('kept.zip', 'out', { parserUrl: '/v2/redirectUrl/lz/out' })
|
||||||
|
const match = file('Alpha.TXT', '1')
|
||||||
|
const other = file('Beta.bin', '2')
|
||||||
|
const hiddenFolder = folder('Alpha-dir', '3')
|
||||||
|
const link = file('Alpha-link.url', '4', { fileType: 'url', parserUrl: '' })
|
||||||
|
const loaded = [match, other, hiddenFolder, link]
|
||||||
|
|
||||||
|
it('selects only loaded selectable files matching the keyword', () => {
|
||||||
|
const selected = selectMatching([outside], loaded, 'alpha')
|
||||||
|
assert.deepEqual(selected.map(item => item.fileId), ['out', '1'])
|
||||||
|
assert.equal(isSelected(selected, other), false)
|
||||||
|
assert.equal(isSelected(selected, hiddenFolder), false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('deselect removes only the current match and keeps selections outside it', () => {
|
||||||
|
const selected = deselectMatching([outside, match, other], loaded, 'alpha')
|
||||||
|
assert.deepEqual(selected.map(item => item.fileId), ['out', '2'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not select a loaded file hidden by the keyword', () => {
|
||||||
|
const selected = selectMatching([other], loaded, 'alpha')
|
||||||
|
assert.equal(isSelected(selected, other), true)
|
||||||
|
assert.equal(isSelected(selected, match), true)
|
||||||
|
const narrowed = selectMatching(selected, loaded, 'beta')
|
||||||
|
assert.deepEqual(narrowed.map(item => item.fileId).sort(), ['1', '2'])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('same name, different id', () => {
|
||||||
|
const first = file('Report.TXT', 'a')
|
||||||
|
const second = file('Report.TXT', 'b')
|
||||||
|
|
||||||
|
it('keeps both files when selecting and can toggle one without the other', () => {
|
||||||
|
const selected = selectMatching([], [first, second], 'report')
|
||||||
|
assert.equal(selected.length, 2)
|
||||||
|
assert.notEqual(selected[0], selected[1])
|
||||||
|
const onlySecond = toggleSelected(selected, first)
|
||||||
|
assert.deepEqual(onlySecond.map(item => item.fileId), ['b'])
|
||||||
|
assert.equal(isSelected(onlySecond, first), false)
|
||||||
|
assert.equal(isSelected(onlySecond, second), true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('distinguishes files that only differ by id when fileId is absent', () => {
|
||||||
|
const left = { fileName: 'Report.TXT', id: 'x', fileType: 'file', parserUrl: '/v2/redirectUrl/lz/same' }
|
||||||
|
const right = { fileName: 'Report.TXT', id: 'y', fileType: 'file', parserUrl: '/v2/redirectUrl/lz/same' }
|
||||||
|
const selected = toggleSelected([], left)
|
||||||
|
assert.equal(isSelected(selected, right), false)
|
||||||
|
assert.equal(toggleSelected(selected, right).length, 2)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('cursor page', () => {
|
||||||
|
it('shows new matches from the next cursor without selecting them', () => {
|
||||||
|
let state = baseState({
|
||||||
|
keyword: 'alpha',
|
||||||
|
loaded: [file('Alpha.TXT', '1'), file('Beta.bin', '2')],
|
||||||
|
selected: [file('Beta.bin', '2')],
|
||||||
|
more: { listUrl: '/v2/getFileList?url=share', nextPage: 2, nextCursor: 'c1', loading: false, error: '' }
|
||||||
|
})
|
||||||
|
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1'])
|
||||||
|
|
||||||
|
state = applyCursorPage(state, readPage({
|
||||||
|
list: [file('ALPHA-extra.txt', '3'), file('Gamma.bin', '4')],
|
||||||
|
paged: true,
|
||||||
|
hasMore: true,
|
||||||
|
nextPage: 3,
|
||||||
|
nextCursor: 'c2'
|
||||||
|
}))
|
||||||
|
|
||||||
|
assert.deepEqual(state.loaded.map(item => item.fileId), ['1', '2', '3', '4'])
|
||||||
|
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1', '3'])
|
||||||
|
assert.deepEqual(state.selected.map(item => item.fileId), ['2'])
|
||||||
|
assert.equal(state.more.nextCursor, 'c2')
|
||||||
|
assert.equal(state.more.nextPage, 3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps load-more available when nothing matches yet', () => {
|
||||||
|
let state = baseState({
|
||||||
|
keyword: 'zzzz',
|
||||||
|
loaded: [file('Alpha.TXT', '1')],
|
||||||
|
more: { listUrl: '/v2/getFileList?url=share', nextPage: 2, nextCursor: 'c1', loading: false, error: '' }
|
||||||
|
})
|
||||||
|
assert.equal(filterByFileName(state.loaded, state.keyword).length, 0)
|
||||||
|
assert.equal(state.more.nextCursor, 'c1')
|
||||||
|
|
||||||
|
state = applyCursorPage(state, readPage({
|
||||||
|
list: [file('zzzz-found.txt', '9')],
|
||||||
|
hasMore: true,
|
||||||
|
nextPage: 3,
|
||||||
|
nextCursor: 'c2'
|
||||||
|
}))
|
||||||
|
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['9'])
|
||||||
|
assert.equal(state.selected.length, 0)
|
||||||
|
assert.ok(state.more)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('view switch and clear', () => {
|
||||||
|
it('keeps the keyword and selected identities when the view changes', () => {
|
||||||
|
const chosen = file('Alpha.TXT', '1')
|
||||||
|
const state = baseState({
|
||||||
|
keyword: ' Alpha ',
|
||||||
|
view: 'pane',
|
||||||
|
loaded: [chosen, file('Beta.bin', '2')],
|
||||||
|
selected: [chosen]
|
||||||
|
})
|
||||||
|
const tree = switchView(state, 'tree')
|
||||||
|
assert.equal(tree.view, 'tree')
|
||||||
|
assert.equal(tree.keyword, ' Alpha ')
|
||||||
|
assert.deepEqual(tree.selected.map(item => item.fileId), ['1'])
|
||||||
|
const back = switchView(tree, 'pane')
|
||||||
|
assert.equal(back.keyword, state.keyword)
|
||||||
|
assert.equal(isSelected(back.selected, chosen), true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('clearing the keyword shows every loaded row again', () => {
|
||||||
|
const state = baseState({
|
||||||
|
keyword: 'alpha',
|
||||||
|
loaded: [file('Alpha.TXT', '1'), file('Beta.bin', '2')]
|
||||||
|
})
|
||||||
|
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1'])
|
||||||
|
const cleared = clearKeyword(state)
|
||||||
|
assert.deepEqual(
|
||||||
|
filterByFileName(cleared.loaded, cleared.keyword).map(item => item.fileId),
|
||||||
|
['1', '2']
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('loaded tree nodes', () => {
|
||||||
|
it('skips unloaded folders, hidden placeholders, and does not invent a fetch', () => {
|
||||||
|
const secret = file('secret.txt', 'secret')
|
||||||
|
const more = { data: { fileType: 'more', fileName: '加载更多…' }, loaded: true, childNodes: [] }
|
||||||
|
const root = {
|
||||||
|
childNodes: [
|
||||||
|
{ data: file('root.txt', 'root'), loaded: true, childNodes: [] },
|
||||||
|
{
|
||||||
|
data: folder('closed', 'closed'),
|
||||||
|
loaded: false,
|
||||||
|
childNodes: [{ data: secret, loaded: true, childNodes: [] }]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: folder('open', 'open'),
|
||||||
|
loaded: true,
|
||||||
|
childNodes: [
|
||||||
|
{ data: file('open-a.txt', 'oa'), loaded: true, childNodes: [] },
|
||||||
|
more
|
||||||
|
]
|
||||||
|
},
|
||||||
|
more
|
||||||
|
]
|
||||||
|
}
|
||||||
|
const loaded = collectLoadedNodes(root)
|
||||||
|
assert.deepEqual(loaded.map(item => item.fileId), ['root', 'closed', 'open', 'oa'])
|
||||||
|
const selected = selectMatching([], loaded, '')
|
||||||
|
assert.deepEqual(selected.map(item => item.fileId), ['root', 'oa'])
|
||||||
|
assert.equal(isSelected(selected, secret), false)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -432,6 +432,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<DirectoryTree
|
<DirectoryTree
|
||||||
:file-list="directoryData"
|
:file-list="directoryData"
|
||||||
|
:root-page-info="directoryPageInfo"
|
||||||
:share-url="link"
|
:share-url="link"
|
||||||
:password="password"
|
:password="password"
|
||||||
:auth="directoryAuth"
|
:auth="directoryAuth"
|
||||||
@@ -670,6 +671,7 @@ export default {
|
|||||||
// 目录树
|
// 目录树
|
||||||
showDirectoryTree: false,
|
showDirectoryTree: false,
|
||||||
directoryData: [],
|
directoryData: [],
|
||||||
|
directoryPageInfo: null,
|
||||||
directoryAuth: '', // 目录解析时的加密 auth,透传给子目录/下载
|
directoryAuth: '', // 目录解析时的加密 auth,透传给子目录/下载
|
||||||
|
|
||||||
// 统计信息
|
// 统计信息
|
||||||
@@ -777,7 +779,7 @@ export default {
|
|||||||
},
|
},
|
||||||
folderParseMeta() {
|
folderParseMeta() {
|
||||||
if (!this.showDirectoryTree) return []
|
if (!this.showDirectoryTree) return []
|
||||||
const meta = [`${this.directoryData.length} 个文件/文件夹`]
|
const meta = [`${this.directoryData.length}${this.directoryPageInfo?.hasMore ? '+' : ''} 个文件/文件夹`]
|
||||||
const recognized = parserUrl.parseLink(this.link || '')
|
const recognized = parserUrl.parseLink(this.link || '')
|
||||||
const panType = this.getCurrentPanType()
|
const panType = this.getCurrentPanType()
|
||||||
const name = recognized?.name || (panType ? parseResultMeta.panDisplayName(panType.toLowerCase(), this.panList) : '')
|
const name = recognized?.name || (panType ? parseResultMeta.panDisplayName(panType.toLowerCase(), this.panList) : '')
|
||||||
@@ -1242,6 +1244,7 @@ export default {
|
|||||||
this.statisticsData = {}
|
this.statisticsData = {}
|
||||||
this.showDirectoryTree = false
|
this.showDirectoryTree = false
|
||||||
this.directoryData = []
|
this.directoryData = []
|
||||||
|
this.directoryPageInfo = null
|
||||||
this.directoryAuth = ''
|
this.directoryAuth = ''
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -1376,14 +1379,17 @@ export default {
|
|||||||
params.auth = this.directoryAuth
|
params.auth = this.directoryAuth
|
||||||
}
|
}
|
||||||
|
|
||||||
// 直接调用 getFileList,让后端返回错误(不做客户端类型检查)
|
// 直接调用 getFileListPage,让后端返回错误(不做客户端类型检查)
|
||||||
const directoryResult = await this.callAPI('/v2/getFileList', params)
|
const directoryResult = await this.callAPI('/v2/getFileListPage', params)
|
||||||
this.directoryData = directoryResult.data || []
|
const page = directoryResult.data || {}
|
||||||
|
this.directoryPageInfo = Array.isArray(page) ? null : page
|
||||||
|
this.directoryData = Array.isArray(page) ? page : (page.list || [])
|
||||||
this.showDirectoryTree = true
|
this.showDirectoryTree = true
|
||||||
// 自动赋值分享链接
|
// 自动赋值分享链接
|
||||||
this.showListLink = `${this.baseUrl}/showList?url=${encodeURIComponent(this.link)}`
|
this.showListLink = `${this.baseUrl}/showList?url=${encodeURIComponent(this.link)}`
|
||||||
|
|
||||||
this.$message.success(`目录解析成功!共找到 ${this.directoryData.length} 个文件/文件夹`)
|
const more = this.directoryPageInfo?.hasMore ? '(当前为第 1 页,可在列表底部加载更多)' : ''
|
||||||
|
this.$message.success(`目录解析成功!共找到 ${this.directoryData.length} 个文件/文件夹${more}`)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('目录解析失败:', error)
|
console.error('目录解析失败:', error)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
<div v-else>
|
<div v-else>
|
||||||
<DirectoryTree
|
<DirectoryTree
|
||||||
:file-list="directoryData"
|
:file-list="directoryData"
|
||||||
|
:root-page-info="pageInfo"
|
||||||
:share-url="url"
|
:share-url="url"
|
||||||
:password="''"
|
:password="''"
|
||||||
:view-mode="viewMode"
|
:view-mode="viewMode"
|
||||||
@@ -42,6 +43,7 @@ export default {
|
|||||||
loading: true,
|
loading: true,
|
||||||
error: '',
|
error: '',
|
||||||
directoryData: [],
|
directoryData: [],
|
||||||
|
pageInfo: null,
|
||||||
url: '',
|
url: '',
|
||||||
viewMode: 'pane'
|
viewMode: 'pane'
|
||||||
}
|
}
|
||||||
@@ -55,8 +57,10 @@ export default {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const res = await axios.get('/v2/getFileList', { params: { url: this.url } })
|
const res = await axios.get('/v2/getFileListPage', { params: { url: this.url } })
|
||||||
this.directoryData = res.data.data || []
|
const page = res.data.data || {}
|
||||||
|
this.pageInfo = Array.isArray(page) ? null : page
|
||||||
|
this.directoryData = Array.isArray(page) ? page : (page.list || [])
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.error = e.response?.data?.msg || e.response?.data?.error || '目录解析失败'
|
this.error = e.response?.data?.msg || e.response?.data?.error || '目录解析失败'
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -71,7 +71,9 @@ public class URLParamUtil {
|
|||||||
// 忽略单独处理的参数,不应拼接到分享URL中
|
// 忽略单独处理的参数,不应拼接到分享URL中
|
||||||
if (!paramName.equals("url") && !paramName.equals("pwd") && !paramName.equals("dirId")
|
if (!paramName.equals("url") && !paramName.equals("pwd") && !paramName.equals("dirId")
|
||||||
&& !paramName.equals("uuid") && !paramName.equals("auth")
|
&& !paramName.equals("uuid") && !paramName.equals("auth")
|
||||||
&& !paramName.equals("stoken") && !paramName.equals("zml")) {
|
&& !paramName.equals("stoken") && !paramName.equals("zml")
|
||||||
|
&& !paramName.equals("page") && !paramName.equals("pg")
|
||||||
|
&& !paramName.equals("pageCursor")) {
|
||||||
if (firstParam) {
|
if (firstParam) {
|
||||||
urlBuilder.append("?");
|
urlBuilder.append("?");
|
||||||
firstParam = false;
|
firstParam = false;
|
||||||
|
|||||||
@@ -10,9 +10,11 @@ import cn.qaiu.lz.common.util.URLParamUtil;
|
|||||||
import cn.qaiu.lz.web.model.AuthParam;
|
import cn.qaiu.lz.web.model.AuthParam;
|
||||||
import cn.qaiu.lz.web.model.CacheLinkInfo;
|
import cn.qaiu.lz.web.model.CacheLinkInfo;
|
||||||
import cn.qaiu.lz.web.model.ClientLinkResp;
|
import cn.qaiu.lz.web.model.ClientLinkResp;
|
||||||
|
import cn.qaiu.lz.web.model.FileListPageResp;
|
||||||
import cn.qaiu.lz.web.model.LinkInfoResp;
|
import cn.qaiu.lz.web.model.LinkInfoResp;
|
||||||
import cn.qaiu.lz.web.model.StatisticsInfo;
|
import cn.qaiu.lz.web.model.StatisticsInfo;
|
||||||
import cn.qaiu.lz.web.service.DbService;
|
import cn.qaiu.lz.web.service.DbService;
|
||||||
|
import cn.qaiu.parser.FolderPaging;
|
||||||
import cn.qaiu.parser.PanDomainTemplate;
|
import cn.qaiu.parser.PanDomainTemplate;
|
||||||
import cn.qaiu.parser.IPanTool;
|
import cn.qaiu.parser.IPanTool;
|
||||||
import cn.qaiu.parser.ParserCreate;
|
import cn.qaiu.parser.ParserCreate;
|
||||||
@@ -162,9 +164,50 @@ public class ParserApi {
|
|||||||
}}).collect(Collectors.toList());
|
}}).collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目录列表。不带 page 时行为与旧版一致;带 page 时返回该页(结构不变)。pg 是 page 的别名。
|
||||||
|
* 需要 hasMore / nextCursor 时用 {@link #getFileListPage}。
|
||||||
|
*/
|
||||||
@RouteMapping("/getFileList")
|
@RouteMapping("/getFileList")
|
||||||
public Future<List<FileInfo>> getFileList(HttpServerRequest request, String pwd, String dirId, String uuid,
|
public Future<List<FileInfo>> getFileList(HttpServerRequest request, String pwd, String dirId, String uuid,
|
||||||
String stoken, String zml, String auth) {
|
String stoken, String zml, String auth,
|
||||||
|
String page, String pg, String pageCursor) {
|
||||||
|
Integer pageNo;
|
||||||
|
try {
|
||||||
|
pageNo = FolderPaging.parsePage(StringUtils.isNotBlank(page) ? page : pg);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return Future.failedFuture(e.getMessage());
|
||||||
|
}
|
||||||
|
return listFolder(request, pwd, dirId, uuid, stoken, zml, auth, pageNo, pageCursor)
|
||||||
|
.map(FolderListResult::list);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 目录分页:参数同 /getFileList,另有 page(默认 1)与 pageCursor(上一页的 nextCursor)。
|
||||||
|
*/
|
||||||
|
@RouteMapping("/getFileListPage")
|
||||||
|
public Future<FileListPageResp> getFileListPage(HttpServerRequest request, String pwd, String dirId, String uuid,
|
||||||
|
String stoken, String zml, String auth,
|
||||||
|
String page, String pg, String pageCursor) {
|
||||||
|
int pageNo;
|
||||||
|
try {
|
||||||
|
Integer parsed = FolderPaging.parsePage(StringUtils.isNotBlank(page) ? page : pg);
|
||||||
|
pageNo = parsed == null ? 1 : parsed;
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
return Future.failedFuture(e.getMessage());
|
||||||
|
}
|
||||||
|
return listFolder(request, pwd, dirId, uuid, stoken, zml, auth, pageNo, pageCursor)
|
||||||
|
.map(r -> r.unpagedBeyondFirst()
|
||||||
|
? FileListPageResp.beyondUnpaged(pageNo)
|
||||||
|
: FileListPageResp.of(r.list(), pageNo, FolderPaging.pageInfo(r.shareLinkInfo())));
|
||||||
|
}
|
||||||
|
|
||||||
|
private record FolderListResult(List<FileInfo> list, ShareLinkInfo shareLinkInfo, boolean unpagedBeyondFirst) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private Future<FolderListResult> listFolder(HttpServerRequest request, String pwd, String dirId, String uuid,
|
||||||
|
String stoken, String zml, String auth,
|
||||||
|
Integer page, String pageCursor) {
|
||||||
String url = URLParamUtil.parserParams(request);
|
String url = URLParamUtil.parserParams(request);
|
||||||
ParserCreate parserCreate;
|
ParserCreate parserCreate;
|
||||||
try {
|
try {
|
||||||
@@ -172,6 +215,16 @@ public class ParserApi {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
return Future.failedFuture(e);
|
return Future.failedFuture(e);
|
||||||
}
|
}
|
||||||
|
ShareLinkInfo info = parserCreate.getShareLinkInfo();
|
||||||
|
if (page != null && page > 1 && !FileListPageResp.isPagedType(info.getType())) {
|
||||||
|
return Future.succeededFuture(new FolderListResult(new ArrayList<>(), info, true));
|
||||||
|
}
|
||||||
|
if (page != null) {
|
||||||
|
info.getOtherParam().put(FolderPaging.PAGE, page);
|
||||||
|
if (StringUtils.isNotBlank(pageCursor)) {
|
||||||
|
info.getOtherParam().put(FolderPaging.CURSOR, pageCursor);
|
||||||
|
}
|
||||||
|
}
|
||||||
String linkPrefix = getLinkPrefix(request);
|
String linkPrefix = getLinkPrefix(request);
|
||||||
JsonObject otherParam = ParserAuthUtil.buildOtherParam(request, auth, linkPrefix);
|
JsonObject otherParam = ParserAuthUtil.buildOtherParam(request, auth, linkPrefix);
|
||||||
parserCreate.getShareLinkInfo().getOtherParam().put("domainName", linkPrefix);
|
parserCreate.getShareLinkInfo().getOtherParam().put("domainName", linkPrefix);
|
||||||
@@ -198,7 +251,8 @@ public class ParserApi {
|
|||||||
ParserAuthUtil.recordAutoDonatedFailureIfNeeded(dbService,
|
ParserAuthUtil.recordAutoDonatedFailureIfNeeded(dbService,
|
||||||
parserCreate.getShareLinkInfo(), t);
|
parserCreate.getShareLinkInfo(), t);
|
||||||
});
|
});
|
||||||
});
|
})
|
||||||
|
.map(list -> new FolderListResult(list, info, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 目录解析下载文件
|
// 目录解析下载文件
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
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());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user