mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-11-30 17:16:59 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9b75b29d8 |
No files matched your search
@@ -25,8 +25,8 @@ body:
|
|||||||
id: version
|
id: version
|
||||||
attributes:
|
attributes:
|
||||||
label: 版本号
|
label: 版本号
|
||||||
description: 页面上的版本,或发布包名里的版本,例如 0.4.13。
|
description: 页面上的版本,或发布包名里的版本,例如 0.4.12。
|
||||||
placeholder: "0.4.13"
|
placeholder: "0.4.12"
|
||||||
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.13。不确定就写获取方式。
|
description: 例如 0.4.12。不确定就写获取方式。
|
||||||
placeholder: "0.4.13"
|
placeholder: "0.4.12"
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
- type: dropdown
|
- type: dropdown
|
||||||
|
|||||||
+20
-17
@@ -1,22 +1,25 @@
|
|||||||
## 更新内容
|
## 更新内容
|
||||||
|
|
||||||
- 蓝奏文件页识别 `ajaxfiles.php`(#310):
|
目录列表支持分页了。之前蓝奏云目录只返回前 50 个文件,小飞机盘和蓝奏云优享只返回前 60 个。早先的分页需求见 https://github.com/qaiu/netdisk-fast-download/issues/112 。
|
||||||
- 单文件页 iframe 里的下载 ajax 写成了 `/ajaxfiles.php`。解析器原来只认 `ajaxm.php` 和 `ajaxfile.php`,匹配不上就报「获取失败0, 可能分享已失效」。表单字段没有改。
|
|
||||||
- `https://njkn.lanzouw.com/winx123`(无密码)没有失效。修复后本机完整下载 1,197,569 字节,`unzip -t` 无错误。
|
- 目录分页(#308):
|
||||||
- 另外三个同样改成 `ajaxfiles.php` 的对照只各下载了 1 MiB Range,返回 206,文件头分别是 7z、zip、zip,没有做完整下载:
|
- 蓝奏云:按页读取 `filemoreajax`,每页 50 个。只有 `zt=2`(翻过最后一页)或不足 50 个的页才算结束。`zt=4`「请刷新,重试0」视为限流,同一页等 2 秒、再等 5 秒重试;仍失败就返回可重试的错误,不当作最后一页。每页返回 `nextCursor`,下一页沿用同一组翻页参数。不带游标时最多直接请求到第 6 页。
|
||||||
- `wwn.lanzouy.com/ihLkw1gezutg`
|
- 小飞机盘、蓝奏云优享:`offset` 作为页码,每页 60 个,由 `totalPage` / `total` 判断是否还有下一页。
|
||||||
- b66477 目录下的 `pan.lanzoui.com/io4y41i3zq5e`
|
- 新接口 `/v2/getFileListPage` 返回 `list`、`hasMore`、`nextPage`、`nextCursor`、`total`、`totalPage`。`/v2/getFileList` 也接受 `page`(或 `pg`)和 `pageCursor`。不带页码时返回结构和以前一样。不支持分页的网盘请求第 2 页及以后时返回空页。
|
||||||
- 密码目录 `b00yaejvte` 里的子文件 `w1.lanzn.com/i4VjZ332qzwh`
|
- 前端:目录面板和树形视图有「加载更多」,滚动到底也会自动加载下一页。已加载的文件会保留,加载失败时显示错误并停止自动加载,点击可重试。`list.html` 同样支持。
|
||||||
- 带密码的单文件分享没有找到公开样例,没有实测。
|
- 蓝奏云目录风控页(#307):目录分享页改用移动端 UA 请求,文件页仍用桌面 UA。如果仍返回空白风控页,提示「访问风控,不能据此判断分享已失效」,不再报成分享已失效。
|
||||||
- 目录按已加载文件名筛选(#311):
|
- 新增 Issue 表单:解析失败、运行问题、功能建议(#305)。
|
||||||
- 分享目录浏览器和首页解析后的目录共用目录树。两套视图以及独立的 `list.html` 按文件名做大小写不敏感的子串匹配,只筛已经加载的行,不把后续页自动拉完。
|
|
||||||
- 目录树底部「全选 / 取消全选」只作用于当前关键字命中的、已经加载的可选文件。不勾选被筛掉的项,不拉取未加载分页,也不清掉范围外原来的选择。
|
## 实测范围
|
||||||
- 分页仍走现有的 `nextCursor` / `pageCursor`。
|
|
||||||
- 界面验收跑在本机开发服务和本机夹具,不是线上分享页。
|
- 蓝奏云 `pan.lanzoui.com/b66477`:连续翻完 93 页,共 4598 个文件,没有重复,最后一页 9 个且 `hasMore=false`。实测遇到 `zt=4` 时,2 秒后重试成功。第 2 页的文件可以下载。
|
||||||
|
- 蓝奏云带密码目录 `moteam.lanzoum.com/b00yaejvte`(密码 `1234`):第 1 页 7 个且没有下一页,第 2 页为空。不带页码的旧接口仍返回 7 个。
|
||||||
|
- 蓝奏云优享:用真实小目录、把每页条数临时设为 1 来验证。`offset` 是从 1 开始的页码,`total` / `totalPage` 正确,翻过最后一页为空。
|
||||||
|
- 夸克、城通:目录列表和以前一样,请求第 2 页返回空页。
|
||||||
|
|
||||||
## 限制
|
## 限制
|
||||||
|
|
||||||
- 没有把这次界面验收当成线上分享页或全站界面已验。
|
- 小飞机盘没有可用的真实目录样本,只做了本地模拟测试(与蓝奏云优享是同一套接口)。
|
||||||
- 三个对照链接只验证了 1 MiB Range,不能据此说这些文件已经完整下载并核对。
|
- 蓝奏云优享没有实测超过 60 个文件的大目录。
|
||||||
- 带密码的单文件分享未测。
|
- 蓝奏云不带游标直接请求第 7 页及以后会提示需要游标,请按 `nextCursor` 顺序翻页。
|
||||||
- 本机访问部分蓝奏下载域时连接时好时坏。winx123 曾连续超时,重试后完整下载成功。
|
- 风控页提示只能说明这次请求被拦截,不代表分享一定有效。
|
||||||
@@ -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.13/netdisk-fast-download-linux-amd64.zip
|
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.12/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
|
||||||
|
|||||||
@@ -394,33 +394,6 @@ public abstract class PanBase implements IPanTool, Closeable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 尝试将响应体解析为 JsonObject,失败时返回 null,且不调用 fail()。
|
|
||||||
* 用于版本探测等允许非 JSON(例如 HTML)的场景,避免提前终止解析并阻断 nextParser()。
|
|
||||||
*
|
|
||||||
* @param res HttpResponse
|
|
||||||
* @return JsonObject,若响应体不是合法 JSON 则返回 null
|
|
||||||
*/
|
|
||||||
protected JsonObject tryParseJson(HttpResponse<?> res) {
|
|
||||||
String contentEncoding = res.getHeader("Content-Encoding");
|
|
||||||
try {
|
|
||||||
if ("gzip".equalsIgnoreCase(contentEncoding) && res.body() instanceof Buffer gzipBody
|
|
||||||
&& gzipBody.length() >= 2
|
|
||||||
&& (gzipBody.getByte(0) & 0xff) == 0x1f
|
|
||||||
&& (gzipBody.getByte(1) & 0xff) == 0x8b) {
|
|
||||||
String decompressed = decompressGzip(gzipBody);
|
|
||||||
return new JsonObject(decompressed);
|
|
||||||
} else {
|
|
||||||
return res.bodyAsJsonObject();
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.debug("响应体不是合法JSON,跳过: {}", e.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* body To text的封装, 会自动处理异常, 会自动解压gzip
|
|
||||||
/**
|
/**
|
||||||
* body To text的封装, 会自动处理异常, 会自动解压gzip
|
* body To text的封装, 会自动处理异常, 会自动解压gzip
|
||||||
* @param res HttpResponse
|
* @param res HttpResponse
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ public enum PanDomainTemplate {
|
|||||||
|
|
||||||
// https://www.ilanzou.com/s/
|
// https://www.ilanzou.com/s/
|
||||||
IZ("蓝奏云优享",
|
IZ("蓝奏云优享",
|
||||||
compile("https://www\\.ilanzou\\.com/s/(?<KEY>[^/?#]+)(?:[?#].*)?"),
|
compile("https://www\\.ilanzou\\.com/s/(?<KEY>.+)"),
|
||||||
"https://www.ilanzou.com/s/{shareKey}",
|
"https://www.ilanzou.com/s/{shareKey}",
|
||||||
IzTool.class),
|
IzTool.class),
|
||||||
// 网盘定义
|
// 网盘定义
|
||||||
@@ -111,7 +111,7 @@ public enum PanDomainTemplate {
|
|||||||
// https://www.feijix.com/s/
|
// https://www.feijix.com/s/
|
||||||
// https://share.feijipan.com/s/
|
// https://share.feijipan.com/s/
|
||||||
FJ("小飞机网盘",
|
FJ("小飞机网盘",
|
||||||
compile("https://(share\\.feijipan\\.com|www\\.feijix\\.com)/s/(?<KEY>[^/?#]+)(?:[?#].*)?"),
|
compile("https://(share\\.feijipan\\.com|www\\.feijix\\.com)/s/(?<KEY>.+)"),
|
||||||
"https://www.feijix.com/s/{shareKey}",
|
"https://www.feijix.com/s/{shareKey}",
|
||||||
FjTool.class),
|
FjTool.class),
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import cn.qaiu.parser.custom.CustomParserConfig;
|
|||||||
import cn.qaiu.parser.custom.CustomParserRegistry;
|
import cn.qaiu.parser.custom.CustomParserRegistry;
|
||||||
import cn.qaiu.parser.customjs.JsParserExecutor;
|
import cn.qaiu.parser.customjs.JsParserExecutor;
|
||||||
|
|
||||||
import cn.qaiu.util.ShareUrlParams;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
@@ -97,8 +96,6 @@ public class ParserCreate {
|
|||||||
}
|
}
|
||||||
} catch (IllegalStateException | IllegalArgumentException ignored) {}
|
} catch (IllegalStateException | IllegalArgumentException ignored) {}
|
||||||
|
|
||||||
applyShareUrlParams(shareLinkInfo, shareUrl);
|
|
||||||
|
|
||||||
// 设置标准URL
|
// 设置标准URL
|
||||||
if (customParserConfig.getStandardUrlTemplate() != null) {
|
if (customParserConfig.getStandardUrlTemplate() != null) {
|
||||||
String standardUrl = customParserConfig.getStandardUrlTemplate()
|
String standardUrl = customParserConfig.getStandardUrlTemplate()
|
||||||
@@ -129,10 +126,6 @@ public class ParserCreate {
|
|||||||
Matcher matcher = this.panDomainTemplate.getPattern().matcher(shareUrl);
|
Matcher matcher = this.panDomainTemplate.getPattern().matcher(shareUrl);
|
||||||
if (matcher.find()) {
|
if (matcher.find()) {
|
||||||
String k0 = matcher.group(KEY);
|
String k0 = matcher.group(KEY);
|
||||||
String cleanedKey = ShareUrlParams.cleanShareKey(k0);
|
|
||||||
if (StringUtils.isNotEmpty(cleanedKey)) {
|
|
||||||
k0 = cleanedKey;
|
|
||||||
}
|
|
||||||
String shareKey = URLEncoder.encode(k0, StandardCharsets.UTF_8);
|
String shareKey = URLEncoder.encode(k0, StandardCharsets.UTF_8);
|
||||||
|
|
||||||
// 返回规范化的标准链接
|
// 返回规范化的标准链接
|
||||||
@@ -149,15 +142,6 @@ public class ParserCreate {
|
|||||||
|
|
||||||
shareLinkInfo.setShareUrl(shareUrl);
|
shareLinkInfo.setShareUrl(shareUrl);
|
||||||
shareLinkInfo.setShareKey(shareKey);
|
shareLinkInfo.setShareKey(shareKey);
|
||||||
if (StringUtils.isBlank(shareLinkInfo.getSharePassword())) {
|
|
||||||
String pwdFromUrl = ShareUrlParams.extractSharePassword(shareUrl);
|
|
||||||
if (StringUtils.isNotEmpty(pwdFromUrl)) {
|
|
||||||
shareLinkInfo.setSharePassword(pwdFromUrl);
|
|
||||||
if (standardUrl != null && standardUrl.contains("{pwd}")) {
|
|
||||||
standardUrl = standardUrl.replace("{pwd}", pwdFromUrl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!isGenericBuiltInParser(panDomainTemplate)) {
|
if (!isGenericBuiltInParser(panDomainTemplate)) {
|
||||||
shareLinkInfo.setStandardUrl(standardUrl);
|
shareLinkInfo.setStandardUrl(standardUrl);
|
||||||
}
|
}
|
||||||
@@ -306,8 +290,6 @@ public class ParserCreate {
|
|||||||
}
|
}
|
||||||
} catch (IllegalStateException | IllegalArgumentException ignored) {}
|
} catch (IllegalStateException | IllegalArgumentException ignored) {}
|
||||||
|
|
||||||
applyShareUrlParams(shareLinkInfo, shareUrl);
|
|
||||||
|
|
||||||
// 设置标准URL(如果有模板)
|
// 设置标准URL(如果有模板)
|
||||||
if (customConfig.getStandardUrlTemplate() != null) {
|
if (customConfig.getStandardUrlTemplate() != null) {
|
||||||
String standardUrl = customConfig.getStandardUrlTemplate()
|
String standardUrl = customConfig.getStandardUrlTemplate()
|
||||||
@@ -428,23 +410,6 @@ public class ParserCreate {
|
|||||||
return customParserConfig;
|
return customParserConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private static void applyShareUrlParams(ShareLinkInfo shareLinkInfo, String shareUrl) {
|
|
||||||
String key = shareLinkInfo.getShareKey();
|
|
||||||
if (StringUtils.isNotEmpty(key)) {
|
|
||||||
String cleaned = ShareUrlParams.cleanShareKey(key);
|
|
||||||
if (StringUtils.isNotEmpty(cleaned)) {
|
|
||||||
shareLinkInfo.setShareKey(cleaned);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (StringUtils.isBlank(shareLinkInfo.getSharePassword())) {
|
|
||||||
String pwdFromUrl = ShareUrlParams.extractSharePassword(shareUrl);
|
|
||||||
if (StringUtils.isNotEmpty(pwdFromUrl)) {
|
|
||||||
shareLinkInfo.setSharePassword(pwdFromUrl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean isGenericBuiltInParser(PanDomainTemplate panDomainTemplate) {
|
private static boolean isGenericBuiltInParser(PanDomainTemplate panDomainTemplate) {
|
||||||
return GENERIC_BUILT_IN_PARSERS.contains(panDomainTemplate);
|
return GENERIC_BUILT_IN_PARSERS.contains(panDomainTemplate);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -81,14 +81,18 @@ public class CeTool extends PanBase {
|
|||||||
// 禁止跟随重定向:assertPublicHost 只校验初始 host,自动 30x 会绕过 SSRF 防护
|
// 禁止跟随重定向:assertPublicHost 只校验初始 host,自动 30x 会绕过 SSRF 防护
|
||||||
clientNoRedirects.getAbs(pingUrlV4).send().onSuccess(res -> {
|
clientNoRedirects.getAbs(pingUrlV4).send().onSuccess(res -> {
|
||||||
if (res.statusCode() == 200) {
|
if (res.statusCode() == 200) {
|
||||||
// 使用 tryParseJson 而非 asJson,避免非JSON响应(如HTML)提前终止整个解析流程
|
try {
|
||||||
JsonObject json = tryParseJson(res);
|
JsonObject json = asJson(res);
|
||||||
if (json != null && !json.isEmpty()) {
|
// v4 ping 成功且返回有效JSON,使用 Ce4Tool
|
||||||
log.debug("检测到Cloudreve 4.x (通过v4 ping)");
|
if (json != null && !json.isEmpty()) {
|
||||||
delegateToCe4Tool();
|
log.debug("检测到Cloudreve 4.x (通过v4 ping)");
|
||||||
return;
|
delegateToCe4Tool();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
// JSON解析失败,继续尝试 v3
|
||||||
|
log.debug("v4 ping返回非JSON响应,尝试v3");
|
||||||
}
|
}
|
||||||
log.debug("v4 ping返回非JSON响应,尝试v3");
|
|
||||||
}
|
}
|
||||||
// v4 ping失败或返回非JSON,尝试 v3
|
// v4 ping失败或返回非JSON,尝试 v3
|
||||||
tryV3Ping(baseUrl, key, pwd);
|
tryV3Ping(baseUrl, key, pwd);
|
||||||
@@ -107,14 +111,18 @@ public class CeTool extends PanBase {
|
|||||||
|
|
||||||
clientNoRedirects.getAbs(pingUrlV3).send().onSuccess(res -> {
|
clientNoRedirects.getAbs(pingUrlV3).send().onSuccess(res -> {
|
||||||
if (res.statusCode() == 200) {
|
if (res.statusCode() == 200) {
|
||||||
// 使用 tryParseJson 而非 asJson,避免非JSON响应(如HTML)提前终止整个解析流程
|
try {
|
||||||
JsonObject json = tryParseJson(res);
|
JsonObject json = asJson(res);
|
||||||
if (json != null && !json.isEmpty()) {
|
// v3 ping 成功且返回有效JSON,进一步验证是否为 v3
|
||||||
// 尝试调用 v3 share API 来确认
|
if (json != null && !json.isEmpty()) {
|
||||||
verifyV3AndParse(baseUrl, key, pwd);
|
// 尝试调用 v3 share API 来确认
|
||||||
return;
|
verifyV3AndParse(baseUrl, key, pwd);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
// JSON解析失败,不是Cloudreve盘
|
||||||
|
log.debug("v3 ping返回非JSON响应,不是Cloudreve盘");
|
||||||
}
|
}
|
||||||
log.debug("v3 ping返回非JSON响应,不是Cloudreve盘");
|
|
||||||
}
|
}
|
||||||
// v3 ping失败,不是Cloudreve盘
|
// v3 ping失败,不是Cloudreve盘
|
||||||
log.debug("v3 ping失败,尝试下一个解析器");
|
log.debug("v3 ping失败,尝试下一个解析器");
|
||||||
@@ -140,9 +148,9 @@ public class CeTool extends PanBase {
|
|||||||
httpRequest.send().onSuccess(res -> {
|
httpRequest.send().onSuccess(res -> {
|
||||||
try {
|
try {
|
||||||
if (res.statusCode() == 200) {
|
if (res.statusCode() == 200) {
|
||||||
JsonObject jsonObject = tryParseJson(res);
|
JsonObject jsonObject = asJson(res);
|
||||||
// 检查响应格式是否符合 v3 API
|
// 检查响应格式是否符合 v3 API
|
||||||
if (jsonObject != null && jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) {
|
if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) {
|
||||||
// v3 share API 成功,确认是 v3 版本
|
// v3 share API 成功,确认是 v3 版本
|
||||||
// 设置文件信息
|
// 设置文件信息
|
||||||
setFileInfo(jsonObject);
|
setFileInfo(jsonObject);
|
||||||
@@ -176,9 +184,9 @@ public class CeTool extends PanBase {
|
|||||||
httpRequest.send().onSuccess(res -> {
|
httpRequest.send().onSuccess(res -> {
|
||||||
try {
|
try {
|
||||||
if (res.statusCode() == 200) {
|
if (res.statusCode() == 200) {
|
||||||
JsonObject jsonObject = tryParseJson(res);
|
JsonObject jsonObject = asJson(res);
|
||||||
// 检查响应格式是否符合 v4 API
|
// 检查响应格式是否符合 v4 API
|
||||||
if (jsonObject != null && jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) {
|
if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) {
|
||||||
// v4 share API 成功,使用 Ce4Tool
|
// v4 share API 成功,使用 Ce4Tool
|
||||||
log.debug("确认是Cloudreve 4.x (通过v4 share API)");
|
log.debug("确认是Cloudreve 4.x (通过v4 share API)");
|
||||||
delegateToCe4Tool();
|
delegateToCe4Tool();
|
||||||
|
|||||||
@@ -99,14 +99,11 @@ public class LzTool extends PanBase {
|
|||||||
private static final Pattern P_AJAXDATA = Pattern.compile("ajaxdata\\s*=\\s*'([^']+)'");
|
private static final Pattern P_AJAXDATA = Pattern.compile("ajaxdata\\s*=\\s*'([^']+)'");
|
||||||
private static final Pattern P_WEBSIGN = Pattern.compile("'websign'\\s*:\\s*'([^']*)'");
|
private static final Pattern P_WEBSIGN = Pattern.compile("'websign'\\s*:\\s*'([^']*)'");
|
||||||
private static final Pattern P_WEBPAGE = Pattern.compile("[?&]webpage=([^&\"'\\s#]+)");
|
private static final Pattern P_WEBPAGE = Pattern.compile("[?&]webpage=([^&\"'\\s#]+)");
|
||||||
/**
|
/** 页面脚本里的绝对 ajax,例如 https://apifile.lanzouw.com/ajaxfile.php?file=123 */
|
||||||
* 页面脚本里的绝对 ajax,例如 https://apifile.lanzouw.com/ajaxfile.php?file=123。
|
|
||||||
* 文件名有 ajaxm / ajaxfile / ajaxfiles 三种,2026-11 起文件页 iframe 改用 ajaxfiles.php。
|
|
||||||
*/
|
|
||||||
private static final Pattern P_AJAX_ABSOLUTE = Pattern.compile(
|
private static final Pattern P_AJAX_ABSOLUTE = Pattern.compile(
|
||||||
"['\"]((?:https?:)?//[^'\"\\s<>]+/ajax(?:m|files?)\\.php\\?file=\\d+)['\"]",
|
"['\"]((?:https?:)?//[^'\"\\s<>]+/ajax(?:m|file)\\.php\\?file=\\d+)['\"]",
|
||||||
Pattern.CASE_INSENSITIVE);
|
Pattern.CASE_INSENSITIVE);
|
||||||
private static final Pattern P_AJAX_PATH = Pattern.compile("(?:['\"/]|^)(ajax(?:m|files?)\\.php\\?file=\\d+)");
|
private static final Pattern P_AJAX_PATH = Pattern.compile("(?:['\"/]|^)(ajax(?:m|file)\\.php\\?file=\\d+)");
|
||||||
private static final Pattern P_SIGN = Pattern.compile("'sign'\\s*:\\s*'([^']+)'");
|
private static final Pattern P_SIGN = Pattern.compile("'sign'\\s*:\\s*'([^']+)'");
|
||||||
private static final Pattern P_ISNGIS = Pattern.compile("var\\s+isngis\\s*=\\s*'([^']+)'");
|
private static final Pattern P_ISNGIS = Pattern.compile("var\\s+isngis\\s*=\\s*'([^']+)'");
|
||||||
private static final Pattern P_VERIFY_FILE = Pattern.compile("'file'\\s*:\\s*'([^']+)'");
|
private static final Pattern P_VERIFY_FILE = Pattern.compile("'file'\\s*:\\s*'([^']+)'");
|
||||||
|
|||||||
@@ -32,12 +32,8 @@ import java.util.zip.CRC32;
|
|||||||
import static cn.qaiu.util.RandomStringGenerator.gen36String;
|
import static cn.qaiu.util.RandomStringGenerator.gen36String;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 123盘解析器。
|
* 123盘解析器 v2 - 使用Android平台API
|
||||||
* 分享单文件走分享域名:先 POST /api/share/download/traffic/check,
|
* 支持账号密码或token配置
|
||||||
* 再 POST /api/v2/share/download/info。platform web,App-Version 149。
|
|
||||||
* 域名只由 shareKey 解码出的数字 uid 组成,不使用调用方提供的任意 host。
|
|
||||||
* 文件夹打包下载仍走 App-Version 55 的 batch_download_share_info。
|
|
||||||
* 支持账号密码或 token 配置。
|
|
||||||
*
|
*
|
||||||
* @author <a href="https://qaiu.top">QAIU</a>
|
* @author <a href="https://qaiu.top">QAIU</a>
|
||||||
*/
|
*/
|
||||||
@@ -45,13 +41,9 @@ public class Ye2Tool extends PanBase {
|
|||||||
|
|
||||||
private static final String API_BASE = "https://api.123278.com";
|
private static final String API_BASE = "https://api.123278.com";
|
||||||
private static final String GET_SHARE_INFO_URL = API_BASE + "/b/api/share/get?limit=100&next=1&orderBy=share_id&orderDirection=desc&shareKey={shareKey}&SharePwd={pwd}&ParentFileId={ParentFileId}&Page=1";
|
private static final String GET_SHARE_INFO_URL = API_BASE + "/b/api/share/get?limit=100&next=1&orderBy=share_id&orderDirection=desc&shareKey={shareKey}&SharePwd={pwd}&ParentFileId={ParentFileId}&Page=1";
|
||||||
/** 分享页脚本把 /share/download/traffic/check 加上 /api 前缀,发到当前分享域名。 */
|
private static final String DOWNLOAD_API_URL = API_BASE + "/b/api/file/download_info";
|
||||||
static final String SHARE_TRAFFIC_CHECK_PATH = "/api/share/download/traffic/check";
|
private static final String DOWNLOAD_API_V2_BASE = "https://api.123278.com";
|
||||||
/** 分享页脚本把 /v2/share/download/info 加上 /api 前缀,不是 api.123278.com/b/api。 */
|
private static final String DOWNLOAD_API_V2_PATH = "/b/api/v2/share/download/info";
|
||||||
static final String SHARE_DOWNLOAD_INFO_PATH = "/api/v2/share/download/info";
|
|
||||||
static final String SHARE_PLATFORM = "web";
|
|
||||||
/** 当前分享页静态资源里的 App-Version。个人文件接口 App-Version 55 会返回 5066。 */
|
|
||||||
static final String SHARE_WEB_APP_VERSION = "149";
|
|
||||||
private static final String BATCH_DOWNLOAD_API_URL = API_BASE + "/b/api/file/batch_download_share_info";
|
private static final String BATCH_DOWNLOAD_API_URL = API_BASE + "/b/api/file/batch_download_share_info";
|
||||||
private static final String LOGIN_URL = "https://login.123pan.com/api/user/sign_in";
|
private static final String LOGIN_URL = "https://login.123pan.com/api/user/sign_in";
|
||||||
|
|
||||||
@@ -134,25 +126,28 @@ public class Ye2Tool extends PanBase {
|
|||||||
return TokenCache.isExpired(cacheKey);
|
return TokenCache.isExpired(cacheKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String crc32(String data) {
|
||||||
|
CRC32 crc32 = new CRC32();
|
||||||
|
crc32.update(data.getBytes());
|
||||||
|
long value = crc32.getValue();
|
||||||
|
return String.format("%08x", value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private long hexToInt(String hexStr) {
|
||||||
|
return Long.parseLong(hexStr, 16);
|
||||||
|
}
|
||||||
|
|
||||||
private String encode123(String url, String way, String version, String timestamp) {
|
private String encode123(String url, String way, String version, String timestamp) {
|
||||||
return signQuery(url, way, version, Long.parseLong(timestamp), nextSignRandom());
|
Random random = new Random();
|
||||||
}
|
int randomInt = random.nextInt(10000000) + 1;
|
||||||
|
long a = (10000000L * randomInt) / 10000;
|
||||||
|
|
||||||
private static long nextSignRandom() {
|
long timeLong = Long.parseLong(timestamp) / 1000;
|
||||||
int randomInt = new Random().nextInt(10000000) + 1;
|
|
||||||
return (10000000L * randomInt) / 10000;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 签名原文:unix秒|随机数|实际路径|platform|App-Version|时间混淆值。
|
|
||||||
* 分享下载的路径是 /api/...,platform 是 web,版本是 149。
|
|
||||||
*/
|
|
||||||
static String signMaterial(String url, String way, String version, long timeMillis, long randomA) {
|
|
||||||
long timeLong = timeMillis / 1000;
|
|
||||||
java.time.LocalDateTime dateTime = java.time.Instant.ofEpochSecond(timeLong)
|
java.time.LocalDateTime dateTime = java.time.Instant.ofEpochSecond(timeLong)
|
||||||
.atZone(java.time.ZoneId.systemDefault())
|
.atZone(java.time.ZoneId.systemDefault())
|
||||||
.toLocalDateTime();
|
.toLocalDateTime();
|
||||||
String timeStr = dateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
|
String timeStr = dateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
|
||||||
|
|
||||||
StringBuilder g = new StringBuilder();
|
StringBuilder g = new StringBuilder();
|
||||||
for (char c : timeStr.toCharArray()) {
|
for (char c : timeStr.toCharArray()) {
|
||||||
int digit = Character.getNumericValue(c);
|
int digit = Character.getNumericValue(c);
|
||||||
@@ -162,22 +157,11 @@ public class Ye2Tool extends PanBase {
|
|||||||
g.append(CHAR_MAP.charAt(digit - 1));
|
g.append(CHAR_MAP.charAt(digit - 1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
String y = String.valueOf(crc32Decimal(g.toString()));
|
|
||||||
return timeLong + "|" + randomA + "|" + url + "|" + way + "|" + version + "|" + y;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String signQuery(String url, String way, String version, long timeMillis, long randomA) {
|
String y = String.valueOf(hexToInt(crc32(g.toString())));
|
||||||
String material = signMaterial(url, way, version, timeMillis, randomA);
|
String finalCrcInput = String.format("%d|%d|%s|%s|%s|%s", timeLong, a, url, way, version, y);
|
||||||
String y = material.substring(material.lastIndexOf('|') + 1);
|
String finalCrc = String.valueOf(hexToInt(crc32(finalCrcInput)));
|
||||||
long timeLong = timeMillis / 1000;
|
return String.format("?%s=%d-%d-%s", y, timeLong, a, finalCrc);
|
||||||
String finalCrc = String.valueOf(crc32Decimal(material));
|
|
||||||
return "?" + y + "=" + timeLong + "-" + randomA + "-" + finalCrc;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static long crc32Decimal(String data) {
|
|
||||||
CRC32 crc32 = new CRC32();
|
|
||||||
crc32.update(data.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
|
||||||
return crc32.getValue();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Future<String> parse() {
|
public Future<String> parse() {
|
||||||
@@ -226,14 +210,15 @@ public class Ye2Tool extends PanBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
JsonObject fileInfo = data.getJsonArray("InfoList").getJsonObject(0);
|
JsonObject fileInfo = data.getJsonArray("InfoList").getJsonObject(0);
|
||||||
|
if (token.equals("nologin")) {
|
||||||
|
fail(loginRequiredDownloadMessage(false, null));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (fileInfo.getInteger("Type", 0) == 1) {
|
if (fileInfo.getInteger("Type", 0) == 1) {
|
||||||
if (!hasUsableToken(token)) {
|
|
||||||
fail(loginRequiredDownloadMessage(false, null));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
getZipDownUrl(client, fileInfo);
|
getZipDownUrl(client, fileInfo);
|
||||||
} else {
|
} else {
|
||||||
getDownUrl(fileInfo, token);
|
getDownUrl(client, fileInfo);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.onFailure(this.handleFail(GET_SHARE_INFO_URL));
|
.onFailure(this.handleFail(GET_SHARE_INFO_URL));
|
||||||
@@ -332,55 +317,112 @@ public class Ye2Tool extends PanBase {
|
|||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private void getDownUrl(WebClient client, JsonObject fileInfo) {
|
||||||
* 分享单文件:流量预检通过后走分享域名 v2。不回退个人文件接口,也不创建订单。
|
|
||||||
*/
|
|
||||||
private void getDownUrl(JsonObject fileInfo, String token) {
|
|
||||||
setFileInfo(fileInfo);
|
setFileInfo(fileInfo);
|
||||||
|
|
||||||
String normalizedShareKey = YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey());
|
String normalizedShareKey = YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey());
|
||||||
applyResolvedShareKey(shareLinkInfo, normalizedShareKey);
|
if (StringUtils.isNotEmpty(normalizedShareKey)) {
|
||||||
Integer fileId = fileInfo.getInteger("FileId");
|
JsonObject v2Body = new JsonObject()
|
||||||
if (!usableShareKey(normalizedShareKey) || fileId == null) {
|
.put("ShareKey", normalizedShareKey)
|
||||||
fail("123网盘公开下载参数缺少分享标识");
|
.put("FileID", fileInfo.getInteger("FileId"))
|
||||||
|
.put("S3keyFlag", fileInfo.getString("S3KeyFlag"))
|
||||||
|
.put("Size", fileInfo.getLong("Size"))
|
||||||
|
.put("Etag", fileInfo.getString("Etag"));
|
||||||
|
requestShareV2Download(normalizedShareKey, v2Body).onSuccess(v2Url -> {
|
||||||
|
if (StringUtils.isNotEmpty(v2Url)) {
|
||||||
|
complete(v2Url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
requestLegacyDownUrl(client, fileInfo);
|
||||||
|
}).onFailure(err -> {
|
||||||
|
log.warn("Ye2 v2分享下载接口失败,回退旧接口: {}", err.getMessage());
|
||||||
|
requestLegacyDownUrl(client, fileInfo);
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
long size = fileInfo.getLong("Size") == null ? 0L : fileInfo.getLong("Size");
|
|
||||||
requestShareDownload(normalizedShareKey, fileId, fileInfo.getString("S3KeyFlag"), size,
|
requestLegacyDownUrl(client, fileInfo);
|
||||||
fileInfo.getString("Etag"), token).onSuccess(this::complete)
|
|
||||||
.onFailure(err -> fail(err.getMessage()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Future<String> requestShareDownload(String shareKey, long fileId, String s3keyFlag, long size,
|
private void requestLegacyDownUrl(WebClient client, JsonObject fileInfo) {
|
||||||
String etag, String token) {
|
JsonObject jsonObject = new JsonObject();
|
||||||
return executeShareFileDownload(this::postShareJson, new ShareFileRequest(
|
jsonObject.put("driveId", 0);
|
||||||
shareLinkInfo.getShareUrl(),
|
jsonObject.put("etag", fileInfo.getString("Etag"));
|
||||||
shareLinkInfo.getStandardUrl(),
|
jsonObject.put("fileId", fileInfo.getInteger("FileId"));
|
||||||
shareKey,
|
jsonObject.put("fileName", fileInfo.getString("FileName"));
|
||||||
shareLinkInfo.getSharePassword(),
|
jsonObject.put("s3keyFlag", fileInfo.getString("S3KeyFlag"));
|
||||||
fileId,
|
jsonObject.put("size", fileInfo.getLong("Size"));
|
||||||
s3keyFlag,
|
jsonObject.put("type", 0);
|
||||||
size,
|
|
||||||
etag,
|
String timestamp = String.valueOf(System.currentTimeMillis());
|
||||||
token,
|
String encryptedParams = encode123("/b/api/file/download_info", "android", "55", timestamp);
|
||||||
System.currentTimeMillis(),
|
String apiUrl = DOWNLOAD_API_URL + encryptedParams;
|
||||||
nextSignRandom()));
|
|
||||||
|
log.info("Ye2 API URL: {}", apiUrl);
|
||||||
|
|
||||||
|
HttpRequest<Buffer> bufferHttpRequest = client.postAbs(apiUrl);
|
||||||
|
bufferHttpRequest.putHeader("platform", "android");
|
||||||
|
bufferHttpRequest.putHeader("App-Version", "55");
|
||||||
|
bufferHttpRequest.putHeader("Authorization", "Bearer " + TokenCache.getToken(cacheKey));
|
||||||
|
bufferHttpRequest.putHeader("User-Agent", "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36");
|
||||||
|
bufferHttpRequest.putHeader("Content-Type", "application/json");
|
||||||
|
|
||||||
|
bufferHttpRequest
|
||||||
|
.sendJsonObject(jsonObject)
|
||||||
|
.onSuccess(res2 -> handleDownloadUrlResponse(client, asJson(res2), "Ye2"))
|
||||||
|
.onFailure(err -> fail("下载接口失败: " + err.getMessage()));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Future<JsonObject> postShareJson(ShareHttpCall call) {
|
private Future<String> requestShareV2Download(String shareKey, JsonObject body) {
|
||||||
Promise<JsonObject> promise = Promise.promise();
|
Promise<String> promise = Promise.promise();
|
||||||
HttpRequest<Buffer> request = client.postAbs(call.url());
|
String timestamp = String.valueOf(System.currentTimeMillis());
|
||||||
call.headers.forEach(entry -> request.putHeader(entry.getKey(), entry.getValue()));
|
String encryptedParams = encode123(DOWNLOAD_API_V2_PATH, "web", "3", timestamp);
|
||||||
request.sendJsonObject(call.body)
|
String apiUrl = DOWNLOAD_API_V2_BASE + DOWNLOAD_API_V2_PATH + encryptedParams;
|
||||||
.onSuccess(resp -> promise.complete(asJson(resp)))
|
String shareOrigin = resolveYeShareOrigin(shareKey);
|
||||||
.onFailure(promise::fail);
|
String shareReferer = buildShareReferer(shareOrigin, shareKey, shareLinkInfo.getSharePassword());
|
||||||
|
|
||||||
|
HttpRequest<Buffer> request = client.postAbs(apiUrl);
|
||||||
|
request.putHeader("Accept", "*/*");
|
||||||
|
request.putHeader("Authorization", "Bearer " + TokenCache.getToken(cacheKey));
|
||||||
|
request.putHeader("App-Version", "3");
|
||||||
|
request.putHeader("platform", "web");
|
||||||
|
request.putHeader("Origin", shareOrigin);
|
||||||
|
request.putHeader("Referer", shareReferer);
|
||||||
|
request.putHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36");
|
||||||
|
request.putHeader("Content-Type", "application/json;charset=UTF-8");
|
||||||
|
|
||||||
|
request.sendJsonObject(body).onSuccess(resp -> {
|
||||||
|
JsonObject json = asJson(resp);
|
||||||
|
if (json == null || json.getInteger("code", -1) != 0) {
|
||||||
|
promise.fail("v2接口返回异常: " + (json == null ? "null" : json.encode()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JsonObject data = json.getJsonObject("data", new JsonObject());
|
||||||
|
JsonArray dispatchList = data.getJsonArray("dispatchList", new JsonArray());
|
||||||
|
String downloadPath = data.getString("downloadPath");
|
||||||
|
if (StringUtils.isBlank(downloadPath)) {
|
||||||
|
promise.complete("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String prefix = "";
|
||||||
|
if (dispatchList.size() > 0) {
|
||||||
|
JsonObject firstDispatch = dispatchList.getJsonObject(0);
|
||||||
|
if (firstDispatch != null) {
|
||||||
|
prefix = firstDispatch.getString("prefix", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (StringUtils.isBlank(prefix)) {
|
||||||
|
promise.complete(downloadPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String finalUrl = prefix.endsWith("/") ? prefix.substring(0, prefix.length() - 1) : prefix;
|
||||||
|
finalUrl += downloadPath.startsWith("/") ? downloadPath : "/" + downloadPath;
|
||||||
|
promise.complete(finalUrl);
|
||||||
|
}).onFailure(promise::fail);
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 文件夹打包下载仍使用 App-Version 55 的 /b/api/file/batch_download_share_info。
|
|
||||||
* 分享页脚本已改走 /v2/file/batch_download_share_info,这次不改这条路径。
|
|
||||||
*/
|
|
||||||
private void getZipDownUrl(WebClient client, JsonObject fileInfo) {
|
private void getZipDownUrl(WebClient client, JsonObject fileInfo) {
|
||||||
JsonObject jsonObject = new JsonObject();
|
JsonObject jsonObject = new JsonObject();
|
||||||
jsonObject.put("shareKey", YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey()));
|
jsonObject.put("shareKey", YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey()));
|
||||||
@@ -649,322 +691,76 @@ public class Ye2Tool extends PanBase {
|
|||||||
Future<String> tokenFuture = resolveTokenFuture();
|
Future<String> tokenFuture = resolveTokenFuture();
|
||||||
|
|
||||||
tokenFuture.onSuccess(token -> {
|
tokenFuture.onSuccess(token -> {
|
||||||
if (hasUsableToken(token)) {
|
if (token.equals("nologin")) {
|
||||||
TokenCache.putToken(cacheKey, token);
|
fail(loginRequiredDownloadMessage(false, null));
|
||||||
}
|
|
||||||
String normalizedShareKey = resolveDownloadShareKey(paramJson, shareLinkInfo.getShareKey());
|
|
||||||
applyResolvedShareKey(shareLinkInfo, normalizedShareKey);
|
|
||||||
if (!usableShareKey(normalizedShareKey)) {
|
|
||||||
fail("123网盘公开下载参数缺少分享标识");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
long fileId = paramJson.getLong("fileId", paramJson.getLong("FileID", 0L));
|
|
||||||
String s3keyFlag = firstNonBlank(paramJson, "s3keyFlag", "S3keyFlag", "S3KeyFlag");
|
String rawShareKey = paramJson.getString("shareKey");
|
||||||
long size = paramJson.getLong("size", paramJson.getLong("Size", 0L));
|
if (StringUtils.isBlank(rawShareKey)) {
|
||||||
String etag = firstNonBlank(paramJson, "etag", "Etag");
|
rawShareKey = paramJson.getString("ShareKey");
|
||||||
requestShareDownload(normalizedShareKey, fileId, s3keyFlag, size, etag, token)
|
}
|
||||||
.onSuccess(this::complete)
|
if (StringUtils.isBlank(rawShareKey)) {
|
||||||
.onFailure(err -> fail(err.getMessage()));
|
rawShareKey = shareLinkInfo.getShareKey();
|
||||||
|
}
|
||||||
|
String normalizedShareKey = YeShareHostUtil.normalizeShareKey(rawShareKey);
|
||||||
|
if (StringUtils.isNotEmpty(normalizedShareKey)) {
|
||||||
|
JsonObject v2Body = new JsonObject()
|
||||||
|
.put("ShareKey", normalizedShareKey)
|
||||||
|
.put("FileID", paramJson.getInteger("fileId", paramJson.getInteger("FileID", 0)))
|
||||||
|
.put("S3keyFlag", paramJson.getString("s3keyFlag", paramJson.getString("S3keyFlag", "")))
|
||||||
|
.put("Size", paramJson.getLong("size", paramJson.getLong("Size", 0L)))
|
||||||
|
.put("Etag", paramJson.getString("etag", paramJson.getString("Etag", "")));
|
||||||
|
requestShareV2Download(normalizedShareKey, v2Body).onSuccess(v2Url -> {
|
||||||
|
if (StringUtils.isNotEmpty(v2Url)) {
|
||||||
|
complete(v2Url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
parseByIdLegacy(token, paramJson);
|
||||||
|
}).onFailure(err -> {
|
||||||
|
log.warn("Ye2 parseById v2接口失败,回退旧接口: {}", err.getMessage());
|
||||||
|
parseByIdLegacy(token, paramJson);
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
parseByIdLegacy(token, paramJson);
|
||||||
}).onFailure(err -> fail("123盘解析异常: " + err.getMessage()));
|
}).onFailure(err -> fail("123盘解析异常: " + err.getMessage()));
|
||||||
|
|
||||||
return promise.future();
|
return promise.future();
|
||||||
}
|
}
|
||||||
|
|
||||||
static final class ShareFileRequest {
|
private void parseByIdLegacy(String token, JsonObject paramJson) {
|
||||||
final String shareUrl;
|
if (paramJson.containsKey("FileID") && !paramJson.containsKey("fileId")) {
|
||||||
final String standardUrl;
|
paramJson.put("fileId", paramJson.getValue("FileID"));
|
||||||
final String shareKey;
|
|
||||||
final String password;
|
|
||||||
final long fileId;
|
|
||||||
final String s3keyFlag;
|
|
||||||
final long size;
|
|
||||||
final String etag;
|
|
||||||
final String token;
|
|
||||||
final long timeMillis;
|
|
||||||
final long randomA;
|
|
||||||
|
|
||||||
ShareFileRequest(String shareUrl, String standardUrl, String shareKey, String password, long fileId,
|
|
||||||
String s3keyFlag, long size, String etag, String token, long timeMillis, long randomA) {
|
|
||||||
this.shareUrl = shareUrl;
|
|
||||||
this.standardUrl = standardUrl;
|
|
||||||
this.shareKey = shareKey;
|
|
||||||
this.password = password;
|
|
||||||
this.fileId = fileId;
|
|
||||||
this.s3keyFlag = s3keyFlag;
|
|
||||||
this.size = size;
|
|
||||||
this.etag = etag;
|
|
||||||
this.token = token;
|
|
||||||
this.timeMillis = timeMillis;
|
|
||||||
this.randomA = randomA;
|
|
||||||
}
|
}
|
||||||
}
|
if (paramJson.containsKey("S3keyFlag") && !paramJson.containsKey("s3keyFlag")) {
|
||||||
|
paramJson.put("s3keyFlag", paramJson.getValue("S3keyFlag"));
|
||||||
static final class ShareHttpCall {
|
}
|
||||||
final String origin;
|
if (paramJson.containsKey("Size") && !paramJson.containsKey("size")) {
|
||||||
final String path;
|
paramJson.put("size", paramJson.getValue("Size"));
|
||||||
final String query;
|
}
|
||||||
final JsonObject body;
|
if (paramJson.containsKey("Etag") && !paramJson.containsKey("etag")) {
|
||||||
final MultiMap headers;
|
paramJson.put("etag", paramJson.getValue("Etag"));
|
||||||
|
|
||||||
ShareHttpCall(String origin, String path, String query, JsonObject body, MultiMap headers) {
|
|
||||||
this.origin = origin;
|
|
||||||
this.path = path;
|
|
||||||
this.query = query;
|
|
||||||
this.body = body;
|
|
||||||
this.headers = headers;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String url() {
|
String timestamp = String.valueOf(System.currentTimeMillis());
|
||||||
return origin + path + query;
|
String encryptedParams = encode123("/b/api/file/download_info", "android", "55", timestamp);
|
||||||
}
|
String apiUrl = DOWNLOAD_API_URL + encryptedParams;
|
||||||
}
|
|
||||||
|
|
||||||
@FunctionalInterface
|
log.info("Ye2 parseById API URL: {}", apiUrl);
|
||||||
interface ShareJsonPost {
|
|
||||||
Future<JsonObject> post(ShareHttpCall call);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
HttpRequest<Buffer> bufferHttpRequest = client.postAbs(apiUrl);
|
||||||
* 分享接口只发到 key 解码出的 https://{uid}.share.123pan.cn。
|
bufferHttpRequest.putHeader("platform", "android");
|
||||||
* mshare、/s/ 和调用方写入的其它 host 都不能改变这个目标。
|
bufferHttpRequest.putHeader("App-Version", "55");
|
||||||
*/
|
bufferHttpRequest.putHeader("Authorization", "Bearer " + token);
|
||||||
static String shareApiOrigin(String shareUrl, String standardUrl, String shareKey) {
|
bufferHttpRequest.putHeader("User-Agent", "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36");
|
||||||
String uid = YeShareHostUtil.getNumericSubdomainIdByShareKey(shareKey);
|
bufferHttpRequest.putHeader("Content-Type", "application/json");
|
||||||
if (!uid.matches("\\d+")) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (hostileShareHost(shareUrl) || hostileShareHost(standardUrl)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return "https://" + uid + ".share.123pan.cn";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
bufferHttpRequest
|
||||||
* 调用方给出的地址如果带了 host,只允许空、普通网页,或与 shareKey 一致的数字分享域名。
|
.sendJsonObject(paramJson)
|
||||||
* 127.0.0.1、云元数据、以及伪装成 123 域名的其它 host 直接拒绝。
|
.onSuccess(res2 -> handleDownloadUrlResponse(client, asJson(res2), "Ye2"))
|
||||||
*/
|
.onFailure(err -> fail("下载接口失败: " + err.getMessage()));
|
||||||
static boolean hostileShareHost(String url) {
|
|
||||||
if (StringUtils.isBlank(url)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
java.net.URI uri;
|
|
||||||
try {
|
|
||||||
uri = java.net.URI.create(url.trim());
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String host = uri.getHost();
|
|
||||||
if (host == null) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
String scheme = uri.getScheme();
|
|
||||||
if (!"https".equalsIgnoreCase(scheme) && !"http".equalsIgnoreCase(scheme)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (uri.getUserInfo() != null || uri.getPort() > 0) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (host.equalsIgnoreCase("www.123pan.com") || host.equalsIgnoreCase("yun.123pan.com")
|
|
||||||
|| host.equalsIgnoreCase("123pan.com")) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return !host.matches("(?i)\\d+\\.(?:mshare|share)\\.123pan\\.cn");
|
|
||||||
}
|
|
||||||
|
|
||||||
static JsonObject trafficCheckBody(String shareKey, long fileId) {
|
|
||||||
return new JsonObject()
|
|
||||||
.put("shareKey", shareKey)
|
|
||||||
.put("fileIds", new JsonArray().add(fileId));
|
|
||||||
}
|
|
||||||
|
|
||||||
static JsonObject downloadInfoBody(String shareKey, long fileId, String s3keyFlag, long size, String etag) {
|
|
||||||
return new JsonObject()
|
|
||||||
.put("ShareKey", shareKey)
|
|
||||||
.put("FileID", fileId)
|
|
||||||
.put("S3keyFlag", s3keyFlag == null ? "" : s3keyFlag)
|
|
||||||
.put("Size", size)
|
|
||||||
.put("Etag", etag == null ? "" : etag);
|
|
||||||
}
|
|
||||||
|
|
||||||
static String trafficStopMessage(JsonObject data) {
|
|
||||||
if (data == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (Boolean.TRUE.equals(data.getBoolean("isBlocked"))) {
|
|
||||||
return "123网盘限制了这个分享的下载。解析器不会自动下单或选择付费流量。";
|
|
||||||
}
|
|
||||||
if (Boolean.TRUE.equals(data.getBoolean("isPay"))) {
|
|
||||||
return "123网盘这个文件需要付费后下载。解析器不会自动下单或选择付费流量。";
|
|
||||||
}
|
|
||||||
if (Boolean.TRUE.equals(data.getBoolean("isTrafficExceeded"))) {
|
|
||||||
return "123网盘分享提取流量不足。解析器不会自动购买或选择付费流量。";
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String joinDownloadUrl(String downloadPath, String prefix) {
|
|
||||||
if (StringUtils.isBlank(downloadPath)) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String path = downloadPath.trim();
|
|
||||||
if (path.startsWith("//")) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
if (isAbsoluteHttp(path)) {
|
|
||||||
return path;
|
|
||||||
}
|
|
||||||
if (StringUtils.isBlank(prefix) || !isAbsoluteHttp(prefix.trim())) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String normalizedPrefix = prefix.trim();
|
|
||||||
if (normalizedPrefix.endsWith("/") && path.startsWith("/")) {
|
|
||||||
return normalizedPrefix.substring(0, normalizedPrefix.length() - 1) + path;
|
|
||||||
}
|
|
||||||
if (!normalizedPrefix.endsWith("/") && !path.startsWith("/")) {
|
|
||||||
return normalizedPrefix + "/" + path;
|
|
||||||
}
|
|
||||||
return normalizedPrefix + path;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean isAbsoluteHttp(String value) {
|
|
||||||
return value.startsWith("https://") || value.startsWith("http://");
|
|
||||||
}
|
|
||||||
|
|
||||||
static Future<String> executeShareFileDownload(ShareJsonPost post, ShareFileRequest request) {
|
|
||||||
String origin = shareApiOrigin(request.shareUrl, request.standardUrl, request.shareKey);
|
|
||||||
if (origin == null || !usableShareKey(request.shareKey)) {
|
|
||||||
return Future.failedFuture("123网盘公开下载参数缺少可识别的分享域名");
|
|
||||||
}
|
|
||||||
String referer = origin + "/123pan/" + YeShareHostUtil.normalizeShareKey(request.shareKey);
|
|
||||||
if (StringUtils.isNotBlank(request.password)) {
|
|
||||||
referer = referer + "?pwd=" + request.password;
|
|
||||||
}
|
|
||||||
MultiMap headers = shareHeaders(origin, referer, request.token);
|
|
||||||
ShareHttpCall traffic = new ShareHttpCall(
|
|
||||||
origin,
|
|
||||||
SHARE_TRAFFIC_CHECK_PATH,
|
|
||||||
signQuery(SHARE_TRAFFIC_CHECK_PATH, SHARE_PLATFORM, SHARE_WEB_APP_VERSION,
|
|
||||||
request.timeMillis, request.randomA),
|
|
||||||
trafficCheckBody(request.shareKey, request.fileId),
|
|
||||||
headers);
|
|
||||||
ShareHttpCall download = new ShareHttpCall(
|
|
||||||
origin,
|
|
||||||
SHARE_DOWNLOAD_INFO_PATH,
|
|
||||||
signQuery(SHARE_DOWNLOAD_INFO_PATH, SHARE_PLATFORM, SHARE_WEB_APP_VERSION,
|
|
||||||
request.timeMillis, request.randomA),
|
|
||||||
downloadInfoBody(request.shareKey, request.fileId, request.s3keyFlag, request.size, request.etag),
|
|
||||||
headers);
|
|
||||||
return post.post(traffic).compose(json -> {
|
|
||||||
if (json == null || json.getInteger("code", -1) != 0) {
|
|
||||||
return Future.failedFuture(shareV2FailureMessage(json, request.token));
|
|
||||||
}
|
|
||||||
String stop = trafficStopMessage(json.getJsonObject("data"));
|
|
||||||
if (stop != null) {
|
|
||||||
return Future.failedFuture(stop);
|
|
||||||
}
|
|
||||||
return post.post(download);
|
|
||||||
}).compose(json -> {
|
|
||||||
if (json == null || json.getInteger("code", -1) != 0) {
|
|
||||||
return Future.failedFuture(shareV2FailureMessage(json, request.token));
|
|
||||||
}
|
|
||||||
JsonObject data = json.getJsonObject("data", new JsonObject());
|
|
||||||
JsonArray dispatchList = data.getJsonArray("dispatchList", new JsonArray());
|
|
||||||
String prefix = "";
|
|
||||||
if (!dispatchList.isEmpty() && dispatchList.getJsonObject(0) != null) {
|
|
||||||
prefix = dispatchList.getJsonObject(0).getString("prefix", "");
|
|
||||||
}
|
|
||||||
String url = joinDownloadUrl(data.getString("downloadPath"), prefix);
|
|
||||||
if (StringUtils.isBlank(url)) {
|
|
||||||
return Future.failedFuture("123网盘公开下载接口未返回下载链接");
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(url);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private static MultiMap shareHeaders(String origin, String referer, String token) {
|
|
||||||
MultiMap headers = MultiMap.caseInsensitiveMultiMap();
|
|
||||||
headers.set("Accept", "*/*");
|
|
||||||
headers.set("App-Version", SHARE_WEB_APP_VERSION);
|
|
||||||
headers.set("platform", SHARE_PLATFORM);
|
|
||||||
headers.set("Origin", origin);
|
|
||||||
headers.set("Referer", referer);
|
|
||||||
headers.set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36");
|
|
||||||
headers.set("Content-Type", "application/json;charset=UTF-8");
|
|
||||||
String authorization = bearerAuthorization(token);
|
|
||||||
if (authorization != null) {
|
|
||||||
headers.set("Authorization", authorization);
|
|
||||||
}
|
|
||||||
return headers;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String firstNonBlank(JsonObject json, String... keys) {
|
|
||||||
if (json == null) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
for (String key : keys) {
|
|
||||||
String value = json.getString(key);
|
|
||||||
if (StringUtils.isNotBlank(value)) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
static String resolveDownloadShareKey(JsonObject paramJson, String fallbackShareKey) {
|
|
||||||
String shareKey = paramJson == null ? null : paramJson.getString("shareKey");
|
|
||||||
if (StringUtils.isBlank(shareKey) && paramJson != null) {
|
|
||||||
shareKey = paramJson.getString("ShareKey");
|
|
||||||
}
|
|
||||||
if (StringUtils.isBlank(shareKey)) {
|
|
||||||
shareKey = fallbackShareKey;
|
|
||||||
}
|
|
||||||
return YeShareHostUtil.normalizeShareKey(shareKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
static boolean usableShareKey(String shareKey) {
|
|
||||||
return StringUtils.isNotBlank(shareKey) && !"-".equals(shareKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* getFileDownInfo / redirectUrl 用 shareKey="-" 占位,错误文案会变成 /s/-。
|
|
||||||
* 目录参数里已有真实 shareKey 时,只替换这个占位地址。
|
|
||||||
*/
|
|
||||||
static void applyResolvedShareKey(ShareLinkInfo info, String shareKey) {
|
|
||||||
if (info == null || !usableShareKey(shareKey)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
info.setShareKey(shareKey);
|
|
||||||
String rebuilt = "https://www.123pan.com/s/" + shareKey;
|
|
||||||
if (isPlaceholderYeShareUrl(info.getShareUrl())) {
|
|
||||||
info.setShareUrl(rebuilt);
|
|
||||||
}
|
|
||||||
if (isPlaceholderYeShareUrl(info.getStandardUrl())) {
|
|
||||||
info.setStandardUrl(rebuilt);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static boolean isPlaceholderYeShareUrl(String url) {
|
|
||||||
return StringUtils.isNotBlank(url) && (url.endsWith("/s/-") || url.endsWith("/s/-.html"));
|
|
||||||
}
|
|
||||||
|
|
||||||
static String bearerAuthorization(String token) {
|
|
||||||
return hasUsableToken(token) ? "Bearer " + token : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* v2 非 0 的说明。5112 仍用现有登录提示;5113、5066 原样留在 v2 错误里,不再改写成个人文件接口的文案。
|
|
||||||
*/
|
|
||||||
static String shareV2FailureMessage(JsonObject json, String token) {
|
|
||||||
Integer code = json == null ? null : json.getInteger("code");
|
|
||||||
String message = json == null ? null : json.getString("message");
|
|
||||||
if (isYeLoginRequired(code, message)) {
|
|
||||||
return loginRequiredDownloadMessage(hasUsableToken(token), message);
|
|
||||||
}
|
|
||||||
return "v2接口返回异常: " + (json == null ? "null" : json.encode());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean hasUsableToken(String token) {
|
|
||||||
return StringUtils.isNotBlank(token) && !"nologin".equals(token);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setFileTimes(JsonObject item, FileInfo fileInfo) {
|
private void setFileTimes(JsonObject item, FileInfo fileInfo) {
|
||||||
|
|||||||
@@ -1,102 +0,0 @@
|
|||||||
package cn.qaiu.util;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import java.net.URLDecoder;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 从分享链接中整理 shareKey、提取常见提取码查询参数。
|
|
||||||
* 许多网盘模板用贪婪的 KEY 分组匹配路径,会把 ?pwd= / ?code= 或 # 片段吞进 shareKey。
|
|
||||||
*/
|
|
||||||
public final class ShareUrlParams {
|
|
||||||
|
|
||||||
private static final String[] PASSWORD_QUERY_KEYS = {"pwd", "password", "code"};
|
|
||||||
|
|
||||||
private ShareUrlParams() {
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 去掉误捕获的查询串和 hash 片段,保留路径中的 shareKey。
|
|
||||||
* 若清理后为空则返回原始值,避免把合法 key 清掉。
|
|
||||||
*/
|
|
||||||
public static String cleanShareKey(String key) {
|
|
||||||
if (StringUtils.isEmpty(key)) {
|
|
||||||
return key;
|
|
||||||
}
|
|
||||||
String cleaned = key;
|
|
||||||
int hashIndex = cleaned.indexOf('#');
|
|
||||||
if (hashIndex >= 0) {
|
|
||||||
cleaned = cleaned.substring(0, hashIndex);
|
|
||||||
}
|
|
||||||
int queryIndex = cleaned.indexOf('?');
|
|
||||||
if (queryIndex >= 0) {
|
|
||||||
cleaned = cleaned.substring(0, queryIndex);
|
|
||||||
}
|
|
||||||
return StringUtils.isEmpty(cleaned) ? key : cleaned;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 从完整分享 URL(或误带在 key 里的查询串)提取提取码。
|
|
||||||
* 优先 {@code pwd},其次 {@code password}、{@code code}(小飞机等)。
|
|
||||||
*/
|
|
||||||
public static String extractSharePassword(String shareUrl) {
|
|
||||||
if (StringUtils.isBlank(shareUrl)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
String query = queryString(shareUrl);
|
|
||||||
if (StringUtils.isEmpty(query)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
Map<String, String> params = parseQuery(query);
|
|
||||||
for (String name : PASSWORD_QUERY_KEYS) {
|
|
||||||
String value = params.get(name);
|
|
||||||
if (StringUtils.isNotEmpty(value)) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String queryString(String url) {
|
|
||||||
String noHash = url;
|
|
||||||
int hashIndex = url.indexOf('#');
|
|
||||||
if (hashIndex >= 0) {
|
|
||||||
noHash = url.substring(0, hashIndex);
|
|
||||||
}
|
|
||||||
int queryIndex = noHash.indexOf('?');
|
|
||||||
if (queryIndex < 0 || queryIndex == noHash.length() - 1) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return noHash.substring(queryIndex + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
static Map<String, String> parseQuery(String query) {
|
|
||||||
Map<String, String> params = new LinkedHashMap<>();
|
|
||||||
String[] pairs = query.split("&");
|
|
||||||
for (String pair : pairs) {
|
|
||||||
if (pair.isEmpty()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
int eq = pair.indexOf('=');
|
|
||||||
String rawName = eq >= 0 ? pair.substring(0, eq) : pair;
|
|
||||||
String rawValue = eq >= 0 ? pair.substring(eq + 1) : "";
|
|
||||||
String name = decode(rawName).toLowerCase();
|
|
||||||
if (name.isEmpty() || params.containsKey(name)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
params.put(name, decode(rawValue));
|
|
||||||
}
|
|
||||||
return params;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String decode(String value) {
|
|
||||||
try {
|
|
||||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
package cn.qaiu.parser;
|
|
||||||
|
|
||||||
import cn.qaiu.WebClientVertxInit;
|
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
|
||||||
import io.vertx.core.Vertx;
|
|
||||||
import io.vertx.core.buffer.Buffer;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
import io.vertx.ext.web.client.HttpResponse;
|
|
||||||
import org.junit.BeforeClass;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.lang.reflect.InvocationHandler;
|
|
||||||
import java.lang.reflect.Proxy;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 探测场景必须用 tryParseJson:asJson 会 fail(),从而阻断 nextParser。
|
|
||||||
*/
|
|
||||||
public class PanBaseTryParseJsonTest {
|
|
||||||
|
|
||||||
private static Vertx vertx;
|
|
||||||
|
|
||||||
@BeforeClass
|
|
||||||
public static void setUpClass() {
|
|
||||||
// 不在用例结束后关闭 Vertx:共享 WebClient 绑定该实例,关闭会导致同 JVM 后续测试出现 Client is closed
|
|
||||||
vertx = Vertx.vertx();
|
|
||||||
WebClientVertxInit.init(vertx);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static final class ProbeTool extends PanBase {
|
|
||||||
ProbeTool() {
|
|
||||||
super();
|
|
||||||
this.shareLinkInfo = ShareLinkInfo.newBuilder()
|
|
||||||
.type("ce")
|
|
||||||
.panName("Cloudreve")
|
|
||||||
.shareKey("k")
|
|
||||||
.shareUrl("https://example.com/s/k")
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public io.vertx.core.Future<String> parse() {
|
|
||||||
return promise.future();
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonObject probe(HttpResponse<?> res) {
|
|
||||||
return tryParseJson(res);
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonObject parseOrFail(HttpResponse<?> res) {
|
|
||||||
return asJson(res);
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean promiseCompleted() {
|
|
||||||
return promise.future().isComplete();
|
|
||||||
}
|
|
||||||
|
|
||||||
boolean promiseFailed() {
|
|
||||||
return promise.future().failed();
|
|
||||||
}
|
|
||||||
|
|
||||||
String failureMessage() {
|
|
||||||
return promise.future().cause() == null ? null : promise.future().cause().getMessage();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
private static HttpResponse<Buffer> stub(String contentEncoding, String body) {
|
|
||||||
Buffer buffer = body == null ? null : Buffer.buffer(body);
|
|
||||||
return (HttpResponse<Buffer>) Proxy.newProxyInstance(
|
|
||||||
HttpResponse.class.getClassLoader(),
|
|
||||||
new Class<?>[]{HttpResponse.class},
|
|
||||||
(proxy, method, args) -> {
|
|
||||||
switch (method.getName()) {
|
|
||||||
case "getHeader":
|
|
||||||
String name = args != null && args.length > 0 ? String.valueOf(args[0]) : "";
|
|
||||||
return "Content-Encoding".equalsIgnoreCase(name) ? contentEncoding : null;
|
|
||||||
case "body":
|
|
||||||
return buffer;
|
|
||||||
case "bodyAsString":
|
|
||||||
return body;
|
|
||||||
case "bodyAsJsonObject":
|
|
||||||
if (body == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return new JsonObject(body);
|
|
||||||
default:
|
|
||||||
if (method.isDefault()) {
|
|
||||||
return InvocationHandler.invokeDefault(proxy, method, args);
|
|
||||||
}
|
|
||||||
Class<?> type = method.getReturnType();
|
|
||||||
if (type == boolean.class) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (type == int.class || type == long.class) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void tryParseJsonReturnsNullForHtmlWithoutFailingPromise() {
|
|
||||||
ProbeTool tool = new ProbeTool();
|
|
||||||
JsonObject json = tool.probe(stub(null, "<html><body>not json</body></html>"));
|
|
||||||
assertNull(json);
|
|
||||||
assertFalse(tool.promiseCompleted());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void tryParseJsonParsesObject() {
|
|
||||||
ProbeTool tool = new ProbeTool();
|
|
||||||
JsonObject json = tool.probe(stub(null, "{\"code\":0,\"data\":\"ok\"}"));
|
|
||||||
assertEquals(0, json.getInteger("code").intValue());
|
|
||||||
assertFalse(tool.promiseCompleted());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void asJsonFailsPromiseOnHtml() {
|
|
||||||
ProbeTool tool = new ProbeTool();
|
|
||||||
JsonObject json = tool.parseOrFail(stub(null, "<!DOCTYPE html>"));
|
|
||||||
assertTrue(json == null || json.isEmpty());
|
|
||||||
assertTrue(tool.promiseFailed());
|
|
||||||
assertTrue(tool.failureMessage(), tool.failureMessage().contains("json格式异常"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
package cn.qaiu.parser;
|
|
||||||
|
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 完整分享链接里的提取码不应被吞进 shareKey。
|
|
||||||
*/
|
|
||||||
public class ShareUrlQueryTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void feijipanCodeQueryBecomesPassword() {
|
|
||||||
ShareLinkInfo info = ParserCreate.fromShareUrl("https://share.feijipan.com/s/SjfEaY2z?code=064d")
|
|
||||||
.getShareLinkInfo();
|
|
||||||
assertEquals("fj", info.getType());
|
|
||||||
assertEquals("SjfEaY2z", info.getShareKey());
|
|
||||||
assertEquals("064d", info.getSharePassword());
|
|
||||||
assertTrue(info.getStandardUrl().contains("SjfEaY2z"));
|
|
||||||
assertTrue("standard url should not keep the query in the key",
|
|
||||||
!info.getStandardUrl().contains("code=064d") || !info.getStandardUrl().contains("SjfEaY2z?"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void yePwdQueryIsExtractedWithoutChangingKey() {
|
|
||||||
ShareLinkInfo info = ParserCreate.fromShareUrl("https://www.123278.com/s/lN7UVv-pbYJ.html?pwd=abcd")
|
|
||||||
.getShareLinkInfo();
|
|
||||||
assertEquals("ye", info.getType());
|
|
||||||
assertEquals("lN7UVv-pbYJ", info.getShareKey());
|
|
||||||
assertEquals("abcd", info.getSharePassword());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void lanzouQueryPasswordAndWebpageDoNotPolluteKey() {
|
|
||||||
ShareLinkInfo info = ParserCreate.fromShareUrl("https://a.lanzouw.com/iabc?webpage=wp1&pwd=secret")
|
|
||||||
.getShareLinkInfo();
|
|
||||||
assertEquals("lz", info.getType());
|
|
||||||
assertEquals("iabc", info.getShareKey());
|
|
||||||
assertEquals("secret", info.getSharePassword());
|
|
||||||
assertTrue(info.getShareUrl().contains("webpage=wp1"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void ilanzouHashAndCodeQuery() {
|
|
||||||
ShareLinkInfo info = ParserCreate.fromShareUrl("https://www.ilanzou.com/s/RkR09zIL?code=abc#/list")
|
|
||||||
.getShareLinkInfo();
|
|
||||||
assertEquals("iz", info.getType());
|
|
||||||
assertEquals("RkR09zIL", info.getShareKey());
|
|
||||||
assertEquals("abc", info.getSharePassword());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void ucPublicQueryIsNotTreatedAsPassword() {
|
|
||||||
ShareLinkInfo info = ParserCreate.fromShareUrl("https://drive.uc.cn/s/e623b6da278e4?public=1#/list/share")
|
|
||||||
.getShareLinkInfo();
|
|
||||||
assertEquals("uc", info.getType());
|
|
||||||
assertEquals("e623b6da278e4", info.getShareKey());
|
|
||||||
assertTrue(info.getSharePassword() == null || info.getSharePassword().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void plainLanzouUrlUnchanged() {
|
|
||||||
ShareLinkInfo info = ParserCreate.fromShareUrl("https://wwn.lanzouy.com/ihLkw1gezutg")
|
|
||||||
.getShareLinkInfo();
|
|
||||||
assertEquals("lz", info.getType());
|
|
||||||
assertEquals("ihLkw1gezutg", info.getShareKey());
|
|
||||||
assertTrue(info.getSharePassword() == null || info.getSharePassword().isEmpty());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import cn.qaiu.WebClientVertxInit;
|
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
|
||||||
import io.vertx.core.MultiMap;
|
|
||||||
import io.vertx.core.Vertx;
|
|
||||||
import io.vertx.core.http.HttpServer;
|
|
||||||
import org.junit.After;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.CopyOnWriteArrayList;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 蓝奏文件页离线回归:2026-11 起文件页 iframe 的下载 ajax 改名为 ajaxfiles.php,
|
|
||||||
* 其余字段(wp_sign / ajaxdata / kd / ves)不变。本地模拟 分享页 → /fn iframe → ajaxfiles.php → 下载域 302。
|
|
||||||
*/
|
|
||||||
public class LzToolAjaxfilesTest {
|
|
||||||
|
|
||||||
private static final String SHARE_KEY = "winx123";
|
|
||||||
private static final String FILE_ID = "333017612";
|
|
||||||
|
|
||||||
private Vertx vertx;
|
|
||||||
private HttpServer server;
|
|
||||||
private final List<String> ajaxPaths = new CopyOnWriteArrayList<>();
|
|
||||||
private final List<MultiMap> ajaxForms = new CopyOnWriteArrayList<>();
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void setup() throws Exception {
|
|
||||||
vertx = Vertx.vertx();
|
|
||||||
WebClientVertxInit.init(vertx);
|
|
||||||
server = vertx.createHttpServer().requestHandler(req -> {
|
|
||||||
String path = req.path();
|
|
||||||
if ("GET".equals(req.method().name()) && path.equals("/" + SHARE_KEY)) {
|
|
||||||
html(req.response(), sharePage());
|
|
||||||
} else if ("GET".equals(req.method().name()) && path.equals("/fn")) {
|
|
||||||
html(req.response(), iframePage());
|
|
||||||
} else if ("POST".equals(req.method().name()) && path.startsWith("/ajax")) {
|
|
||||||
req.setExpectMultipart(true);
|
|
||||||
req.endHandler(v -> {
|
|
||||||
ajaxPaths.add(req.uri());
|
|
||||||
ajaxForms.add(MultiMap.caseInsensitiveMultiMap().addAll(req.formAttributes()));
|
|
||||||
String dom = "http://127.0.0.1:" + server.actualPort();
|
|
||||||
req.response().putHeader("Content-Type", "application/json")
|
|
||||||
.end("{\"zt\":1,\"dom\":\"" + dom + "\",\"url\":\"?mock-token\",\"inf\":0}");
|
|
||||||
});
|
|
||||||
} else if (path.equals("/file/")) {
|
|
||||||
req.response().setStatusCode(302)
|
|
||||||
.putHeader("Location", "http://cdn.test/2026/11/25/steam.zip")
|
|
||||||
.end();
|
|
||||||
} else {
|
|
||||||
req.response().setStatusCode(404).end();
|
|
||||||
}
|
|
||||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
@After
|
|
||||||
public void cleanup() throws Exception {
|
|
||||||
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
|
||||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void filePageWithAjaxfilesIframeResolvesDirectLink() throws Exception {
|
|
||||||
String url = "http://127.0.0.1:" + server.actualPort() + "/" + SHARE_KEY;
|
|
||||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("lz").panName("蓝奏云").shareKey(SHARE_KEY)
|
|
||||||
.shareUrl(url).standardUrl(url).build();
|
|
||||||
|
|
||||||
String link = new LzTool(info).parse().toCompletionStage().toCompletableFuture()
|
|
||||||
.get(30, TimeUnit.SECONDS);
|
|
||||||
|
|
||||||
assertEquals("http://cdn.test/2026/11/25/steam.zip", link);
|
|
||||||
assertEquals(List.of("/ajaxfiles.php?file=" + FILE_ID), ajaxPaths);
|
|
||||||
MultiMap form = ajaxForms.get(0);
|
|
||||||
assertEquals("downprocess", form.get("action"));
|
|
||||||
assertEquals("test-wp-sign", form.get("sign"));
|
|
||||||
assertEquals("test-ajaxdata", form.get("websignkey"));
|
|
||||||
assertEquals("test-ajaxdata", form.get("signs"));
|
|
||||||
assertEquals("1", form.get("ves"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void html(io.vertx.core.http.HttpServerResponse res, String body) {
|
|
||||||
res.putHeader("Content-Type", "text/html; charset=utf-8").end(body);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String sharePage() {
|
|
||||||
return """
|
|
||||||
<!DOCTYPE html><html><head><title>steam.zip - 蓝奏云</title>
|
|
||||||
<meta name="description" content="文件大小:1.1 M" /></head><body>
|
|
||||||
<div class="n_box_3fn" id="filenajax">steam.zip</div>
|
|
||||||
<div class="n_file"><div class="n_filesize">大小:1.1 M</div>
|
|
||||||
<iframe class="n_downlink" name="1795620352" src="/fn?mock-fn-query" frameborder="0" scrolling="no"></iframe></div>
|
|
||||||
</body></html>
|
|
||||||
""";
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String iframePage() {
|
|
||||||
return """
|
|
||||||
<html><body><div id="tourl"></div>
|
|
||||||
<script type="text/javascript">
|
|
||||||
var wsk_sign = 'c20230908';
|
|
||||||
var wp_sign = 'test-wp-sign';
|
|
||||||
var ajaxdata = 'test-ajaxdata';
|
|
||||||
var kdns =1;
|
|
||||||
$.ajax({
|
|
||||||
type : 'post',
|
|
||||||
url : '/ajaxfiles.php?file=%s',
|
|
||||||
data : { 'action':'downprocess','websignkey':ajaxdata,'signs':ajaxdata,'sign':wp_sign,'websign':'','kd':kdns,'ves':1 },
|
|
||||||
dataType : 'json'
|
|
||||||
});
|
|
||||||
</script></body></html>
|
|
||||||
""".formatted(FILE_ID);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -156,16 +156,6 @@ public class LzToolShareUrlTest {
|
|||||||
assertEquals("https://apifile.lanzouw.com/ajaxm.php?file=42", LzTool.fileAjaxTarget(html));
|
assertEquals("https://apifile.lanzouw.com/ajaxm.php?file=42", LzTool.fileAjaxTarget(html));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void ajaxfilesEndpointIsRecognized() {
|
|
||||||
assertEquals("/ajaxfiles.php?file=333017612",
|
|
||||||
LzTool.fileAjaxTarget("url : '/ajaxfiles.php?file=333017612',"));
|
|
||||||
assertEquals("https://apifile.lanzouw.com/ajaxfiles.php?file=7",
|
|
||||||
LzTool.fileAjaxTarget("url : 'https://apifile.lanzouw.com/ajaxfiles.php?file=7',"));
|
|
||||||
assertEquals("/ajaxm.php?file=5", LzTool.fileAjaxTarget("url : '/ajaxm.php?file=5',"));
|
|
||||||
assertNull(LzTool.fileAjaxTarget("url : '/ajaxfilex.php?file=5',"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void relativeFileAjaxFallsThroughToApifileBeforeWwww() {
|
public void relativeFileAjaxFallsThroughToApifileBeforeWwww() {
|
||||||
String html = "url : '/ajaxfile.php?file=150233466',";
|
String html = "url : '/ajaxfile.php?file=150233466',";
|
||||||
|
|||||||
@@ -18,8 +18,6 @@ public class Ye2LoginHintTest {
|
|||||||
assertTrue(Ye2Tool.isYeLoginRequired(0, "需要登录才能下载"));
|
assertTrue(Ye2Tool.isYeLoginRequired(0, "需要登录才能下载"));
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(0, "ok"));
|
assertFalse(Ye2Tool.isYeLoginRequired(0, "ok"));
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(null, null));
|
assertFalse(Ye2Tool.isYeLoginRequired(null, null));
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(5113, "分享方提取流量包不足"));
|
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(5066, "该文件暂不支持在当前版本下载"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -1,410 +0,0 @@
|
|||||||
package cn.qaiu.parser.impl;
|
|
||||||
|
|
||||||
import cn.qaiu.entity.ShareLinkInfo;
|
|
||||||
import io.vertx.core.Future;
|
|
||||||
import io.vertx.core.json.JsonArray;
|
|
||||||
import io.vertx.core.json.JsonObject;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertFalse;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 123 分享单文件下载规则。不访问网络。
|
|
||||||
* mvn -pl parser -DskipTests=false -Dtest=Ye2ToolTest,Ye2LoginHintTest test
|
|
||||||
*/
|
|
||||||
public class Ye2ToolTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void downloadUsesShareKeyEncodedInDirectoryFileParameter() {
|
|
||||||
JsonObject directoryFileParameter = new JsonObject()
|
|
||||||
.put("shareKey", "iaKtVv-6OECd.html?from=dir")
|
|
||||||
.put("fileId", 123);
|
|
||||||
|
|
||||||
assertEquals("iaKtVv-6OECd",
|
|
||||||
Ye2Tool.resolveDownloadShareKey(directoryFileParameter, "-"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void downloadFallsBackToParserShareKeyWhenParameterHasNone() {
|
|
||||||
assertEquals("iaKtVv-6OECd",
|
|
||||||
Ye2Tool.resolveDownloadShareKey(new JsonObject(), "iaKtVv-6OECd.html"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void downloadAcceptsCapitalShareKeyFromParameter() {
|
|
||||||
JsonObject directoryFileParameter = new JsonObject()
|
|
||||||
.put("ShareKey", "iaKtVv-r4aCd");
|
|
||||||
|
|
||||||
assertEquals("iaKtVv-r4aCd",
|
|
||||||
Ye2Tool.resolveDownloadShareKey(directoryFileParameter, "-"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void anonymous123RequestsDoNotSendFakeBearerTokens() {
|
|
||||||
assertNull(Ye2Tool.bearerAuthorization(null));
|
|
||||||
assertNull(Ye2Tool.bearerAuthorization(""));
|
|
||||||
assertNull(Ye2Tool.bearerAuthorization("nologin"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void configured123TokenKeepsExistingBearerAuthentication() {
|
|
||||||
assertEquals("Bearer configured-token",
|
|
||||||
Ye2Tool.bearerAuthorization("configured-token"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shareDownloadUsesCurrentWebAppVersion() {
|
|
||||||
assertEquals("149", Ye2Tool.SHARE_WEB_APP_VERSION);
|
|
||||||
assertTrue(Ye2Tool.usableShareKey("iaKtVv-r4aCd"));
|
|
||||||
assertFalse(Ye2Tool.usableShareKey("-"));
|
|
||||||
assertFalse(Ye2Tool.usableShareKey(""));
|
|
||||||
assertFalse(Ye2Tool.usableShareKey(null));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void placeholderShareUrlIsReplacedWithShareKeyFromFileParameter() {
|
|
||||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
|
||||||
.type("ye")
|
|
||||||
.shareKey("-")
|
|
||||||
.shareUrl("https://www.123pan.com/s/-")
|
|
||||||
.standardUrl("https://www.123pan.com/s/-")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
Ye2Tool.applyResolvedShareKey(info, "iaKtVv-r4aCd");
|
|
||||||
|
|
||||||
assertEquals("iaKtVv-r4aCd", info.getShareKey());
|
|
||||||
assertEquals("https://www.123pan.com/s/iaKtVv-r4aCd", info.getShareUrl());
|
|
||||||
assertEquals("https://www.123pan.com/s/iaKtVv-r4aCd", info.getStandardUrl());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void realShareUrlIsKeptWhenResolvingDirectoryFile() {
|
|
||||||
String original = "https://1815268665.mshare.123pan.cn/123pan/iaKtVv-r4aCd";
|
|
||||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
|
||||||
.type("ye")
|
|
||||||
.shareKey("iaKtVv-r4aCd")
|
|
||||||
.shareUrl(original)
|
|
||||||
.standardUrl("https://www.123pan.com/s/iaKtVv-r4aCd")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
Ye2Tool.applyResolvedShareKey(info, "iaKtVv-r4aCd");
|
|
||||||
|
|
||||||
assertEquals(original, info.getShareUrl());
|
|
||||||
assertEquals("https://www.123pan.com/s/iaKtVv-r4aCd", info.getStandardUrl());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void placeholderStandardUrlDoesNotReplaceOriginalShareUrl() {
|
|
||||||
String original = "https://1815268665.mshare.123pan.cn/123pan/iaKtVv-r4aCd";
|
|
||||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
|
||||||
.type("ye")
|
|
||||||
.shareKey("-")
|
|
||||||
.shareUrl(original)
|
|
||||||
.standardUrl("https://www.123pan.com/s/-")
|
|
||||||
.build();
|
|
||||||
|
|
||||||
Ye2Tool.applyResolvedShareKey(info, "iaKtVv-r4aCd");
|
|
||||||
|
|
||||||
assertEquals(original, info.getShareUrl());
|
|
||||||
assertEquals("https://www.123pan.com/s/iaKtVv-r4aCd", info.getStandardUrl());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void anonymousV2LoginCodeUsesExistingLoginHint() {
|
|
||||||
JsonObject json = new JsonObject()
|
|
||||||
.put("code", 5112)
|
|
||||||
.put("message", "您需要注册登录或付费后下载");
|
|
||||||
|
|
||||||
String msg = Ye2Tool.shareV2FailureMessage(json, "nologin");
|
|
||||||
|
|
||||||
assertTrue(msg.contains("auths.ye.authorization"));
|
|
||||||
assertTrue(msg.contains("上游信息: 您需要注册登录或付费后下载"));
|
|
||||||
assertFalse(msg.contains("downURLJson"));
|
|
||||||
assertFalse(msg.contains("download_info"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void loggedInV2TrafficShortageStaysOnV2Error() {
|
|
||||||
JsonObject json = new JsonObject()
|
|
||||||
.put("code", 5113)
|
|
||||||
.put("message", "分享方提取流量包不足");
|
|
||||||
|
|
||||||
String msg = Ye2Tool.shareV2FailureMessage(json, "configured-token");
|
|
||||||
|
|
||||||
assertTrue(msg.startsWith("v2接口返回异常:"));
|
|
||||||
assertTrue(msg.contains("5113"));
|
|
||||||
assertTrue(msg.contains("分享方提取流量包不足"));
|
|
||||||
assertFalse(msg.contains("downURLJson"));
|
|
||||||
assertFalse(msg.contains("download_info"));
|
|
||||||
assertFalse(msg.contains("auths.ye.authorization"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void oldClientErrorIsNotRewrittenAsPersonalFileApiFailure() {
|
|
||||||
JsonObject json = new JsonObject()
|
|
||||||
.put("code", 5066)
|
|
||||||
.put("message", "该文件暂不支持在当前版本下载");
|
|
||||||
|
|
||||||
String msg = Ye2Tool.shareV2FailureMessage(json, "configured-token");
|
|
||||||
|
|
||||||
assertTrue(msg.startsWith("v2接口返回异常:"));
|
|
||||||
assertTrue(msg.contains("5066"));
|
|
||||||
assertFalse(msg.contains("downURLJson"));
|
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(5066, "该文件暂不支持在当前版本下载"));
|
|
||||||
assertFalse(Ye2Tool.isYeLoginRequired(5113, "分享方提取流量包不足"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void signatureUsesActualSharePathPlatformAndVersion() {
|
|
||||||
long time = 1_700_000_000_000L;
|
|
||||||
long randomA = 42L;
|
|
||||||
String traffic = Ye2Tool.signMaterial(
|
|
||||||
Ye2Tool.SHARE_TRAFFIC_CHECK_PATH, Ye2Tool.SHARE_PLATFORM, Ye2Tool.SHARE_WEB_APP_VERSION, time, randomA);
|
|
||||||
String download = Ye2Tool.signMaterial(
|
|
||||||
Ye2Tool.SHARE_DOWNLOAD_INFO_PATH, Ye2Tool.SHARE_PLATFORM, Ye2Tool.SHARE_WEB_APP_VERSION, time, randomA);
|
|
||||||
|
|
||||||
assertTrue(traffic.contains("|/api/share/download/traffic/check|web|149|"));
|
|
||||||
assertTrue(download.contains("|/api/v2/share/download/info|web|149|"));
|
|
||||||
assertFalse(traffic.contains("/b/api/"));
|
|
||||||
assertFalse(download.contains("/b/api/"));
|
|
||||||
assertEquals(Ye2Tool.signQuery(
|
|
||||||
Ye2Tool.SHARE_DOWNLOAD_INFO_PATH, "web", "149", time, randomA),
|
|
||||||
Ye2Tool.signQuery(Ye2Tool.SHARE_DOWNLOAD_INFO_PATH, Ye2Tool.SHARE_PLATFORM,
|
|
||||||
Ye2Tool.SHARE_WEB_APP_VERSION, time, randomA));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void mshareAndPlainSharePageUseDecodedShareHost() {
|
|
||||||
String host = "https://1815268665.share.123pan.cn";
|
|
||||||
assertEquals(host, Ye2Tool.shareApiOrigin(
|
|
||||||
"https://1815268665.mshare.123pan.cn/123pan/iaKtVv-r4aCd",
|
|
||||||
"https://www.123pan.com/s/iaKtVv-r4aCd",
|
|
||||||
"iaKtVv-r4aCd"));
|
|
||||||
assertEquals(host, Ye2Tool.shareApiOrigin(
|
|
||||||
"https://1815268665.share.123pan.cn/123pan/iaKtVv-r4aCd?notoken=1",
|
|
||||||
null,
|
|
||||||
"iaKtVv-r4aCd"));
|
|
||||||
assertEquals(host, Ye2Tool.shareApiOrigin(
|
|
||||||
"https://www.123pan.com/s/iaKtVv-r4aCd",
|
|
||||||
"https://yun.123pan.com/s/iaKtVv-r4aCd",
|
|
||||||
"iaKtVv-r4aCd"));
|
|
||||||
assertFalse(host.contains("mshare"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void maliciousHostIsNotCalled() {
|
|
||||||
AtomicInteger calls = new AtomicInteger();
|
|
||||||
Future<String> blocked = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
return Future.succeededFuture(new JsonObject().put("code", 0));
|
|
||||||
}, sampleRequest("http://127.0.0.1/latest/meta-data", "iaKtVv-r4aCd", "configured-token"));
|
|
||||||
Future<String> disguised = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
return Future.succeededFuture(new JsonObject().put("code", 0));
|
|
||||||
}, sampleRequest("https://1815268665.share.123pan.cn.evil.com/123pan/iaKtVv-r4aCd",
|
|
||||||
"iaKtVv-r4aCd", "configured-token"));
|
|
||||||
Future<String> unknownKey = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
return Future.succeededFuture(new JsonObject().put("code", 0));
|
|
||||||
}, sampleRequest("https://evil.example/123pan/not-a-real-key", "not-a-real-key", "configured-token"));
|
|
||||||
|
|
||||||
assertEquals(0, calls.get());
|
|
||||||
assertTrue(blocked.failed());
|
|
||||||
assertTrue(disguised.failed());
|
|
||||||
assertTrue(unknownKey.failed());
|
|
||||||
assertTrue(blocked.cause().getMessage().contains("分享域名"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void successChecksTrafficThenDownloadsOnShareHost() {
|
|
||||||
List<Ye2Tool.ShareHttpCall> seen = new ArrayList<>();
|
|
||||||
Future<String> result = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
seen.add(call);
|
|
||||||
if (seen.size() == 1) {
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject()
|
|
||||||
.put("isBlocked", false)
|
|
||||||
.put("isTrafficExceeded", false)
|
|
||||||
.put("isPay", false)));
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject()
|
|
||||||
.put("downloadPath", "/123/file.zip")
|
|
||||||
.put("dispatchList", new JsonArray()
|
|
||||||
.add(new JsonObject().put("prefix", "https://cdn-a.example/"))
|
|
||||||
.add(new JsonObject().put("prefix", "https://cdn-b.example/")))));
|
|
||||||
}, sampleRequest("https://1815268665.mshare.123pan.cn/123pan/iaKtVv-r4aCd",
|
|
||||||
"iaKtVv-r4aCd", "configured-token"));
|
|
||||||
|
|
||||||
assertTrue(result.succeeded());
|
|
||||||
assertEquals("https://cdn-a.example/123/file.zip", result.result());
|
|
||||||
assertEquals(2, seen.size());
|
|
||||||
|
|
||||||
Ye2Tool.ShareHttpCall traffic = seen.get(0);
|
|
||||||
Ye2Tool.ShareHttpCall download = seen.get(1);
|
|
||||||
assertEquals("https://1815268665.share.123pan.cn", traffic.origin);
|
|
||||||
assertEquals(Ye2Tool.SHARE_TRAFFIC_CHECK_PATH, traffic.path);
|
|
||||||
assertEquals(Ye2Tool.SHARE_DOWNLOAD_INFO_PATH, download.path);
|
|
||||||
assertEquals(traffic.origin, download.origin);
|
|
||||||
assertFalse(traffic.url().contains("api.123278.com"));
|
|
||||||
assertFalse(traffic.url().contains("/b/api/"));
|
|
||||||
assertEquals(Ye2Tool.signQuery(traffic.path, "web", "149", 1_700_000_000_000L, 42L), traffic.query);
|
|
||||||
assertEquals(Ye2Tool.signQuery(download.path, "web", "149", 1_700_000_000_000L, 42L), download.query);
|
|
||||||
|
|
||||||
assertEquals("149", traffic.headers.get("App-Version"));
|
|
||||||
assertEquals("web", traffic.headers.get("platform"));
|
|
||||||
assertEquals("Bearer configured-token", traffic.headers.get("Authorization"));
|
|
||||||
assertEquals("application/json;charset=UTF-8", traffic.headers.get("Content-Type"));
|
|
||||||
assertEquals("https://1815268665.share.123pan.cn", traffic.headers.get("Origin"));
|
|
||||||
assertEquals("https://1815268665.share.123pan.cn/123pan/iaKtVv-r4aCd", traffic.headers.get("Referer"));
|
|
||||||
assertEquals("iaKtVv-r4aCd", traffic.body.getString("shareKey"));
|
|
||||||
assertEquals(Long.valueOf(2468L), traffic.body.getJsonArray("fileIds").getLong(0));
|
|
||||||
assertFalse(traffic.body.containsKey("payType"));
|
|
||||||
|
|
||||||
assertEquals("iaKtVv-r4aCd", download.body.getString("ShareKey"));
|
|
||||||
assertEquals(Long.valueOf(2468L), download.body.getLong("FileID"));
|
|
||||||
assertEquals("etag-flag", download.body.getString("S3keyFlag"));
|
|
||||||
assertEquals(Long.valueOf(6915371L), download.body.getLong("Size"));
|
|
||||||
assertEquals("abcetag", download.body.getString("Etag"));
|
|
||||||
assertFalse(download.body.containsKey("OrderId"));
|
|
||||||
assertFalse(download.body.containsKey("payType"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void directoryDownloadUsesShareKeyHostNotPlaceholderPage() {
|
|
||||||
List<Ye2Tool.ShareHttpCall> seen = new ArrayList<>();
|
|
||||||
Ye2Tool.ShareFileRequest request = sampleRequest(
|
|
||||||
"https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "configured-token");
|
|
||||||
Future<String> result = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
seen.add(call);
|
|
||||||
if (seen.size() == 1) {
|
|
||||||
return Future.succeededFuture(openTraffic());
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject()
|
|
||||||
.put("downloadPath", "folder/file.bin")
|
|
||||||
.put("dispatchList", new JsonArray().add(
|
|
||||||
new JsonObject().put("prefix", "https://cdn.example/root")))));
|
|
||||||
}, request);
|
|
||||||
|
|
||||||
assertTrue(result.succeeded());
|
|
||||||
assertEquals("https://cdn.example/root/folder/file.bin", result.result());
|
|
||||||
assertEquals("https://1815268665.share.123pan.cn", seen.get(0).origin);
|
|
||||||
assertFalse(seen.get(0).url().contains("www.123pan.com"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void absoluteDownloadPathIsKept() {
|
|
||||||
Future<String> result = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
if (call.path.equals(Ye2Tool.SHARE_TRAFFIC_CHECK_PATH)) {
|
|
||||||
return Future.succeededFuture(openTraffic());
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject()
|
|
||||||
.put("downloadPath", "https://cdn.example/already.zip")
|
|
||||||
.put("dispatchList", new JsonArray().add(
|
|
||||||
new JsonObject().put("prefix", "https://ignored.example/")))));
|
|
||||||
}, sampleRequest("https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "configured-token"));
|
|
||||||
|
|
||||||
assertEquals("https://cdn.example/already.zip", result.result());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void blockedPayAndMissingLinkDoNotContinue() {
|
|
||||||
Future<String> blocked = downloadAfterTraffic(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject().put("isBlocked", true).put("isPay", false)));
|
|
||||||
Future<String> pay = downloadAfterTraffic(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject().put("isPay", true)));
|
|
||||||
Future<String> missing = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
if (call.path.equals(Ye2Tool.SHARE_TRAFFIC_CHECK_PATH)) {
|
|
||||||
return Future.succeededFuture(openTraffic());
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(new JsonObject().put("code", 0).put("data", new JsonObject()));
|
|
||||||
}, sampleRequest("https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "configured-token"));
|
|
||||||
|
|
||||||
Future<String> exceeded = downloadAfterTraffic(new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject().put("isTrafficExceeded", true)));
|
|
||||||
|
|
||||||
assertTrue(blocked.cause().getMessage().contains("不会自动下单"));
|
|
||||||
assertTrue(pay.cause().getMessage().contains("不会自动下单"));
|
|
||||||
assertTrue(exceeded.cause().getMessage().contains("不会自动购买"));
|
|
||||||
assertTrue(missing.cause().getMessage().contains("未返回下载链接"));
|
|
||||||
assertFalse(blocked.cause().getMessage().contains("OrderId"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void loginAndTrafficErrorsStayOnTheStepThatReturnedThem() {
|
|
||||||
AtomicInteger calls = new AtomicInteger();
|
|
||||||
Future<String> login = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 5112)
|
|
||||||
.put("message", "您需要注册登录或付费后下载"));
|
|
||||||
}, sampleRequest("https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "nologin"));
|
|
||||||
Future<String> traffic = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
if (call.path.equals(Ye2Tool.SHARE_TRAFFIC_CHECK_PATH)) {
|
|
||||||
assertNull(call.headers.get("Authorization"));
|
|
||||||
return Future.succeededFuture(openTraffic());
|
|
||||||
}
|
|
||||||
return Future.succeededFuture(new JsonObject()
|
|
||||||
.put("code", 5113)
|
|
||||||
.put("message", "分享方提取流量包不足"));
|
|
||||||
}, sampleRequest("https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "nologin"));
|
|
||||||
|
|
||||||
assertEquals(3, calls.get());
|
|
||||||
assertTrue(login.cause().getMessage().contains("auths.ye.authorization"));
|
|
||||||
assertTrue(traffic.cause().getMessage().contains("5113"));
|
|
||||||
assertFalse(traffic.cause().getMessage().contains("downURLJson"));
|
|
||||||
assertFalse(traffic.cause().getMessage().contains("download_info"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Future<String> downloadAfterTraffic(JsonObject trafficJson) {
|
|
||||||
AtomicInteger calls = new AtomicInteger();
|
|
||||||
Future<String> result = Ye2Tool.executeShareFileDownload(call -> {
|
|
||||||
calls.incrementAndGet();
|
|
||||||
return Future.succeededFuture(trafficJson);
|
|
||||||
}, sampleRequest("https://www.123pan.com/s/iaKtVv-r4aCd", "iaKtVv-r4aCd", "configured-token"));
|
|
||||||
assertEquals(1, calls.get());
|
|
||||||
assertTrue(result.failed());
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static JsonObject openTraffic() {
|
|
||||||
return new JsonObject()
|
|
||||||
.put("code", 0)
|
|
||||||
.put("data", new JsonObject()
|
|
||||||
.put("isBlocked", false)
|
|
||||||
.put("isTrafficExceeded", false)
|
|
||||||
.put("isPay", false));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Ye2Tool.ShareFileRequest sampleRequest(String shareUrl, String shareKey, String token) {
|
|
||||||
return new Ye2Tool.ShareFileRequest(
|
|
||||||
shareUrl,
|
|
||||||
"https://www.123pan.com/s/" + shareKey,
|
|
||||||
shareKey,
|
|
||||||
"",
|
|
||||||
2468L,
|
|
||||||
"etag-flag",
|
|
||||||
6915371L,
|
|
||||||
"abcetag",
|
|
||||||
token,
|
|
||||||
1_700_000_000_000L,
|
|
||||||
42L);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
package cn.qaiu.util;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertNull;
|
|
||||||
|
|
||||||
public class ShareUrlParamsTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void cleanShareKeyStripsQueryAndHash() {
|
|
||||||
assertEquals("SjfEaY2z", ShareUrlParams.cleanShareKey("SjfEaY2z?code=064d"));
|
|
||||||
assertEquals("lN7UVv-pbYJ", ShareUrlParams.cleanShareKey("lN7UVv-pbYJ?pwd=abcd#/list"));
|
|
||||||
assertEquals("iabc", ShareUrlParams.cleanShareKey("iabc?webpage=wp1&pwd=secret"));
|
|
||||||
assertEquals("s/someShareKey", ShareUrlParams.cleanShareKey("s/someShareKey"));
|
|
||||||
assertEquals("key", ShareUrlParams.cleanShareKey("key"));
|
|
||||||
assertNull(ShareUrlParams.cleanShareKey(null));
|
|
||||||
assertEquals("", ShareUrlParams.cleanShareKey(""));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void extractPasswordFromCommonQueryNames() {
|
|
||||||
assertEquals("064d", ShareUrlParams.extractSharePassword("https://share.feijipan.com/s/SjfEaY2z?code=064d"));
|
|
||||||
assertEquals("Pbdl", ShareUrlParams.extractSharePassword("https://www.123684.com/s/6gXfvd-7H9kh?pwd=Pbdl#/list"));
|
|
||||||
assertEquals("secret", ShareUrlParams.extractSharePassword(
|
|
||||||
"https://a.lanzouw.com/iabc?webpage=wp1&pwd=secret"));
|
|
||||||
assertEquals("I4KG7H", ShareUrlParams.extractSharePassword(
|
|
||||||
"https://www.vyuyun.com/s/QMa6ie?password=I4KG7H"));
|
|
||||||
assertEquals("测码", ShareUrlParams.extractSharePassword("https://example.com/s/k?pwd=%E6%B5%8B%E7%A0%81"));
|
|
||||||
assertNull(ShareUrlParams.extractSharePassword("https://drive.uc.cn/s/abc?public=1#/list/share"));
|
|
||||||
assertNull(ShareUrlParams.extractSharePassword("https://www.123pan.com/s/abc"));
|
|
||||||
assertNull(ShareUrlParams.extractSharePassword("https://www.123pan.com/s/abc?pwd="));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void prefersPwdOverCode() {
|
|
||||||
assertEquals("fromPwd", ShareUrlParams.extractSharePassword(
|
|
||||||
"https://example.com/s/k?code=fromCode&pwd=fromPwd"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<revision>0.4.13</revision>
|
<revision>0.4.12</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>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "nfd-web",
|
"name": "nfd-web",
|
||||||
"version": "0.4.13",
|
"version": "0.4.12",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"serve": "vue-cli-service serve",
|
"serve": "vue-cli-service serve",
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
"build": "node scripts/sync-version.js && vue-cli-service build && node scripts/compress-vs.js",
|
"build": "node scripts/sync-version.js && vue-cli-service build && node scripts/compress-vs.js",
|
||||||
"build:no-compress": "node scripts/sync-version.js && vue-cli-service build",
|
"build:no-compress": "node scripts/sync-version.js && vue-cli-service build",
|
||||||
"lint": "vue-cli-service lint",
|
"lint": "vue-cli-service lint",
|
||||||
"test": "node --test src/utils/batchTreeCollect.spec.js src/utils/folderPaging.spec.js src/utils/nameFilter.spec.js"
|
"test": "node --test src/utils/batchTreeCollect.spec.js src/utils/folderPaging.spec.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@element-plus/icons-vue": "^2.3.1",
|
"@element-plus/icons-vue": "^2.3.1",
|
||||||
|
|||||||
+26
-147
@@ -315,73 +315,6 @@
|
|||||||
opacity: .6;
|
opacity: .6;
|
||||||
cursor: default;
|
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>
|
||||||
@@ -396,14 +329,6 @@
|
|||||||
<!-- 面包屑导航会通过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动态生成 -->
|
||||||
@@ -513,9 +438,6 @@
|
|||||||
let seenKeys = new Set();
|
let seenKeys = new Set();
|
||||||
let folderCount = 0;
|
let folderCount = 0;
|
||||||
let fileCount = 0;
|
let fileCount = 0;
|
||||||
// 已加载的完整列表。筛选只看这里,规则与 src/utils/nameFilter.js 一致。
|
|
||||||
let loadedFiles = [];
|
|
||||||
let nameFilter = '';
|
|
||||||
const moreEl = document.createElement('div');
|
const moreEl = document.createElement('div');
|
||||||
moreEl.className = 'load-more';
|
moreEl.className = 'load-more';
|
||||||
moreEl.style.display = 'none';
|
moreEl.style.display = 'none';
|
||||||
@@ -549,18 +471,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function fileKey(file) {
|
function fileKey(file) {
|
||||||
return `${file.parserUrl || ''}::${file.fileName || ''}::${file.fileId || file.id || ''}`;
|
return `${file.parserUrl || ''}::${file.fileName || ''}::${file.fileId || ''}`;
|
||||||
}
|
|
||||||
|
|
||||||
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() {
|
function renderMore() {
|
||||||
@@ -609,8 +520,7 @@
|
|||||||
|
|
||||||
if (typeof IntersectionObserver !== 'undefined') {
|
if (typeof IntersectionObserver !== 'undefined') {
|
||||||
new IntersectionObserver(entries => {
|
new IntersectionObserver(entries => {
|
||||||
// 有关键字时不自动翻页,避免筛选结果变短后把后续页一次拉完
|
if (more && !more.loading && !more.error && entries.some(e => e.isIntersecting)) loadMore();
|
||||||
if (more && !more.loading && !more.error && !normalizeQuery(nameFilter) && entries.some(e => e.isIntersecting)) loadMore();
|
|
||||||
}).observe(moreEl);
|
}).observe(moreEl);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -624,13 +534,6 @@
|
|||||||
// 初始化
|
// 初始化
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
fileGridEl.insertAdjacentElement('afterend', moreEl);
|
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);
|
||||||
|
|
||||||
@@ -702,50 +605,37 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateFilterHint(matchedCount) {
|
// 渲染文件列表
|
||||||
const hint = document.getElementById('filter-hint');
|
function renderFileList(files, append = false) {
|
||||||
if (!hint) return;
|
if (!append) {
|
||||||
const query = normalizeQuery(nameFilter);
|
fileGridEl.innerHTML = '';
|
||||||
if (!query) {
|
seenKeys = new Set();
|
||||||
hint.hidden = true;
|
folderCount = 0;
|
||||||
hint.textContent = '';
|
fileCount = 0;
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
hint.hidden = false;
|
|
||||||
hint.textContent = `仅筛选已加载的 ${loadedFiles.length} 项,匹配 ${matchedCount} 项`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 按当前关键字重绘已加载列表。加载更多按钮在网格外面,无匹配时仍然在。
|
if (!append && (!files || files.length === 0)) {
|
||||||
function renderLoadedFiles() {
|
fileGridEl.innerHTML = `
|
||||||
const visible = filterByFileName(loadedFiles, nameFilter);
|
<div class="empty-state">
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
visible.forEach(file => {
|
(files || []).forEach(file => {
|
||||||
|
const key = fileKey(file);
|
||||||
|
if (seenKeys.has(key)) return;
|
||||||
|
seenKeys.add(key);
|
||||||
const item = document.createElement('div');
|
const item = document.createElement('div');
|
||||||
const metaText = fileMetaText(file);
|
const metaText = fileMetaText(file);
|
||||||
|
|
||||||
if (file.fileType === 'folder') {
|
if (file.fileType === 'folder') {
|
||||||
|
// 文件夹
|
||||||
item.className = 'item folder';
|
item.className = 'item folder';
|
||||||
item.innerHTML = `
|
item.innerHTML = `
|
||||||
<div class="item-icon">
|
<div class="item-icon">
|
||||||
@@ -755,12 +645,16 @@
|
|||||||
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
|
||||||
`;
|
`;
|
||||||
folderCount++;
|
folderCount++;
|
||||||
|
|
||||||
|
// 添加点击事件
|
||||||
item.addEventListener('click', () => {
|
item.addEventListener('click', () => {
|
||||||
enterFolder(file);
|
enterFolder(file);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
|
// 文件
|
||||||
const fileExt = getFileExtension(file.fileName);
|
const fileExt = getFileExtension(file.fileName);
|
||||||
const fileTypeInfo = fileTypeIcons[fileExt.toLowerCase()] || fileTypeIcons['default'];
|
const fileTypeInfo = fileTypeIcons[fileExt.toLowerCase()] || fileTypeIcons['default'];
|
||||||
|
|
||||||
item.className = `item ${fileTypeInfo.type}`;
|
item.className = `item ${fileTypeInfo.type}`;
|
||||||
item.innerHTML = `
|
item.innerHTML = `
|
||||||
<div class="item-icon">
|
<div class="item-icon">
|
||||||
@@ -770,6 +664,8 @@
|
|||||||
${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);
|
||||||
});
|
});
|
||||||
@@ -778,26 +674,9 @@
|
|||||||
fileGridEl.appendChild(item);
|
fileGridEl.appendChild(item);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 更新统计信息
|
||||||
folderCountEl.textContent = folderCount;
|
folderCountEl.textContent = folderCount;
|
||||||
fileCountEl.textContent = fileCount;
|
fileCountEl.textContent = fileCount;
|
||||||
updateFilterHint(visible.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 渲染文件列表
|
|
||||||
function renderFileList(files, append = false) {
|
|
||||||
if (!append) {
|
|
||||||
seenKeys = new Set();
|
|
||||||
loadedFiles = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
(files || []).forEach(file => {
|
|
||||||
const key = fileKey(file);
|
|
||||||
if (seenKeys.has(key)) return;
|
|
||||||
seenKeys.add(key);
|
|
||||||
loadedFiles.push(file);
|
|
||||||
});
|
|
||||||
|
|
||||||
renderLoadedFiles();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取文件扩展名
|
// 获取文件扩展名
|
||||||
|
|||||||
@@ -1,20 +1,6 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="main-container">
|
<div class="main-container">
|
||||||
<div class="directory-tree" :class="{ 'dark-theme': isDarkTheme }">
|
<div class="directory-tree" :class="{ 'dark-theme': isDarkTheme }">
|
||||||
<div class="dir-filter-bar">
|
|
||||||
<el-input
|
|
||||||
v-model="nameFilter"
|
|
||||||
class="dir-name-filter"
|
|
||||||
clearable
|
|
||||||
placeholder="按文件名筛选"
|
|
||||||
aria-label="按文件名筛选"
|
|
||||||
>
|
|
||||||
<template #prefix>
|
|
||||||
<i class="fas fa-search" aria-hidden="true"></i>
|
|
||||||
</template>
|
|
||||||
</el-input>
|
|
||||||
<p v-if="nameQuery" class="dir-filter-hint">仅筛选已加载的 {{ loadedCount }} 项,匹配 {{ matchedCount }} 项</p>
|
|
||||||
</div>
|
|
||||||
<template v-if="viewMode === 'pane'">
|
<template v-if="viewMode === 'pane'">
|
||||||
<!-- 窗格模式(原有) -->
|
<!-- 窗格模式(原有) -->
|
||||||
<div class="breadcrumb">
|
<div class="breadcrumb">
|
||||||
@@ -32,7 +18,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="file-grid" v-loading="loading">
|
<div class="file-grid" v-loading="loading">
|
||||||
<div
|
<div
|
||||||
v-for="file in visibleFileList"
|
v-for="file in currentFileList"
|
||||||
:key="fileKey(file)"
|
:key="fileKey(file)"
|
||||||
class="file-item"
|
class="file-item"
|
||||||
:class="[getFileTypeClass(file), { 'selected': batchMode && isFileSelected(file) }]"
|
:class="[getFileTypeClass(file), { 'selected': batchMode && isFileSelected(file) }]"
|
||||||
@@ -50,10 +36,10 @@
|
|||||||
{{ fileMetaText(file) }}
|
{{ fileMetaText(file) }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!loading && visibleFileList.length === 0" class="empty-state">
|
<div v-if="!loading && (!currentFileList || currentFileList.length === 0)" class="empty-state">
|
||||||
<i class="fas" :class="nameQuery && currentFileList.length ? 'fa-search' : 'fa-folder-open'"></i>
|
<i class="fas fa-folder-open"></i>
|
||||||
<h3>{{ nameQuery && currentFileList.length ? '没有匹配的文件' : '此文件夹为空' }}</h3>
|
<h3>此文件夹为空</h3>
|
||||||
<p>{{ nameQuery && currentFileList.length ? '换个关键字,或加载更多后再筛' : '暂无文件或文件夹' }}</p>
|
<p>暂无文件或文件夹</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="paneMore" ref="loadMoreBar" class="load-more-bar">
|
<div v-if="paneMore" ref="loadMoreBar" class="load-more-bar">
|
||||||
@@ -140,11 +126,6 @@
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
||||||
<div v-if="treeFilterEmpty" class="empty-state tree-filter-empty">
|
|
||||||
<i class="fas fa-search"></i>
|
|
||||||
<h3>没有匹配的文件</h3>
|
|
||||||
<p>换个关键字,或加载更多后再筛</p>
|
|
||||||
</div>
|
|
||||||
<el-tree
|
<el-tree
|
||||||
ref="fileTree"
|
ref="fileTree"
|
||||||
:data="treeData"
|
:data="treeData"
|
||||||
@@ -155,20 +136,16 @@
|
|||||||
:highlight-current="!batchMode"
|
:highlight-current="!batchMode"
|
||||||
:show-checkbox="batchMode"
|
:show-checkbox="batchMode"
|
||||||
:check-strictly="false"
|
:check-strictly="false"
|
||||||
:filter-node-method="filterTreeNode"
|
|
||||||
@node-click="onNodeClick"
|
@node-click="onNodeClick"
|
||||||
@check="onTreeCheck"
|
@check="onTreeCheck"
|
||||||
@check-change="onTreeCheckChange"
|
@check-change="onTreeCheckChange"
|
||||||
:default-expand-all="false"
|
:default-expand-all="false"
|
||||||
|
:default-expanded-keys="['root']"
|
||||||
:render-content="renderContent"
|
:render-content="renderContent"
|
||||||
style="background:transparent;"
|
style="background:transparent;"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="batchMode" class="tree-sidebar-footer">
|
<div v-if="batchMode" class="tree-sidebar-footer">
|
||||||
<div class="tree-select-row">
|
|
||||||
<el-button size="small" @click="selectAll">全选</el-button>
|
|
||||||
<el-button size="small" @click="deselectAll">取消全选</el-button>
|
|
||||||
</div>
|
|
||||||
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
||||||
<div class="tree-sidebar-actions">
|
<div class="tree-sidebar-actions">
|
||||||
<el-button
|
<el-button
|
||||||
@@ -299,11 +276,6 @@
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
<div class="tree-scroll-wrap" v-loading="treeExpanding">
|
||||||
<div v-if="treeFilterEmpty" class="empty-state tree-filter-empty">
|
|
||||||
<i class="fas fa-search"></i>
|
|
||||||
<h3>没有匹配的文件</h3>
|
|
||||||
<p>换个关键字,或加载更多后再筛</p>
|
|
||||||
</div>
|
|
||||||
<el-tree
|
<el-tree
|
||||||
ref="fileTree"
|
ref="fileTree"
|
||||||
:data="treeData"
|
:data="treeData"
|
||||||
@@ -314,11 +286,11 @@
|
|||||||
:highlight-current="!batchMode"
|
:highlight-current="!batchMode"
|
||||||
:show-checkbox="batchMode"
|
:show-checkbox="batchMode"
|
||||||
:check-strictly="false"
|
:check-strictly="false"
|
||||||
:filter-node-method="filterTreeNode"
|
|
||||||
@node-click="onNodeClick"
|
@node-click="onNodeClick"
|
||||||
@check="onTreeCheck"
|
@check="onTreeCheck"
|
||||||
@check-change="onTreeCheckChange"
|
@check-change="onTreeCheckChange"
|
||||||
:default-expand-all="false"
|
:default-expand-all="false"
|
||||||
|
:default-expanded-keys="['root']"
|
||||||
:render-content="renderContent"
|
:render-content="renderContent"
|
||||||
style="background:transparent;"
|
style="background:transparent;"
|
||||||
/>
|
/>
|
||||||
@@ -394,10 +366,6 @@
|
|||||||
</el-button>
|
</el-button>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="batchMode" class="mobile-batch-footer">
|
<div v-if="batchMode" class="mobile-batch-footer">
|
||||||
<div class="tree-select-row">
|
|
||||||
<el-button size="small" @click="selectAll">全选</el-button>
|
|
||||||
<el-button size="small" @click="deselectAll">取消全选</el-button>
|
|
||||||
</div>
|
|
||||||
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
<span class="tree-sidebar-count">已勾选 {{ selectedFiles.length }} 个文件</span>
|
||||||
<div class="tree-sidebar-actions">
|
<div class="tree-sidebar-actions">
|
||||||
<el-button type="primary" size="small" :disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding || batchBrowserDownloadDisabled" :loading="batchDownloading" @click="batchBrowserDownload" :title="batchBrowserDownloadDisabled ? '所选文件需使用下载器下载' : ''">浏览器下载</el-button>
|
<el-button type="primary" size="small" :disabled="selectedFiles.length === 0 || batchDownloading || treeExpanding || batchBrowserDownloadDisabled" :loading="batchDownloading" @click="batchBrowserDownload" :title="batchBrowserDownloadDisabled ? '所选文件需使用下载器下载' : ''">浏览器下载</el-button>
|
||||||
@@ -494,26 +462,16 @@ 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 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 { toPageUrl, readPage, appendUnique, nextState, makeMoreNode, isMoreNode } = folderPaging
|
||||||
const {
|
|
||||||
matchesFileName,
|
|
||||||
filterByFileName,
|
|
||||||
filterSummary,
|
|
||||||
selectMatching,
|
|
||||||
deselectMatching,
|
|
||||||
collectLoadedNodes
|
|
||||||
} = nameFilter
|
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'DirectoryTree',
|
name: 'DirectoryTree',
|
||||||
@@ -556,9 +514,6 @@ export default {
|
|||||||
loading: false,
|
loading: false,
|
||||||
pathStack: [{ name: '全部文件', url: '' }],
|
pathStack: [{ name: '全部文件', url: '' }],
|
||||||
currentFileList: [],
|
currentFileList: [],
|
||||||
nameFilter: '',
|
|
||||||
rootLoadedFiles: [],
|
|
||||||
treeLoadVersion: 0,
|
|
||||||
// 当前窗格目录的下一页状态;null 表示已全部加载
|
// 当前窗格目录的下一页状态;null 表示已全部加载
|
||||||
paneMore: null,
|
paneMore: null,
|
||||||
rootMore: null,
|
rootMore: null,
|
||||||
@@ -594,26 +549,11 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
nameQuery() {
|
|
||||||
return String(this.nameFilter || '').trim()
|
|
||||||
},
|
|
||||||
visibleFileList() {
|
|
||||||
return filterByFileName(this.currentFileList, this.nameFilter)
|
|
||||||
},
|
|
||||||
loadedCount() {
|
|
||||||
return filterSummary(this.entriesForCount(), this.nameFilter).loaded
|
|
||||||
},
|
|
||||||
matchedCount() {
|
|
||||||
return filterSummary(this.entriesForCount(), this.nameFilter).matched
|
|
||||||
},
|
|
||||||
treeFilterEmpty() {
|
|
||||||
return this.viewMode === 'tree' && !!this.nameQuery && this.matchedCount === 0 && this.loadedCount > 0
|
|
||||||
},
|
|
||||||
folderCount() {
|
folderCount() {
|
||||||
return this.visibleFileList.filter(file => file.fileType === 'folder').length
|
return this.currentFileList.filter(file => file.fileType === 'folder').length
|
||||||
},
|
},
|
||||||
fileCount() {
|
fileCount() {
|
||||||
return this.visibleFileList.filter(file => file.fileType !== 'folder').length
|
return this.currentFileList.filter(file => file.fileType !== 'folder').length
|
||||||
},
|
},
|
||||||
batchProgressPercent() {
|
batchProgressPercent() {
|
||||||
if (this.batchProgress.total === 0) return 0
|
if (this.batchProgress.total === 0) return 0
|
||||||
@@ -651,15 +591,8 @@ export default {
|
|||||||
paneMore() {
|
paneMore() {
|
||||||
this.$nextTick(() => this.observeLoadMore())
|
this.$nextTick(() => this.observeLoadMore())
|
||||||
},
|
},
|
||||||
viewMode(next, prev) {
|
viewMode() {
|
||||||
if (prev === 'tree' && next !== 'tree') this.snapshotTreeRoot()
|
this.$nextTick(() => this.observeLoadMore())
|
||||||
this.$nextTick(() => {
|
|
||||||
this.observeLoadMore()
|
|
||||||
if (next === 'tree') this.applyTreeFilter()
|
|
||||||
})
|
|
||||||
},
|
|
||||||
nameFilter() {
|
|
||||||
this.$nextTick(() => this.applyTreeFilter())
|
|
||||||
},
|
},
|
||||||
fileList: {
|
fileList: {
|
||||||
immediate: true,
|
immediate: true,
|
||||||
@@ -667,12 +600,23 @@ export default {
|
|||||||
this.rootExtra = []
|
this.rootExtra = []
|
||||||
this.rootMore = nextState(this.buildApiUrl(), readPage(this.rootPageInfo || []))
|
this.rootMore = nextState(this.buildApiUrl(), readPage(this.rootPageInfo || []))
|
||||||
this.treeMoreFolders = new Set()
|
this.treeMoreFolders = new Set()
|
||||||
this.rootLoadedFiles = (newList || []).slice()
|
const children = (newList || []).map(item => normalizeTreeItem(item))
|
||||||
this.nameFilter = ''
|
if (this.rootMore) {
|
||||||
this.treeLoadVersion += 1
|
children.push(makeMoreNode('root', { ...this.rootMore }))
|
||||||
this.syncTreeDataChildren()
|
this.treeMoreFolders.add('root')
|
||||||
|
}
|
||||||
|
// 根节点children为当前目录下所有文件/文件夹
|
||||||
|
this.treeData = [
|
||||||
|
{
|
||||||
|
id: 'root',
|
||||||
|
fileName: '全部文件',
|
||||||
|
fileType: 'folder',
|
||||||
|
children,
|
||||||
|
isLeaf: false
|
||||||
|
}
|
||||||
|
]
|
||||||
this.pathStack = [{ name: '全部文件', url: '' }]
|
this.pathStack = [{ name: '全部文件', url: '' }]
|
||||||
this.currentFileList = newList || []
|
this.currentFileList = newList
|
||||||
this.paneMore = this.rootMore
|
this.paneMore = this.rootMore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -680,7 +624,6 @@ export default {
|
|||||||
created() {
|
created() {
|
||||||
this.treeMoreFolders = this.treeMoreFolders || new Set()
|
this.treeMoreFolders = this.treeMoreFolders || new Set()
|
||||||
this._paneLoadSeq = 0
|
this._paneLoadSeq = 0
|
||||||
this._syncingChecks = false
|
|
||||||
this.resetTreeCollectState()
|
this.resetTreeCollectState()
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
@@ -710,106 +653,10 @@ export default {
|
|||||||
}
|
}
|
||||||
return this.withAuth(`${baseUrl}?${params.toString()}`)
|
return this.withAuth(`${baseUrl}?${params.toString()}`)
|
||||||
},
|
},
|
||||||
entriesForCount() {
|
|
||||||
// 树节点不是响应式数据,翻页后靠 treeLoadVersion 让「已加载 / 匹配」重新计算
|
|
||||||
void this.treeLoadVersion
|
|
||||||
return this.activeLoadedEntries()
|
|
||||||
},
|
|
||||||
activeLoadedEntries() {
|
|
||||||
if (this.viewMode !== 'tree') return this.currentFileList || []
|
|
||||||
const tree = this.getFileTree()
|
|
||||||
const storeRoot = tree && tree.store ? tree.store.root : null
|
|
||||||
if (storeRoot) return collectLoadedNodes(storeRoot)
|
|
||||||
return this.rootLoadedFiles || []
|
|
||||||
},
|
|
||||||
// 加载更多占位和虚拟根始终留下,否则无匹配时无法继续翻页
|
|
||||||
filterTreeNode(value, data) {
|
|
||||||
if (!data || data.id === 'root') return false
|
|
||||||
if (isMoreNode(data) || !value) return true
|
|
||||||
return matchesFileName(data, value)
|
|
||||||
},
|
|
||||||
displayRootNodes() {
|
|
||||||
const nodes = (this.rootLoadedFiles || []).map(item => normalizeTreeItem(item))
|
|
||||||
if (this.rootMore) nodes.push(makeMoreNode('root', { ...this.rootMore }))
|
|
||||||
return nodes
|
|
||||||
},
|
|
||||||
revealFilter() {
|
|
||||||
const tree = this.getFileTree()
|
|
||||||
if (tree && typeof tree.filter === 'function') tree.filter(this.nameQuery || '')
|
|
||||||
},
|
|
||||||
applyTreeFilter() {
|
|
||||||
this.revealFilter()
|
|
||||||
this.syncChecksFromSelection()
|
|
||||||
},
|
|
||||||
syncTreeDataChildren() {
|
|
||||||
const children = this.displayRootNodes()
|
|
||||||
if (this.rootMore) {
|
|
||||||
if (this.treeMoreFolders) this.treeMoreFolders.add('root')
|
|
||||||
} else if (this.treeMoreFolders) {
|
|
||||||
this.treeMoreFolders.delete('root')
|
|
||||||
}
|
|
||||||
// 树的数据就是当前已加载列表,不包一层「全部文件」,避免懒加载把根节点再插进列表
|
|
||||||
this.treeData = children
|
|
||||||
},
|
|
||||||
snapshotTreeRoot() {
|
|
||||||
const tree = this.getFileTree()
|
|
||||||
const root = tree && tree.store ? tree.store.root : null
|
|
||||||
if (!root) return
|
|
||||||
const files = []
|
|
||||||
let more = null
|
|
||||||
let sawMore = false
|
|
||||||
const pushNode = (child) => {
|
|
||||||
if (!child || !child.data || isMoreNode(child.data)) {
|
|
||||||
if (child && child.data && isMoreNode(child.data)) {
|
|
||||||
sawMore = true
|
|
||||||
more = child.data.paging || null
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (child.data.id === 'root') {
|
|
||||||
for (const grand of child.childNodes || []) pushNode(grand)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
files.push(child.data)
|
|
||||||
}
|
|
||||||
for (const child of root.childNodes || []) pushNode(child)
|
|
||||||
if (files.length || sawMore) {
|
|
||||||
this.rootLoadedFiles = appendUnique([], files)
|
|
||||||
this.rootMore = more
|
|
||||||
}
|
|
||||||
if (this.pathStack.length <= 1) {
|
|
||||||
this.currentFileList = (this.rootLoadedFiles || []).slice()
|
|
||||||
this.paneMore = this.rootMore
|
|
||||||
? { ...this.rootMore, loading: false, error: this.rootMore.error || '' }
|
|
||||||
: null
|
|
||||||
}
|
|
||||||
this.$nextTick(() => {
|
|
||||||
if (this.viewMode !== 'tree') this.syncTreeDataChildren()
|
|
||||||
})
|
|
||||||
},
|
|
||||||
syncChecksFromSelection() {
|
|
||||||
const tree = this.getFileTree()
|
|
||||||
if (!tree || !this.batchMode || typeof tree.setChecked !== 'function') return
|
|
||||||
const root = tree.store ? tree.store.root : null
|
|
||||||
if (!root) return
|
|
||||||
this._syncingChecks = true
|
|
||||||
try {
|
|
||||||
const selectedKeys = new Set(this.selectedFiles.map(fileIdentity))
|
|
||||||
for (const file of collectLoadedNodes(root)) {
|
|
||||||
if (!this.isDownloadableFile(file)) continue
|
|
||||||
if (this.nameQuery && !matchesFileName(file, this.nameQuery)) continue
|
|
||||||
tree.setChecked(getTreeNodeId(file), selectedKeys.has(fileIdentity(file)), false)
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
this._syncingChecks = false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
// 懒加载子节点(批量勾选文件夹时会通过 node.expand → store.load 复用此方法)
|
// 懒加载子节点(批量勾选文件夹时会通过 node.expand → store.load 复用此方法)
|
||||||
loadNode(node, resolve) {
|
loadNode(node, resolve) {
|
||||||
if (node.level === 0) {
|
if (node.level === 0) {
|
||||||
resolve(this.displayRootNodes())
|
resolve((this.treeData[0]?.children || []).map(item => normalizeTreeItem(item)))
|
||||||
this.treeLoadVersion += 1
|
|
||||||
this.$nextTick(() => this.revealFilter())
|
|
||||||
} else if (node.data.fileType === 'folder' && node.data.parserUrl) {
|
} else if (node.data.fileType === 'folder' && node.data.parserUrl) {
|
||||||
const listUrl = this.withAuth(node.data.parserUrl)
|
const listUrl = this.withAuth(node.data.parserUrl)
|
||||||
const pageUrl = toPageUrl(listUrl, 1)
|
const pageUrl = toPageUrl(listUrl, 1)
|
||||||
@@ -826,8 +673,6 @@ export default {
|
|||||||
this.treeMoreFolders.delete(folderKey)
|
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([])
|
||||||
@@ -857,8 +702,7 @@ export default {
|
|||||||
if (!this._moreObserver) {
|
if (!this._moreObserver) {
|
||||||
this._moreObserver = new IntersectionObserver((entries) => {
|
this._moreObserver = new IntersectionObserver((entries) => {
|
||||||
const state = this.paneMore
|
const state = this.paneMore
|
||||||
// 有关键字时列表变短,哨兵会露出来;这时不自动翻页,避免把未加载页一次拉完
|
if (!state || state.loading || state.error || this.viewMode !== 'pane') return
|
||||||
if (!state || state.loading || state.error || this.viewMode !== 'pane' || this.nameQuery) return
|
|
||||||
if (entries.some(e => e.isIntersecting)) this.loadMorePane()
|
if (entries.some(e => e.isIntersecting)) this.loadMorePane()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -891,11 +735,8 @@ export default {
|
|||||||
if (this.pathStack.length === 1) {
|
if (this.pathStack.length === 1) {
|
||||||
this.rootExtra = appendUnique(this.rootExtra, added)
|
this.rootExtra = appendUnique(this.rootExtra, added)
|
||||||
this.rootMore = next
|
this.rootMore = next
|
||||||
this.rootLoadedFiles = appendUnique(this.rootLoadedFiles, added)
|
|
||||||
if (this.viewMode !== 'tree') this.syncTreeDataChildren()
|
|
||||||
}
|
}
|
||||||
this.paneMore = next
|
this.paneMore = next
|
||||||
this.treeLoadVersion += 1
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (seq !== this._paneLoadSeq || this.paneMore !== state) return
|
if (seq !== this._paneLoadSeq || this.paneMore !== state) return
|
||||||
state.error = error.response?.data?.msg || error.message || '加载下一页失败'
|
state.error = error.response?.data?.msg || error.message || '加载下一页失败'
|
||||||
@@ -912,53 +753,25 @@ export default {
|
|||||||
const parent = moreNode?.parent
|
const parent = moreNode?.parent
|
||||||
if (!parent) return
|
if (!parent) return
|
||||||
state.loading = true
|
state.loading = true
|
||||||
state.error = ''
|
|
||||||
try {
|
try {
|
||||||
const page = await this.fetchPage(state)
|
const page = await this.fetchPage(state)
|
||||||
const parentKey = getTreeNodeId(parent.data) || 'root'
|
const parentKey = getTreeNodeId(parent.data) || 'root'
|
||||||
const parentIsRoot = parent.level === 0
|
const existing = new Set((parent.childNodes || []).map(n => getTreeNodeId(n.data)))
|
||||||
|
tree.remove(moreNode)
|
||||||
|
for (const item of page.list.map(normalizeTreeItem)) {
|
||||||
|
if (existing.has(item.id)) continue
|
||||||
|
existing.add(item.id)
|
||||||
|
tree.append(item, parent)
|
||||||
|
}
|
||||||
const next = nextState(state.listUrl, page)
|
const next = nextState(state.listUrl, page)
|
||||||
if (parentIsRoot) {
|
if (next) {
|
||||||
// 换一份根数据,而不是 append 到 el-tree 正在监听的数组上,避免根节点被插进两遍
|
tree.append(makeMoreNode(parentKey, next), parent)
|
||||||
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 {
|
} else {
|
||||||
const existing = new Set((parent.childNodes || []).map(n => getTreeNodeId(n.data)))
|
this.treeMoreFolders.delete(parentKey)
|
||||||
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) {
|
} catch (error) {
|
||||||
state.loading = false
|
state.loading = false
|
||||||
state.error = error.response?.data?.msg || error.message || '加载下一页失败'
|
this.$message.error(`${error.response?.data?.msg || error.message || '加载下一页失败'},可再次点击「加载更多」重试`)
|
||||||
this.$message.error(`${state.error},可再次点击「加载更多」重试`)
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
// 处理文件点击
|
// 处理文件点击
|
||||||
@@ -1430,21 +1243,7 @@ export default {
|
|||||||
const fromTree = tree
|
const fromTree = tree
|
||||||
? tree.getCheckedNodes().filter(n => this.isDownloadableFile(n))
|
? tree.getCheckedNodes().filter(n => this.isDownloadableFile(n))
|
||||||
: []
|
: []
|
||||||
const visibleKeys = new Set(
|
this.selectedFiles = uniqueFiles([...fromTree, ...extraFiles])
|
||||||
filterByFileName(this.activeLoadedEntries(), this.nameFilter)
|
|
||||||
.filter(file => this.isDownloadableFile(file))
|
|
||||||
.map(fileIdentity)
|
|
||||||
)
|
|
||||||
const extraKeys = new Set((extraFiles || []).map(fileIdentity))
|
|
||||||
const kept = this.selectedFiles.filter(file => {
|
|
||||||
const key = fileIdentity(file)
|
|
||||||
return !visibleKeys.has(key) && !extraKeys.has(key)
|
|
||||||
})
|
|
||||||
const checkedVisible = fromTree.filter(file => {
|
|
||||||
const key = fileIdentity(file)
|
|
||||||
return visibleKeys.has(key) || extraKeys.has(key)
|
|
||||||
})
|
|
||||||
this.selectedFiles = uniqueFiles([...kept, ...checkedVisible, ...(extraFiles || [])])
|
|
||||||
},
|
},
|
||||||
enqueueFolderCollect(folderData) {
|
enqueueFolderCollect(folderData) {
|
||||||
const key = getTreeNodeId(folderData)
|
const key = getTreeNodeId(folderData)
|
||||||
@@ -1503,13 +1302,11 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
isFileSelected(file) {
|
isFileSelected(file) {
|
||||||
const key = fileIdentity(file)
|
return this.selectedFiles.some(f => f.fileName === file.fileName && f.parserUrl === file.parserUrl)
|
||||||
return this.selectedFiles.some(item => fileIdentity(item) === key)
|
|
||||||
},
|
},
|
||||||
toggleFileSelect(file) {
|
toggleFileSelect(file) {
|
||||||
if (!file || file.fileType === 'folder' || isMoreNode(file)) return
|
if (file.fileType === 'folder') return
|
||||||
const key = fileIdentity(file)
|
const idx = this.selectedFiles.findIndex(f => f.fileName === file.fileName && f.parserUrl === file.parserUrl)
|
||||||
const idx = this.selectedFiles.findIndex(item => fileIdentity(item) === key)
|
|
||||||
if (idx >= 0) {
|
if (idx >= 0) {
|
||||||
this.selectedFiles.splice(idx, 1)
|
this.selectedFiles.splice(idx, 1)
|
||||||
} else {
|
} else {
|
||||||
@@ -1526,32 +1323,16 @@ export default {
|
|||||||
this.toggleFileSelect(file)
|
this.toggleFileSelect(file)
|
||||||
},
|
},
|
||||||
selectAll() {
|
selectAll() {
|
||||||
const loaded = this.activeLoadedEntries()
|
this.selectedFiles = this.currentFileList.filter(f => this.isDownloadableFile(f))
|
||||||
this.selectedFiles = selectMatching(
|
if (this.paneMore) {
|
||||||
this.selectedFiles,
|
this.$message.warning(`仅选中已加载的 ${this.selectedFiles.length} 个文件,当前目录还有未加载的分页`)
|
||||||
loaded,
|
|
||||||
this.nameFilter,
|
|
||||||
file => this.isDownloadableFile(file)
|
|
||||||
)
|
|
||||||
const hasMore = this.viewMode === 'tree'
|
|
||||||
? !!(this.rootMore || (this.treeMoreFolders && this.treeMoreFolders.size))
|
|
||||||
: !!this.paneMore
|
|
||||||
if (hasMore) {
|
|
||||||
this.$message.warning('仅选中已加载且匹配筛选的文件,未继续拉取后续分页')
|
|
||||||
}
|
}
|
||||||
this.$nextTick(() => this.syncChecksFromSelection())
|
|
||||||
},
|
},
|
||||||
deselectAll() {
|
deselectAll() {
|
||||||
this.selectedFiles = deselectMatching(
|
this.selectedFiles = []
|
||||||
this.selectedFiles,
|
|
||||||
this.activeLoadedEntries(),
|
|
||||||
this.nameFilter,
|
|
||||||
file => this.isDownloadableFile(file)
|
|
||||||
)
|
|
||||||
this.$nextTick(() => this.syncChecksFromSelection())
|
|
||||||
},
|
},
|
||||||
onTreeCheckChange() {
|
onTreeCheckChange() {
|
||||||
if (!this.batchMode || this._treeCollecting || this._syncingChecks) return
|
if (!this.batchMode || this._treeCollecting) return
|
||||||
this.syncSelectedFilesFromTree()
|
this.syncSelectedFilesFromTree()
|
||||||
},
|
},
|
||||||
extractTypeParam(file) {
|
extractTypeParam(file) {
|
||||||
@@ -1741,56 +1522,6 @@ html, body, #app, .main-container, .directory-tree, .content-card {
|
|||||||
border: 1px solid #404040;
|
border: 1px solid #404040;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dir-filter-bar {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 10px 14px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
padding: 10px 12px;
|
|
||||||
background: #fff;
|
|
||||||
border-bottom: 1px solid #eaeaea;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dark-theme .dir-filter-bar {
|
|
||||||
background: #2d2d2d;
|
|
||||||
border-bottom-color: #404040;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dir-name-filter {
|
|
||||||
flex: 1 1 220px;
|
|
||||||
max-width: 420px;
|
|
||||||
min-width: 0;
|
|
||||||
height: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dir-name-filter .el-input__wrapper {
|
|
||||||
min-height: 36px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dir-filter-hint {
|
|
||||||
margin: 0;
|
|
||||||
flex: 1 1 200px;
|
|
||||||
min-width: 0;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.45;
|
|
||||||
color: #909399;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dark-theme .dir-filter-hint {
|
|
||||||
color: #bdc3c7;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tree-filter-empty {
|
|
||||||
padding: 16px 8px 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tree-select-row {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 8px;
|
|
||||||
margin-bottom: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.breadcrumb {
|
.breadcrumb {
|
||||||
background: #f8f9fa;
|
background: #f8f9fa;
|
||||||
padding: 16px 24px;
|
padding: 16px 24px;
|
||||||
@@ -2623,27 +2354,6 @@ html, body, #app, .main-container, .directory-tree, .content-card {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.dir-filter-bar {
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: stretch;
|
|
||||||
gap: 6px;
|
|
||||||
padding: 8px 10px;
|
|
||||||
}
|
|
||||||
.dir-name-filter {
|
|
||||||
flex: 0 0 auto;
|
|
||||||
max-width: none;
|
|
||||||
width: 100%;
|
|
||||||
height: auto;
|
|
||||||
}
|
|
||||||
.dir-name-filter .el-input__wrapper {
|
|
||||||
min-height: 40px;
|
|
||||||
}
|
|
||||||
.dir-filter-hint {
|
|
||||||
flex: none;
|
|
||||||
}
|
|
||||||
.tree-select-row .el-button {
|
|
||||||
flex: 1 1 0;
|
|
||||||
}
|
|
||||||
.file-grid {
|
.file-grid {
|
||||||
grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
|
grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
|
|||||||
@@ -1,155 +0,0 @@
|
|||||||
/**
|
|
||||||
* 目录文件名筛选与批量勾选范围。
|
|
||||||
*
|
|
||||||
* 只处理已经加载的行,不发起下一页请求。分页仍由 folderPaging 的
|
|
||||||
* nextCursor / pageCursor 推进;这里只决定新页里哪些行可见、哪些会被全选。
|
|
||||||
*/
|
|
||||||
const { fileIdentity, uniqueFiles } = require('./batchTreeCollect')
|
|
||||||
const { appendUnique, nextState } = require('./folderPaging')
|
|
||||||
|
|
||||||
function normalizeQuery(keyword) {
|
|
||||||
return String(keyword == null ? '' : keyword).trim().toLowerCase()
|
|
||||||
}
|
|
||||||
|
|
||||||
function matchesFileName(file, keyword) {
|
|
||||||
const query = normalizeQuery(keyword)
|
|
||||||
if (!query) return true
|
|
||||||
return String((file && file.fileName) || '').toLowerCase().includes(query)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 空关键字返回副本,不清空调用方持有的已加载数组。 */
|
|
||||||
function filterByFileName(list, keyword) {
|
|
||||||
const rows = list || []
|
|
||||||
const query = normalizeQuery(keyword)
|
|
||||||
if (!query) return rows.slice()
|
|
||||||
return rows.filter(file => matchesFileName(file, keyword))
|
|
||||||
}
|
|
||||||
|
|
||||||
function isSelectableFile(file) {
|
|
||||||
return !!(
|
|
||||||
file
|
|
||||||
&& file.parserUrl
|
|
||||||
&& file.fileType !== 'folder'
|
|
||||||
&& file.fileType !== 'url'
|
|
||||||
&& file.fileType !== 'more'
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function countableEntries(list) {
|
|
||||||
return (list || []).filter(file => file && file.fileType !== 'more' && file.id !== 'root')
|
|
||||||
}
|
|
||||||
|
|
||||||
function filterSummary(loaded, keyword) {
|
|
||||||
const rows = countableEntries(loaded)
|
|
||||||
const matched = filterByFileName(rows, keyword)
|
|
||||||
return {
|
|
||||||
loaded: rows.length,
|
|
||||||
matched: matched.length,
|
|
||||||
text: `仅筛选已加载的 ${rows.length} 项,匹配 ${matched.length} 项`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 全选:只并入当前关键字命中的已加载可选文件。
|
|
||||||
* 不在这份可见集合里的原选择保留,隐藏项不会被加进来。
|
|
||||||
*/
|
|
||||||
function selectMatching(selected, loaded, keyword, isSelectable = isSelectableFile) {
|
|
||||||
const visible = filterByFileName(loaded, keyword).filter(file => isSelectable(file))
|
|
||||||
const visibleKeys = new Set(visible.map(fileIdentity))
|
|
||||||
const kept = (selected || []).filter(file => !visibleKeys.has(fileIdentity(file)))
|
|
||||||
return uniqueFiles(kept.concat(visible))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 取消全选:只移出当前可见可选文件,范围外的选择不动。 */
|
|
||||||
function deselectMatching(selected, loaded, keyword, isSelectable = isSelectableFile) {
|
|
||||||
const visibleKeys = new Set(
|
|
||||||
filterByFileName(loaded, keyword)
|
|
||||||
.filter(file => isSelectable(file))
|
|
||||||
.map(fileIdentity)
|
|
||||||
)
|
|
||||||
return (selected || []).filter(file => !visibleKeys.has(fileIdentity(file)))
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleSelected(selected, file, isSelectable = isSelectableFile) {
|
|
||||||
const list = (selected || []).slice()
|
|
||||||
if (!isSelectable(file)) return list
|
|
||||||
const key = fileIdentity(file)
|
|
||||||
const index = list.findIndex(item => fileIdentity(item) === key)
|
|
||||||
if (index >= 0) {
|
|
||||||
list.splice(index, 1)
|
|
||||||
return list
|
|
||||||
}
|
|
||||||
list.push(file)
|
|
||||||
return list
|
|
||||||
}
|
|
||||||
|
|
||||||
function isSelected(selected, file) {
|
|
||||||
const key = fileIdentity(file)
|
|
||||||
return (selected || []).some(item => fileIdentity(item) === key)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 已加载树节点。未展开的文件夹不往下走,因此不会把未请求的子项算进全选范围。
|
|
||||||
* 「加载更多」占位节点跳过。
|
|
||||||
*/
|
|
||||||
function collectLoadedNodes(node) {
|
|
||||||
const out = []
|
|
||||||
for (const child of (node && node.childNodes) || []) {
|
|
||||||
const data = child && child.data
|
|
||||||
if (!data || data.fileType === 'more') continue
|
|
||||||
out.push(data)
|
|
||||||
if (child.loaded) {
|
|
||||||
out.push(...collectLoadedNodes(child))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 用目录分页的 nextCursor 追加一页。
|
|
||||||
* 已有选择原样保留:新页即使命中关键字也不会被静默勾上。
|
|
||||||
*/
|
|
||||||
function applyCursorPage(state, page) {
|
|
||||||
const loaded = appendUnique(state.loaded, (page && page.list) || [])
|
|
||||||
const listUrl = (state.more && state.more.listUrl) || state.listUrl
|
|
||||||
return {
|
|
||||||
keyword: state.keyword,
|
|
||||||
view: state.view,
|
|
||||||
loaded,
|
|
||||||
selected: (state.selected || []).slice(),
|
|
||||||
listUrl,
|
|
||||||
more: nextState(listUrl, page)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function switchView(state, view) {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
view,
|
|
||||||
keyword: state.keyword,
|
|
||||||
selected: (state.selected || []).slice()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearKeyword(state) {
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
keyword: ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = {
|
|
||||||
normalizeQuery,
|
|
||||||
matchesFileName,
|
|
||||||
filterByFileName,
|
|
||||||
isSelectableFile,
|
|
||||||
filterSummary,
|
|
||||||
selectMatching,
|
|
||||||
deselectMatching,
|
|
||||||
toggleSelected,
|
|
||||||
isSelected,
|
|
||||||
collectLoadedNodes,
|
|
||||||
applyCursorPage,
|
|
||||||
switchView,
|
|
||||||
clearKeyword
|
|
||||||
}
|
|
||||||
@@ -1,237 +0,0 @@
|
|||||||
const { describe, it } = require('node:test')
|
|
||||||
const assert = require('node:assert/strict')
|
|
||||||
|
|
||||||
const { readPage } = require('./folderPaging')
|
|
||||||
const {
|
|
||||||
normalizeQuery,
|
|
||||||
filterByFileName,
|
|
||||||
filterSummary,
|
|
||||||
selectMatching,
|
|
||||||
deselectMatching,
|
|
||||||
toggleSelected,
|
|
||||||
isSelected,
|
|
||||||
collectLoadedNodes,
|
|
||||||
applyCursorPage,
|
|
||||||
switchView,
|
|
||||||
clearKeyword
|
|
||||||
} = require('./nameFilter')
|
|
||||||
|
|
||||||
function file(name, id, extra = {}) {
|
|
||||||
return {
|
|
||||||
fileName: name,
|
|
||||||
fileId: id,
|
|
||||||
fileType: 'file',
|
|
||||||
parserUrl: '/v2/redirectUrl/lz/same',
|
|
||||||
...extra
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function folder(name, id) {
|
|
||||||
return {
|
|
||||||
fileName: name,
|
|
||||||
fileId: id,
|
|
||||||
fileType: 'folder',
|
|
||||||
parserUrl: `/v2/getFileList?dir=${id}`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function baseState(overrides = {}) {
|
|
||||||
return {
|
|
||||||
keyword: '',
|
|
||||||
view: 'pane',
|
|
||||||
loaded: [],
|
|
||||||
selected: [],
|
|
||||||
listUrl: '/v2/getFileList?url=share',
|
|
||||||
more: null,
|
|
||||||
...overrides
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('filename filter', () => {
|
|
||||||
const loaded = [
|
|
||||||
file('Alpha.TXT', '1'),
|
|
||||||
file('notes.md', '2'),
|
|
||||||
file(' photo.JPG', '3'),
|
|
||||||
folder('Albums', '4')
|
|
||||||
]
|
|
||||||
|
|
||||||
it('trims and matches a case-insensitive substring', () => {
|
|
||||||
assert.equal(normalizeQuery(' ApK '), 'apk')
|
|
||||||
const matched = filterByFileName(loaded, ' aL ')
|
|
||||||
assert.deepEqual(matched.map(item => item.fileId), ['1', '4'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('blank keyword restores the loaded list without dropping rows', () => {
|
|
||||||
const cleared = filterByFileName(loaded, ' ')
|
|
||||||
assert.deepEqual(cleared.map(item => item.fileId), ['1', '2', '3', '4'])
|
|
||||||
assert.notEqual(cleared, loaded)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('describes loaded N and matched M', () => {
|
|
||||||
const summary = filterSummary(loaded, 'photo')
|
|
||||||
assert.equal(summary.loaded, 4)
|
|
||||||
assert.equal(summary.matched, 1)
|
|
||||||
assert.equal(summary.text, '仅筛选已加载的 4 项,匹配 1 项')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('select and deselect scope', () => {
|
|
||||||
const outside = file('kept.zip', 'out', { parserUrl: '/v2/redirectUrl/lz/out' })
|
|
||||||
const match = file('Alpha.TXT', '1')
|
|
||||||
const other = file('Beta.bin', '2')
|
|
||||||
const hiddenFolder = folder('Alpha-dir', '3')
|
|
||||||
const link = file('Alpha-link.url', '4', { fileType: 'url', parserUrl: '' })
|
|
||||||
const loaded = [match, other, hiddenFolder, link]
|
|
||||||
|
|
||||||
it('selects only loaded selectable files matching the keyword', () => {
|
|
||||||
const selected = selectMatching([outside], loaded, 'alpha')
|
|
||||||
assert.deepEqual(selected.map(item => item.fileId), ['out', '1'])
|
|
||||||
assert.equal(isSelected(selected, other), false)
|
|
||||||
assert.equal(isSelected(selected, hiddenFolder), false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('deselect removes only the current match and keeps selections outside it', () => {
|
|
||||||
const selected = deselectMatching([outside, match, other], loaded, 'alpha')
|
|
||||||
assert.deepEqual(selected.map(item => item.fileId), ['out', '2'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not select a loaded file hidden by the keyword', () => {
|
|
||||||
const selected = selectMatching([other], loaded, 'alpha')
|
|
||||||
assert.equal(isSelected(selected, other), true)
|
|
||||||
assert.equal(isSelected(selected, match), true)
|
|
||||||
const narrowed = selectMatching(selected, loaded, 'beta')
|
|
||||||
assert.deepEqual(narrowed.map(item => item.fileId).sort(), ['1', '2'])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('same name, different id', () => {
|
|
||||||
const first = file('Report.TXT', 'a')
|
|
||||||
const second = file('Report.TXT', 'b')
|
|
||||||
|
|
||||||
it('keeps both files when selecting and can toggle one without the other', () => {
|
|
||||||
const selected = selectMatching([], [first, second], 'report')
|
|
||||||
assert.equal(selected.length, 2)
|
|
||||||
assert.notEqual(selected[0], selected[1])
|
|
||||||
const onlySecond = toggleSelected(selected, first)
|
|
||||||
assert.deepEqual(onlySecond.map(item => item.fileId), ['b'])
|
|
||||||
assert.equal(isSelected(onlySecond, first), false)
|
|
||||||
assert.equal(isSelected(onlySecond, second), true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('distinguishes files that only differ by id when fileId is absent', () => {
|
|
||||||
const left = { fileName: 'Report.TXT', id: 'x', fileType: 'file', parserUrl: '/v2/redirectUrl/lz/same' }
|
|
||||||
const right = { fileName: 'Report.TXT', id: 'y', fileType: 'file', parserUrl: '/v2/redirectUrl/lz/same' }
|
|
||||||
const selected = toggleSelected([], left)
|
|
||||||
assert.equal(isSelected(selected, right), false)
|
|
||||||
assert.equal(toggleSelected(selected, right).length, 2)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('cursor page', () => {
|
|
||||||
it('shows new matches from the next cursor without selecting them', () => {
|
|
||||||
let state = baseState({
|
|
||||||
keyword: 'alpha',
|
|
||||||
loaded: [file('Alpha.TXT', '1'), file('Beta.bin', '2')],
|
|
||||||
selected: [file('Beta.bin', '2')],
|
|
||||||
more: { listUrl: '/v2/getFileList?url=share', nextPage: 2, nextCursor: 'c1', loading: false, error: '' }
|
|
||||||
})
|
|
||||||
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1'])
|
|
||||||
|
|
||||||
state = applyCursorPage(state, readPage({
|
|
||||||
list: [file('ALPHA-extra.txt', '3'), file('Gamma.bin', '4')],
|
|
||||||
paged: true,
|
|
||||||
hasMore: true,
|
|
||||||
nextPage: 3,
|
|
||||||
nextCursor: 'c2'
|
|
||||||
}))
|
|
||||||
|
|
||||||
assert.deepEqual(state.loaded.map(item => item.fileId), ['1', '2', '3', '4'])
|
|
||||||
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1', '3'])
|
|
||||||
assert.deepEqual(state.selected.map(item => item.fileId), ['2'])
|
|
||||||
assert.equal(state.more.nextCursor, 'c2')
|
|
||||||
assert.equal(state.more.nextPage, 3)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps load-more available when nothing matches yet', () => {
|
|
||||||
let state = baseState({
|
|
||||||
keyword: 'zzzz',
|
|
||||||
loaded: [file('Alpha.TXT', '1')],
|
|
||||||
more: { listUrl: '/v2/getFileList?url=share', nextPage: 2, nextCursor: 'c1', loading: false, error: '' }
|
|
||||||
})
|
|
||||||
assert.equal(filterByFileName(state.loaded, state.keyword).length, 0)
|
|
||||||
assert.equal(state.more.nextCursor, 'c1')
|
|
||||||
|
|
||||||
state = applyCursorPage(state, readPage({
|
|
||||||
list: [file('zzzz-found.txt', '9')],
|
|
||||||
hasMore: true,
|
|
||||||
nextPage: 3,
|
|
||||||
nextCursor: 'c2'
|
|
||||||
}))
|
|
||||||
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['9'])
|
|
||||||
assert.equal(state.selected.length, 0)
|
|
||||||
assert.ok(state.more)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('view switch and clear', () => {
|
|
||||||
it('keeps the keyword and selected identities when the view changes', () => {
|
|
||||||
const chosen = file('Alpha.TXT', '1')
|
|
||||||
const state = baseState({
|
|
||||||
keyword: ' Alpha ',
|
|
||||||
view: 'pane',
|
|
||||||
loaded: [chosen, file('Beta.bin', '2')],
|
|
||||||
selected: [chosen]
|
|
||||||
})
|
|
||||||
const tree = switchView(state, 'tree')
|
|
||||||
assert.equal(tree.view, 'tree')
|
|
||||||
assert.equal(tree.keyword, ' Alpha ')
|
|
||||||
assert.deepEqual(tree.selected.map(item => item.fileId), ['1'])
|
|
||||||
const back = switchView(tree, 'pane')
|
|
||||||
assert.equal(back.keyword, state.keyword)
|
|
||||||
assert.equal(isSelected(back.selected, chosen), true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('clearing the keyword shows every loaded row again', () => {
|
|
||||||
const state = baseState({
|
|
||||||
keyword: 'alpha',
|
|
||||||
loaded: [file('Alpha.TXT', '1'), file('Beta.bin', '2')]
|
|
||||||
})
|
|
||||||
assert.deepEqual(filterByFileName(state.loaded, state.keyword).map(item => item.fileId), ['1'])
|
|
||||||
const cleared = clearKeyword(state)
|
|
||||||
assert.deepEqual(
|
|
||||||
filterByFileName(cleared.loaded, cleared.keyword).map(item => item.fileId),
|
|
||||||
['1', '2']
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('loaded tree nodes', () => {
|
|
||||||
it('skips unloaded folders, hidden placeholders, and does not invent a fetch', () => {
|
|
||||||
const secret = file('secret.txt', 'secret')
|
|
||||||
const more = { data: { fileType: 'more', fileName: '加载更多…' }, loaded: true, childNodes: [] }
|
|
||||||
const root = {
|
|
||||||
childNodes: [
|
|
||||||
{ data: file('root.txt', 'root'), loaded: true, childNodes: [] },
|
|
||||||
{
|
|
||||||
data: folder('closed', 'closed'),
|
|
||||||
loaded: false,
|
|
||||||
childNodes: [{ data: secret, loaded: true, childNodes: [] }]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
data: folder('open', 'open'),
|
|
||||||
loaded: true,
|
|
||||||
childNodes: [
|
|
||||||
{ data: file('open-a.txt', 'oa'), loaded: true, childNodes: [] },
|
|
||||||
more
|
|
||||||
]
|
|
||||||
},
|
|
||||||
more
|
|
||||||
]
|
|
||||||
}
|
|
||||||
const loaded = collectLoadedNodes(root)
|
|
||||||
assert.deepEqual(loaded.map(item => item.fileId), ['root', 'closed', 'open', 'oa'])
|
|
||||||
const selected = selectMatching([], loaded, '')
|
|
||||||
assert.deepEqual(selected.map(item => item.fileId), ['root', 'oa'])
|
|
||||||
assert.equal(isSelected(selected, secret), false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
Reference in new issue
Block a user