mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-11-25 14:57:00 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
237dc3263b | ||
|
|
8ddbd1ef7f | ||
|
|
a86b26d668 | ||
|
|
5781100905 | ||
|
|
04ba9a0e2c | ||
|
|
3825527519 | ||
|
|
531f431faa | ||
|
|
25888661ad | ||
|
|
d692416a2e |
No files matched your search
@@ -184,8 +184,8 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
|
||||
**网盘认证要求**:
|
||||
| 网盘 | 认证要求 | 说明 |
|
||||
|------|---------|------|
|
||||
| 夸克网盘(QK) | 小文件可免登录 | 小文件走访客直链。文件夹会先列目录再进入。超过访客大小限制(上游 23018,本次核对约 90MB 失败、约 12MB–27MB 成功)必须配置 `auths.qk.cookie` 或请求 `auth`。未配置 Cookie 时不会转存 |
|
||||
| UC网盘(UC) | **必须** | 不能免登录,必须配置 Cookie |
|
||||
| 夸克网盘(QK) | 不超过 10MiB 可走原解析 | 不大于 `10 * 1024 * 1024` 字节(含等于该值)保持原来的分享解析。更大的文件仅在会员接口确认未过期 SVIP/VIP 时使用该账号直链;否则使用探测通过的 H5 文件地址并附上真实文件名。普通或过期 Cookie 不算会员 |
|
||||
| UC网盘(UC) | **不能免登录** | 小文件仍要 Cookie。超过 10MiB 时同样只认未过期 SVIP/VIP 的账号直链;没有时才尝试 H5 文件地址。H5 没有可下载文件就返回明确错误,不会把 UC 当成免登录 |
|
||||
| 小飞机网盘(FJ) | 可选 | 大文件(>100MB)需要认证 |
|
||||
| 蓝奏优享(IZ) | 可选 | 大文件需要认证 |
|
||||
| 123网盘(YE) | 下载通常需要 | 分享列表经常可以不登录读取。下载接口常见 5112 / 请登录后下载 / 您需要注册登录或付费后下载,请在**本机**配置 `auths.ye.authorization`(与 `token` 等价)或账号密码。公共云解析没有共享 123 账号。约 10MB 小文件有时可以直链,大文件和风控必须用你自己的账号。短链:`ye:分享key@提取码`;`#` 片段会去掉;`yun.123pan.com`、`www.123pan.com`、`*.share.123pan.cn` 同一类 |
|
||||
@@ -383,13 +383,13 @@ json返回数据格式示例:
|
||||
| 文叔叔 | √ | √ | 10G | 5GB |
|
||||
| 永硕E盘 | √ | √(空间密码) | 视套餐 | 视套餐 |
|
||||
| WPS云文档 | √ | X | 5G(免费) | 10M(免费)/2G(会员) |
|
||||
| 夸克网盘 | 小文件 | √ | 10G | 访客有大小限制(23018) |
|
||||
| UC网盘 | x | √ | 10G | 不限大小 |
|
||||
| 夸克网盘 | ≤10MiB 原解析 | √ | 10G | 更大文件要有效 SVIP/VIP,或可用的 H5 文件地址 |
|
||||
| UC网盘 | x | √ | 10G | 不能免登录;大文件规则同夸克 |
|
||||
| 飞书云盘 | √ | X | 15G | 不限大小 |
|
||||
|
||||
免登录边界(阈值由网盘决定,不是本项目写死的):
|
||||
|
||||
- **夸克**:小文件可以不登录。本次核对约 12MB–27MB 的访客直链成功,约 90MB 返回 `23018`。分享根目录如果只是文件夹,解析会继续进入子目录。超过限制时配置 `auths.qk.cookie`。UC 不能免登录。百度大约 100MB 以内有直链,属于专业版,这次没有改解析器。
|
||||
- **夸克 / UC**:单文件体积阈值是 `10 * 1024 * 1024` 字节(10MiB)。小于或等于该值保持原来的解析。严格大于该值时,先请求会员接口,只把 `member_type` 为 `SUPER_VIP`、`EXP_SVIP`、`Z_VIP`、`VIP`、`EXP_VIP` 且 `exp_at` 仍在未来的账号当作有效 SVIP/VIP,并走原来的账号直链。缺少档位、普通账号、已过期或只有 Cookie 都不会当成会员。没有有效会员时,才使用 H5 预览返回的 `https://dl-c-*.drive.quark.cn` 或 `https://dl-c-*.drive.uc.cn` 文件地址,并加上真实 `filename`(含中文)。预览网页、HTML、JSON、m3u8 不会当作下载成功。UC 不能免登录。目录列表不变。百度大约 100MB 以内有直链,属于专业版,这次没有改解析器。
|
||||
- **123**:分享目录经常可以不登录看。下载则经常要登录。请本机配置 Authorization,不要依赖公共云解析的共享账号。约 10MB 的小文件有时能直链。
|
||||
|
||||
# 打包部署
|
||||
@@ -470,7 +470,7 @@ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtow
|
||||
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
|
||||
```shell
|
||||
cd ~
|
||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.8/netdisk-fast-download-linux-amd64.zip
|
||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.9/netdisk-fast-download-linux-amd64.zip
|
||||
unzip netdisk-fast-download.zip
|
||||
cd netdisk-fast-download
|
||||
bash service-install.sh
|
||||
@@ -527,7 +527,7 @@ nfd-proxy搭建http代理服务器
|
||||
参考https://github.com/nfd-parser/nfd-proxy
|
||||
|
||||
### 认证信息配置说明
|
||||
夸克小文件可以不登录;大文件要本机 Cookie。123 的下载在公共解析站上基本都要你自己的 Authorization,云端没有共用账号。
|
||||
夸克不超过 10MiB 可以不登录;更大的文件要本机未过期的 SVIP/VIP Cookie,或上游确实返回了可下载的 H5 文件地址。UC 不能免登录。123 的下载在公共解析站上基本都要你自己的 Authorization,云端没有共用账号。
|
||||
|
||||
修改配置文件:
|
||||
app-dev.yml
|
||||
@@ -535,9 +535,12 @@ app-dev.yml
|
||||
```yaml
|
||||
### 解析认证相关
|
||||
auths:
|
||||
# 夸克大文件:auths.qk.cookie
|
||||
# 夸克 / UC 大于 10MiB(10 * 1024 * 1024 字节)时才会查询会员接口。
|
||||
# 只有未过期的 SVIP/VIP 才使用该账号直链;不要把普通 Cookie 写成会员。
|
||||
# qk:
|
||||
# cookie: 浏览器里夸克网盘的 Cookie
|
||||
# uc:
|
||||
# cookie: 浏览器里 UC 网盘的 Cookie
|
||||
# 123:优先填 authorization。账号密码若触发验证码会失败,本项目不处理验证码。
|
||||
ye:
|
||||
username: 你的用户名
|
||||
|
||||
@@ -261,39 +261,11 @@ var methods = systemClass.getDeclaredMethods();
|
||||
|
||||
Nashorn引擎默认允许JavaScript访问所有Java类,这是一个严重的安全隐患。以下是建议的安全措施:
|
||||
|
||||
### 1. 使用ClassFilter限制类访问 🔒 必须
|
||||
### 1. 演练场与已注册解析器的类访问限制
|
||||
|
||||
```java
|
||||
import jdk.nashorn.api.scripting.ClassFilter;
|
||||
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
两个入口都通过 `ParserScriptEngine.create()` 创建 Nashorn 引擎。引擎使用 `--no-java`,类过滤器拒绝按名称解析 Java 类。引擎在执行解析器代码前禁用包入口、脚本加载函数和脚本上下文全局变量。解析器仍可使用项目显式注入的分享信息、HTTP、Fetch 和日志接口。
|
||||
|
||||
public class SecurityClassFilter implements ClassFilter {
|
||||
@Override
|
||||
public boolean exposeToScripts(String className) {
|
||||
// 黑名单:禁止访问危险类
|
||||
if (className.startsWith("java.lang.Runtime") ||
|
||||
className.startsWith("java.lang.ProcessBuilder") ||
|
||||
className.startsWith("java.io.File") ||
|
||||
className.startsWith("java.nio.file") ||
|
||||
className.startsWith("java.lang.System") ||
|
||||
className.startsWith("java.lang.Class") ||
|
||||
className.startsWith("java.lang.reflect") ||
|
||||
className.startsWith("java.net.Socket") ||
|
||||
className.startsWith("java.net.URL")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 白名单:只允许特定的类
|
||||
// return className.startsWith("允许的包名");
|
||||
|
||||
return false; // 默认拒绝所有
|
||||
}
|
||||
}
|
||||
|
||||
// 使用ClassFilter创建引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
ScriptEngine engine = factory.getScriptEngine(new SecurityClassFilter());
|
||||
```
|
||||
`ParserScriptEngineTest` 检查受限全局变量的属性,并通过两个执行入口验证普通解析器的行为。
|
||||
|
||||
### 2. 设置执行超时 ⏱️ 强烈推荐
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package cn.qaiu.entity;
|
||||
|
||||
import cn.qaiu.util.QuarkAccountScope;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -85,12 +87,19 @@ public class ShareLinkInfo {
|
||||
public String getCacheKey() {
|
||||
// 将type和shareKey组合成一个字符串作为缓存key
|
||||
String key = type + ":" + shareKey;
|
||||
if (type.equals("p115")) {
|
||||
if (type != null && type.equals("p115")) {
|
||||
Object ua = otherParam != null ? otherParam.get("UA") : null;
|
||||
if (ua != null) {
|
||||
key += ("_" + ua.toString().hashCode());
|
||||
}
|
||||
}
|
||||
// 带账号的夸克 / UC 直链按账号隔离,避免会员链和 Cookie 进入分享级缓存。
|
||||
if (type != null && ("qk".equalsIgnoreCase(type) || "uc".equalsIgnoreCase(type))) {
|
||||
String scope = QuarkAccountScope.suffix(otherParam);
|
||||
if (scope != null) {
|
||||
key += "#" + scope;
|
||||
}
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import io.vertx.core.Future;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.WorkerExecutor;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -134,15 +133,7 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
|
||||
*/
|
||||
private ScriptEngine initEngine() {
|
||||
try {
|
||||
// 使用安全的ClassFilter创建Nashorn引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
|
||||
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
|
||||
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
|
||||
|
||||
if (engine == null) {
|
||||
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
|
||||
}
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
this.engine = engine;
|
||||
|
||||
// 注入Java对象到JavaScript环境
|
||||
@@ -151,14 +142,6 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
|
||||
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
||||
engine.put("JavaFetch", fetchBridge);
|
||||
|
||||
// 禁用Java对象访问
|
||||
engine.eval("var Java = undefined;");
|
||||
engine.eval("var JavaImporter = undefined;");
|
||||
engine.eval("var Packages = undefined;");
|
||||
engine.eval("var javax = undefined;");
|
||||
engine.eval("var org = undefined;");
|
||||
engine.eval("var com = undefined;");
|
||||
|
||||
// 加载fetch运行时(Promise和fetch API polyfill)
|
||||
String fetchRuntime = loadFetchRuntime();
|
||||
if (!fetchRuntime.isEmpty()) {
|
||||
|
||||
@@ -5,7 +5,6 @@ import cn.qaiu.entity.ShareLinkInfo;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -111,15 +110,7 @@ public class JsPlaygroundExecutor implements AutoCloseable {
|
||||
*/
|
||||
private ScriptEngine initEngine() {
|
||||
try {
|
||||
// 使用安全的ClassFilter创建Nashorn引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
|
||||
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
|
||||
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
|
||||
|
||||
if (engine == null) {
|
||||
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
|
||||
}
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
this.engine = engine;
|
||||
|
||||
// 注入Java对象到JavaScript环境
|
||||
@@ -128,14 +119,6 @@ public class JsPlaygroundExecutor implements AutoCloseable {
|
||||
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
||||
engine.put("JavaFetch", fetchBridge);
|
||||
|
||||
// 禁用Java对象访问
|
||||
engine.eval("var Java = undefined;");
|
||||
engine.eval("var JavaImporter = undefined;");
|
||||
engine.eval("var Packages = undefined;");
|
||||
engine.eval("var javax = undefined;");
|
||||
engine.eval("var org = undefined;");
|
||||
engine.eval("var com = undefined;");
|
||||
|
||||
// 加载fetch运行时(Promise和fetch API polyfill)
|
||||
String fetchRuntime = JsParserExecutor.loadFetchRuntime();
|
||||
if (!fetchRuntime.isEmpty()) {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptException;
|
||||
|
||||
final class ParserScriptEngine {
|
||||
private ParserScriptEngine() {}
|
||||
|
||||
static ScriptEngine create() throws ScriptException {
|
||||
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
|
||||
new String[]{"--no-java"}, null, new SecurityClassFilter());
|
||||
// Remove host loaders and scripting-context globals before binding the parser APIs.
|
||||
engine.eval("""
|
||||
(function (global) {
|
||||
["load", "loadWithNewGlobal", "exit", "quit", "engine", "context",
|
||||
"Java", "JavaImporter", "Packages", "java", "javax", "javafx", "org",
|
||||
"com", "edu"].forEach(function (name) {
|
||||
Object.defineProperty(global, name, {
|
||||
value: void 0, writable: false, configurable: false
|
||||
});
|
||||
});
|
||||
})(this);
|
||||
""");
|
||||
return engine;
|
||||
}
|
||||
}
|
||||
@@ -1,118 +1,11 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import org.openjdk.nashorn.api.scripting.ClassFilter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* JavaScript执行器安全类过滤器
|
||||
* 用于限制JavaScript代码可以访问的Java类,防止恶意代码执行危险操作
|
||||
*
|
||||
* @author <a href="https://qaiu.top">QAIU</a>
|
||||
*/
|
||||
/** Scripts work through the supplied parser APIs and may not resolve Java classes by name. */
|
||||
public class SecurityClassFilter implements ClassFilter {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SecurityClassFilter.class);
|
||||
|
||||
// 危险类黑名单
|
||||
private static final String[] DANGEROUS_CLASSES = {
|
||||
// 系统命令执行
|
||||
"java.lang.Runtime",
|
||||
"java.lang.ProcessBuilder",
|
||||
"java.lang.Process",
|
||||
|
||||
// 文件系统访问
|
||||
"java.io.File",
|
||||
"java.io.FileInputStream",
|
||||
"java.io.FileOutputStream",
|
||||
"java.io.FileReader",
|
||||
"java.io.FileWriter",
|
||||
"java.io.RandomAccessFile",
|
||||
"java.nio.file.Files",
|
||||
"java.nio.file.Paths",
|
||||
"java.nio.file.Path",
|
||||
"java.nio.channels.FileChannel",
|
||||
|
||||
// 系统访问
|
||||
"java.lang.System",
|
||||
"java.lang.SecurityManager",
|
||||
|
||||
// 反射相关
|
||||
"java.lang.Class",
|
||||
"java.lang.reflect.Method",
|
||||
"java.lang.reflect.Field",
|
||||
"java.lang.reflect.Constructor",
|
||||
"java.lang.reflect.AccessibleObject",
|
||||
"java.lang.ClassLoader",
|
||||
|
||||
// 网络访问
|
||||
"java.net.Socket",
|
||||
"java.net.ServerSocket",
|
||||
"java.net.DatagramSocket",
|
||||
"java.net.URL",
|
||||
"java.net.URLConnection",
|
||||
"java.net.HttpURLConnection",
|
||||
"java.net.InetAddress",
|
||||
|
||||
// 线程和并发
|
||||
"java.lang.Thread",
|
||||
"java.lang.ThreadGroup",
|
||||
"java.util.concurrent.Executor",
|
||||
"java.util.concurrent.ExecutorService",
|
||||
|
||||
// 数据库访问
|
||||
"java.sql.Connection",
|
||||
"java.sql.Statement",
|
||||
"java.sql.PreparedStatement",
|
||||
"java.sql.DriverManager",
|
||||
|
||||
// 脚本引擎(防止嵌套执行)
|
||||
"javax.script.ScriptEngine",
|
||||
"javax.script.ScriptEngineManager",
|
||||
|
||||
// JVM控制
|
||||
"java.lang.invoke.MethodHandle",
|
||||
"sun.misc.Unsafe",
|
||||
|
||||
// Nashorn内部类
|
||||
"jdk.nashorn.internal",
|
||||
"jdk.internal",
|
||||
};
|
||||
|
||||
@Override
|
||||
public boolean exposeToScripts(String className) {
|
||||
// 检查是否在黑名单中
|
||||
for (String dangerous : DANGEROUS_CLASSES) {
|
||||
if (className.equals(dangerous) || className.startsWith(dangerous + ".")) {
|
||||
log.warn("🔒 安全拦截: JavaScript尝试访问危险类 - {}", className);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 额外的包级别限制
|
||||
String[] dangerousPackages = {
|
||||
"java.lang.reflect.",
|
||||
"java.io.",
|
||||
"java.nio.",
|
||||
"java.net.",
|
||||
"java.sql.",
|
||||
"javax.script.",
|
||||
"sun.",
|
||||
"jdk.internal.",
|
||||
"jdk.nashorn.internal."
|
||||
};
|
||||
|
||||
for (String pkg : dangerousPackages) {
|
||||
if (className.startsWith(pkg)) {
|
||||
log.warn("🔒 安全拦截: JavaScript尝试访问危险包 - {}", className);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 默认也拒绝(白名单策略更安全,但这里为了兼容性使用黑名单)
|
||||
// 如果要更严格,可以改为 return false
|
||||
log.debug("允许访问类: {}", className);
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
final class FjDownloadParams {
|
||||
private FjDownloadParams() {
|
||||
}
|
||||
|
||||
static JsonObject create(String fileId, String userId, String uuid, String shareId, long timestamp) {
|
||||
if (StringUtils.isBlank(fileId) || StringUtils.isBlank(shareId)) {
|
||||
throw new IllegalArgumentException("缺少 fileId 或 shareId");
|
||||
}
|
||||
return JsonObject.of("fileId", fileId,
|
||||
"fidEncode", AESUtils.encrypt2Hex(fileId + "|" + StringUtils.defaultString(userId)),
|
||||
"uuid", uuid, "shareId", shareId,
|
||||
"ts", AESUtils.encrypt2Hex(Long.toString(timestamp)),
|
||||
"auth", AESUtils.encrypt2Hex(fileId + "|" + timestamp));
|
||||
}
|
||||
|
||||
static String fileId(JsonObject params) throws Exception {
|
||||
String fileId = params.getString("fileId");
|
||||
if (StringUtils.isNotBlank(fileId)) {
|
||||
return fileId;
|
||||
}
|
||||
// 兼容已生成的目录链接,但不再复用其中的身份和过期签名。
|
||||
String decoded = AESUtils.decryptByHexAES(params.getString("fidEncode"), AESUtils.CIPHER_AES0);
|
||||
int separator = decoded.indexOf('|');
|
||||
if (separator <= 0) {
|
||||
throw new IllegalArgumentException("无效的 fidEncode");
|
||||
}
|
||||
return decoded.substring(0, separator);
|
||||
}
|
||||
|
||||
static String ownerId(JsonObject params) throws Exception {
|
||||
Object id = params.getValue("userId");
|
||||
if (id != null && StringUtils.isNotBlank(id.toString())) {
|
||||
return id.toString();
|
||||
}
|
||||
String encoded = params.getString("fidEncode");
|
||||
if (StringUtils.isBlank(encoded)) {
|
||||
return null;
|
||||
}
|
||||
String decoded = AESUtils.decryptByHexAES(encoded, AESUtils.CIPHER_AES0);
|
||||
int separator = decoded.indexOf('|');
|
||||
String owner = separator < 0 ? null : decoded.substring(separator + 1);
|
||||
return StringUtils.isBlank(owner) || "null".equals(owner) ? null : owner;
|
||||
}
|
||||
|
||||
static String missingLocation(int status, String body) {
|
||||
String message = "未获取到下载重定向地址, HTTP " + status;
|
||||
if (StringUtils.isBlank(body)) {
|
||||
return message + ", 响应体为空";
|
||||
}
|
||||
try {
|
||||
JsonObject json = new JsonObject(body);
|
||||
if (StringUtils.isNotBlank(json.getString("msg"))) {
|
||||
return message + ", 上游返回: " + preview(json.getString("msg"))
|
||||
+ " (code=" + json.getValue("code") + ")";
|
||||
}
|
||||
} catch (RuntimeException ignored) {
|
||||
// 非 JSON 错误页同样保留有限长度的诊断内容。
|
||||
}
|
||||
return message + ", 响应体: " + preview(body);
|
||||
}
|
||||
|
||||
private static String preview(String value) {
|
||||
return value.length() > 500 ? value.substring(0, 500) + "..." : value;
|
||||
}
|
||||
}
|
||||
@@ -129,8 +129,6 @@ public class FjTool extends PanBase {
|
||||
if (auths.contains("userId")) {
|
||||
FjTool.userId = auths.get("userId");
|
||||
log.info("已配置用户ID: {}", FjTool.userId);
|
||||
} else {
|
||||
log.warn("未配置用户ID, 可能会导致解析失败");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +197,7 @@ public class FjTool extends PanBase {
|
||||
// 其他参数
|
||||
long nowTs2 = System.currentTimeMillis();
|
||||
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId);
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
||||
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
||||
|
||||
// 检查是否有认证信息
|
||||
@@ -223,7 +221,7 @@ public class FjTool extends PanBase {
|
||||
log.warn("登录失败: {}", failRes.getMessage());
|
||||
fail(failRes.getMessage());
|
||||
}).onSuccess(r-> {
|
||||
httpRequest.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId))
|
||||
httpRequest.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + userId))
|
||||
.putHeaders(header);
|
||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
});
|
||||
@@ -245,7 +243,7 @@ public class FjTool extends PanBase {
|
||||
});
|
||||
} else {
|
||||
httpRequest
|
||||
.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId))
|
||||
.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + userId))
|
||||
.putHeaders(header);
|
||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
}
|
||||
@@ -444,8 +442,15 @@ public class FjTool extends PanBase {
|
||||
|
||||
private void down(HttpResponse<Buffer> res2) {
|
||||
MultiMap headers = res2.headers();
|
||||
if (!headers.contains("Location") || headers.get("Location") == null) {
|
||||
fail("找不到下载链接可能服务器已被禁止或者配置的认证信息有误: " + res2.bodyAsString());
|
||||
if (StringUtils.isBlank(headers.get("Location"))) {
|
||||
String body;
|
||||
try {
|
||||
body = asText(res2);
|
||||
} catch (IllegalArgumentException | UnsupportedOperationException e) {
|
||||
fail(e, "读取下载错误响应失败, HTTP {}", res2.statusCode());
|
||||
return;
|
||||
}
|
||||
fail("{}", FjDownloadParams.missingLocation(res2.statusCode(), body));
|
||||
return;
|
||||
}
|
||||
promise.complete(headers.get("Location"));
|
||||
@@ -523,7 +528,7 @@ public class FjTool extends PanBase {
|
||||
// 其他参数
|
||||
long nowTs2 = System.currentTimeMillis();
|
||||
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId);
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
||||
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
||||
|
||||
// 回传用到的参数
|
||||
@@ -533,6 +538,8 @@ public class FjTool extends PanBase {
|
||||
//"auth", paramJson.getString("auth"))
|
||||
//"shareId", paramJson.getString("shareId"))
|
||||
JsonObject entries = JsonObject.of(
|
||||
"fileId", fileId,
|
||||
"userId", userId,
|
||||
"fidEncode", fidEncode,
|
||||
"uuid", uuid,
|
||||
"ts", tsEncode2,
|
||||
@@ -590,20 +597,24 @@ public class FjTool extends PanBase {
|
||||
promise.fail("缺少 paramJson 参数");
|
||||
return promise.future();
|
||||
}
|
||||
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
||||
.setTemplateParam("fidEncode", paramJson.getString("fidEncode"))
|
||||
.setTemplateParam("uuid", paramJson.getString("uuid"))
|
||||
.setTemplateParam("ts", paramJson.getString("ts"))
|
||||
.setTemplateParam("auth", paramJson.getString("auth"))
|
||||
.setTemplateParam("dataKey", paramJson.getString("shareId"))
|
||||
.putHeaders(header).send().onSuccess(res2 -> {
|
||||
MultiMap headers = res2.headers();
|
||||
if (!headers.contains("Location")) {
|
||||
fail(SECOND_REQUEST_URL_VIP + " 未找到重定向URL: \n" + res2.headers());
|
||||
return;
|
||||
}
|
||||
promise.complete(headers.get("Location"));
|
||||
}).onFailure(handleFail(SECOND_REQUEST_URL_VIP));
|
||||
try {
|
||||
String ownerId = FjDownloadParams.ownerId(paramJson);
|
||||
if (StringUtils.isBlank(ownerId) || "null".equals(ownerId)) {
|
||||
fail("目录下载参数缺少分享者 userId,请刷新文件列表后重试");
|
||||
return promise.future();
|
||||
}
|
||||
JsonObject params = FjDownloadParams.create(FjDownloadParams.fileId(paramJson), ownerId,
|
||||
paramJson.getString("uuid"), paramJson.getString("shareId"), System.currentTimeMillis());
|
||||
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
||||
.setTemplateParam("fidEncode", params.getString("fidEncode"))
|
||||
.setTemplateParam("uuid", params.getString("uuid"))
|
||||
.setTemplateParam("ts", params.getString("ts"))
|
||||
.setTemplateParam("auth", params.getString("auth"))
|
||||
.setTemplateParam("dataKey", params.getString("shareId"))
|
||||
.putHeaders(header).send().onSuccess(this::down).onFailure(handleFail("下载请求"));
|
||||
} catch (Exception e) {
|
||||
fail(e, "下载参数无效");
|
||||
}
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.PanBase;
|
||||
@@ -8,6 +9,7 @@ import cn.qaiu.util.CommonUtils;
|
||||
import cn.qaiu.util.CookieUtils;
|
||||
import cn.qaiu.util.FileSizeConverter;
|
||||
import cn.qaiu.util.HeaderUtils;
|
||||
import cn.qaiu.util.QuarkAccountScope;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Promise;
|
||||
@@ -66,8 +68,10 @@ public class QkTool extends PanBase {
|
||||
"夸克要求登录后才能下载。请配置 Cookie(auths.qk.cookie,或请求参数 auth)。"
|
||||
+ "小文件可以免登录直链;这个报错表示当前文件需要账号,请到 Cookie/auth 配置里补登录态。";
|
||||
|
||||
// 静态变量:缓存已转存的文件 (分享key -> 转存文件ID)
|
||||
// 静态变量:缓存已转存的文件 (账号范围 + 分享文件 -> 转存文件ID)
|
||||
private static final Map<String, String> savedFileCache = new java.util.concurrent.ConcurrentHashMap<>();
|
||||
/** 本次解析得到的是不带账号的公开文件地址。 */
|
||||
private boolean publicDirectLink;
|
||||
|
||||
private final MultiMap header = HeaderUtils.parseHeaders("""
|
||||
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) quark-cloud-drive/2.5.20 Chrome/100.0.4896.160 Electron/18.3.5.4-b478491100 Safari/537.36 Channel/pckk_other_ch
|
||||
@@ -249,7 +253,7 @@ public class QkTool extends PanBase {
|
||||
// 根目录可能只是文件夹(#282)。先列出再进入,找到文件后再取直链。
|
||||
findDownloadableFiles(pwdId, stoken, "0", 0)
|
||||
.compose(files -> resolveListedFiles(files, pwdId, stoken))
|
||||
.onSuccess(downloadUrl -> completeWithMeta(downloadUrl, buildDownloadHeaders(null)))
|
||||
.onSuccess(this::finishParse)
|
||||
.onFailure(t -> fail(t.getMessage() == null ? "解析失败" : t.getMessage()));
|
||||
})
|
||||
.onFailure(handleFail(TOKEN_URL));
|
||||
@@ -261,14 +265,83 @@ public class QkTool extends PanBase {
|
||||
if (files == null || files.isEmpty()) {
|
||||
return Future.failedFuture(EMPTY_SHARE_MSG);
|
||||
}
|
||||
JsonObject primary = files.get(0);
|
||||
if (QuarkFamilyDownloadPolicy.knownLarge(fileSize(primary))) {
|
||||
rememberFile(primary);
|
||||
return resolveLargeFile(primary, pwdId, stoken);
|
||||
}
|
||||
if (hasQuarkCookie()) {
|
||||
JsonObject first = files.get(0);
|
||||
rememberFile(first);
|
||||
return resolveDownloadUrl(first.getString("fid"), pwdId, stoken, first.getString("share_fid_token"));
|
||||
rememberFile(primary);
|
||||
return resolveDownloadUrl(primary.getString("fid"), pwdId, stoken, primary.getString("share_fid_token"));
|
||||
}
|
||||
return resolveGuestDownloads(orderGuestCandidates(files), pwdId, stoken, 0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 大于 10MiB:有效 SVIP/VIP 走现有账号直链(含原有转存回退);否则只要探测通过的 H5 文件地址。
|
||||
*/
|
||||
private Future<String> resolveLargeFile(JsonObject file, String pwdId, String stoken) {
|
||||
String fid = file.getString("fid");
|
||||
String shareFidToken = file.getString("share_fid_token");
|
||||
String fileName = file.getString("file_name", "");
|
||||
if (fid == null || fid.isEmpty()) {
|
||||
return Future.failedFuture(QuarkFamilyDownloadPolicy.largeFileError("qk", null,
|
||||
new IllegalStateException("缺少 fid")));
|
||||
}
|
||||
return QuarkFamilyDownloadPolicy.fetchMembership(client, header, false)
|
||||
.compose(member -> {
|
||||
if (!member.validPaid) {
|
||||
return h5Download(pwdId, stoken, fid, shareFidToken, fileName)
|
||||
.recover(h5Error -> Future.failedFuture(
|
||||
QuarkFamilyDownloadPolicy.largeFileError("qk", null, h5Error)));
|
||||
}
|
||||
return resolveDownloadUrl(fid, pwdId, stoken, shareFidToken)
|
||||
.recover(directError -> h5Download(pwdId, stoken, fid, shareFidToken, fileName)
|
||||
.recover(h5Error -> Future.failedFuture(
|
||||
QuarkFamilyDownloadPolicy.largeFileError("qk", directError, h5Error))));
|
||||
});
|
||||
}
|
||||
|
||||
private Future<String> h5Download(String pwdId, String stoken, String fid, String shareFidToken, String fileName) {
|
||||
return QuarkFamilyDownloadPolicy.resolveH5Download(clientNoRedirects, WebClientVertxInit.get(),
|
||||
"qk", pwdId, stoken, fid, shareFidToken, fileName)
|
||||
.map(url -> {
|
||||
publicDirectLink = true;
|
||||
shareLinkInfo.getOtherParam().put("publicDirectLink", true);
|
||||
shareLinkInfo.getOtherParam().put("previewUrl", QuarkFamilyDownloadPolicy.bareFileUrl(url));
|
||||
return url;
|
||||
});
|
||||
}
|
||||
|
||||
private void finishParse(String downloadUrl) {
|
||||
String presented = presentIfPublic(downloadUrl);
|
||||
if (publicDirectLink) {
|
||||
completeWithMeta(presented, Map.of());
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", false);
|
||||
return;
|
||||
}
|
||||
completeWithMeta(presented, buildDownloadHeaders(null));
|
||||
}
|
||||
|
||||
private String presentIfPublic(String downloadUrl) {
|
||||
String presented = QuarkFamilyDownloadPolicy.presentPublicDownload(downloadUrl, "qk", currentFileName());
|
||||
if (!presented.equals(downloadUrl) || QuarkFamilyDownloadPolicy.isPublicFileUrl(presented, "qk")) {
|
||||
publicDirectLink = true;
|
||||
shareLinkInfo.getOtherParam().put("publicDirectLink", true);
|
||||
shareLinkInfo.getOtherParam().put("previewUrl", QuarkFamilyDownloadPolicy.bareFileUrl(presented));
|
||||
}
|
||||
return presented;
|
||||
}
|
||||
|
||||
private String currentFileName() {
|
||||
Object info = shareLinkInfo.getOtherParam().get("fileInfo");
|
||||
if (info instanceof FileInfo file && file.getFileName() != null && !file.getFileName().isBlank()) {
|
||||
return file.getFileName();
|
||||
}
|
||||
Object name = shareLinkInfo.getOtherParam().get("fileName");
|
||||
return name == null ? "" : name.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 访客没有 Cookie,不能转存。先试接口排序下的第一个文件;
|
||||
* 若夸克返回 23018,再按体积从小到大试同目录里的其他文件。
|
||||
@@ -280,7 +353,7 @@ public class QkTool extends PanBase {
|
||||
}
|
||||
JsonObject file = files.get(index);
|
||||
String fid = file.getString("fid");
|
||||
if (fid == null || fid.isEmpty()) {
|
||||
if (fid == null || fid.isEmpty() || QuarkFamilyDownloadPolicy.knownLarge(fileSize(file))) {
|
||||
return resolveGuestDownloads(files, pwdId, stoken, index + 1, attempts);
|
||||
}
|
||||
return getShareDownloadLink(fid, pwdId, stoken, file.getString("share_fid_token"))
|
||||
@@ -764,6 +837,7 @@ public class QkTool extends PanBase {
|
||||
if (shareFidToken != null) {
|
||||
extParams.put("share_fid_token", shareFidToken);
|
||||
}
|
||||
extParams.put("size", fileSize);
|
||||
extParams.put("needDownloader", true);
|
||||
Map<String, String> dlHeaders = new HashMap<>();
|
||||
String listCookie = header.get(HttpHeaders.COOKIE);
|
||||
@@ -834,13 +908,29 @@ public class QkTool extends PanBase {
|
||||
|
||||
log.debug("夸克 parseById: fid={}, pwd_id={}, stoken={}", fid, pwdId, stoken);
|
||||
|
||||
resolveDownloadUrl(fid, pwdId, stoken, shareFidToken)
|
||||
.onSuccess(downloadUrl -> {
|
||||
Map<String, String> downloadHeaders = buildDownloadHeaders(paramJson);
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", downloadHeaders);
|
||||
shareLinkInfo.getOtherParam().put("fileName", paramJson.getString("fileName", ""));
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", true);
|
||||
promise.complete(downloadUrl);
|
||||
String fileName = paramJson.getString("fileName", "");
|
||||
Future<String> download;
|
||||
if (QuarkFamilyDownloadPolicy.knownLarge(QuarkFamilyDownloadPolicy.sizeOf(paramJson))) {
|
||||
JsonObject file = new JsonObject()
|
||||
.put("fid", fid)
|
||||
.put("share_fid_token", shareFidToken)
|
||||
.put("file_name", fileName)
|
||||
.put("size", QuarkFamilyDownloadPolicy.sizeOf(paramJson));
|
||||
download = resolveLargeFile(file, pwdId, stoken);
|
||||
} else {
|
||||
download = resolveDownloadUrl(fid, pwdId, stoken, shareFidToken);
|
||||
}
|
||||
download.onSuccess(downloadUrl -> {
|
||||
shareLinkInfo.getOtherParam().put("fileName", fileName);
|
||||
String presented = presentIfPublic(downloadUrl);
|
||||
if (publicDirectLink) {
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", new HashMap<>());
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", false);
|
||||
} else {
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", buildDownloadHeaders(paramJson));
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", true);
|
||||
}
|
||||
promise.complete(presented);
|
||||
})
|
||||
.onFailure(promise::fail);
|
||||
|
||||
@@ -904,7 +994,8 @@ public class QkTool extends PanBase {
|
||||
*/
|
||||
private Future<String> saveAndDownload(String pwdId, String stoken, String shareFid, String shareFidToken) {
|
||||
Promise<String> promise = Promise.promise();
|
||||
String fileCacheKey = pwdId + "_" + (shareFid == null ? "" : shareFid);
|
||||
String scope = QuarkAccountScope.suffix(shareLinkInfo.getOtherParam());
|
||||
String fileCacheKey = (scope == null ? "_" : scope) + ":" + pwdId + "_" + (shareFid == null ? "" : shareFid);
|
||||
|
||||
// 本地缓存命中 → 跳过转存,直接用已转存 fid 取链
|
||||
String cachedFid = savedFileCache.get(fileCacheKey);
|
||||
|
||||
@@ -0,0 +1,699 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpClientOptions;
|
||||
import io.vertx.core.http.HttpClientResponse;
|
||||
import io.vertx.core.http.HttpHeaders;
|
||||
import io.vertx.core.http.HttpMethod;
|
||||
import io.vertx.core.http.RequestOptions;
|
||||
import io.vertx.core.json.JsonArray;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.client.HttpResponse;
|
||||
import io.vertx.ext.web.client.WebClient;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 夸克 / UC 单文件下载策略。
|
||||
* <p>
|
||||
* 体积不大于 {@link #NORMAL_PARSE_MAX_BYTES}(10MiB,即 {@code 10 * 1024 * 1024},等于阈值仍走原解析)时,
|
||||
* 调用方保持现有分享下载。更大且能读到体积的文件:先用会员接口确认未过期的 SVIP/VIP,
|
||||
* 再用该账号已有的 {@code /file/download} 直链;否则只接受 H5 预览返回、并经匿名探测确认为文件字节的
|
||||
* {@code https://dl-c-* .drive.quark.cn|drive.uc.cn} 地址,附上真实文件名。
|
||||
* 预览网页、HTML、JSON、m3u8 播放列表和登录态 CDN 都不当作下载成功。
|
||||
* UC 不因为尝试 H5 就变成免登录。
|
||||
* </p>
|
||||
*/
|
||||
public final class QuarkFamilyDownloadPolicy {
|
||||
|
||||
/** 10MiB。仓库没有另一套 10MB 常量,按二进制兆字节 {@code 10 * 1024 * 1024}。 */
|
||||
public static final long NORMAL_PARSE_MAX_BYTES = 10L * 1024 * 1024;
|
||||
|
||||
private static final Set<String> PAID_TYPES = Set.of(
|
||||
"SUPER_VIP", "EXP_SVIP", "Z_VIP", "VIP", "EXP_VIP");
|
||||
private static final List<String> BARE_QUERY = List.of("auth_key", "sp", "token");
|
||||
private static final String GUEST_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
+ "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
|
||||
private static final int PROBE_PREFIX_BYTES = 64;
|
||||
|
||||
private QuarkFamilyDownloadPolicy() {
|
||||
}
|
||||
|
||||
/** 已知体积且严格大于 10MiB。缺少体积或无法解析时返回 false,调用方继续原解析。 */
|
||||
public static boolean knownLarge(long size) {
|
||||
return size > NORMAL_PARSE_MAX_BYTES && size < Long.MAX_VALUE;
|
||||
}
|
||||
|
||||
public static long sizeOf(JsonObject item) {
|
||||
if (item == null || !item.containsKey("size")) {
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
return sizeOf(item.getValue("size"));
|
||||
}
|
||||
|
||||
public static long sizeOf(Object value) {
|
||||
if (value instanceof Number number) {
|
||||
return number.longValue();
|
||||
}
|
||||
if (value instanceof String text && !text.isBlank()) {
|
||||
try {
|
||||
return Long.parseLong(text.trim());
|
||||
} catch (NumberFormatException ignored) {
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
}
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
|
||||
public static final class Membership {
|
||||
public final boolean validPaid;
|
||||
public final String memberType;
|
||||
public final Long expAtMs;
|
||||
public final String reason;
|
||||
|
||||
Membership(boolean validPaid, String memberType, Long expAtMs, String reason) {
|
||||
this.validPaid = validPaid;
|
||||
this.memberType = memberType;
|
||||
this.expAtMs = expAtMs;
|
||||
this.reason = reason;
|
||||
}
|
||||
|
||||
static Membership notPaid(String type, Long expAtMs, String reason) {
|
||||
return new Membership(false, type, expAtMs, reason);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 只认会员接口的 {@code member_type} 和 {@code exp_at}。Cookie 是否存在不参与判断。
|
||||
* 体验会员(EXP_SVIP / EXP_VIP)和 Z_VIP 在到期前算有效;NORMAL、未知档位、缺少到期时间或已到期都无效。
|
||||
*/
|
||||
public static Membership judgeMembership(JsonObject data, long nowMs) {
|
||||
if (data == null) {
|
||||
return Membership.notPaid(null, null, "会员接口没有 data");
|
||||
}
|
||||
String raw = data.getString("member_type");
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return Membership.notPaid(null, null, "会员接口没有 member_type");
|
||||
}
|
||||
String type = raw.trim().toUpperCase(Locale.ROOT);
|
||||
Long expAt = epochMillis(data.getValue("exp_at"));
|
||||
if (!PAID_TYPES.contains(type)) {
|
||||
return Membership.notPaid(type, expAt, "当前档位不是未过期的 SVIP/VIP");
|
||||
}
|
||||
if (expAt == null) {
|
||||
return Membership.notPaid(type, null, "会员接口没有 exp_at,不能确认未过期");
|
||||
}
|
||||
if (expAt <= nowMs) {
|
||||
return Membership.notPaid(type, expAt, "会员已过期");
|
||||
}
|
||||
return new Membership(true, type, expAt, null);
|
||||
}
|
||||
|
||||
static Long epochMillis(Object value) {
|
||||
Long raw = null;
|
||||
if (value instanceof Number number) {
|
||||
raw = number.longValue();
|
||||
} else if (value instanceof String text && !text.isBlank()) {
|
||||
try {
|
||||
raw = Long.parseLong(text.trim());
|
||||
} catch (NumberFormatException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (raw == null || raw <= 0) {
|
||||
return null;
|
||||
}
|
||||
return raw < 100_000_000_000L ? raw * 1000L : raw;
|
||||
}
|
||||
|
||||
public static Future<Membership> fetchMembership(WebClient client, MultiMap apiHeaders, boolean uc) {
|
||||
String url = uc
|
||||
? "https://pc-api.uc.cn/1/clouddrive/member?pr=UCBrowser&fr=pc&fetch_subscribe=true&_ch=home&fetch_identity=true"
|
||||
: "https://drive-pc.quark.cn/1/clouddrive/member?pr=ucpro&fr=pc&fetch_subscribe=true&_ch=home&fetch_identity=true";
|
||||
return fetchMembership(client, apiHeaders, url, uc);
|
||||
}
|
||||
|
||||
static Future<Membership> fetchMembership(WebClient client, MultiMap apiHeaders, String memberUrl, boolean uc) {
|
||||
String cookie = apiHeaders == null ? null : apiHeaders.get(HttpHeaders.COOKIE);
|
||||
if (cookie == null || cookie.isBlank()) {
|
||||
return Future.succeededFuture(Membership.notPaid(null, null, "未配置 Cookie"));
|
||||
}
|
||||
String referer = uc ? "https://drive.uc.cn/" : "https://pan.quark.cn/";
|
||||
String ua = apiHeaders.get(HttpHeaders.USER_AGENT);
|
||||
if (ua == null || ua.isBlank()) {
|
||||
ua = GUEST_UA;
|
||||
}
|
||||
return client.getAbs(memberUrl)
|
||||
.putHeader(HttpHeaders.COOKIE.toString(), cookie)
|
||||
.putHeader(HttpHeaders.USER_AGENT.toString(), ua)
|
||||
.putHeader(HttpHeaders.REFERER.toString(), referer)
|
||||
.timeout(10_000)
|
||||
.send()
|
||||
.map(res -> membershipFromResponse(res))
|
||||
.recover(err -> Future.succeededFuture(
|
||||
Membership.notPaid(null, null, "会员接口不可用")));
|
||||
}
|
||||
|
||||
static Membership membershipFromResponse(HttpResponse<?> res) {
|
||||
int status = res.statusCode();
|
||||
if (status == 401 || status == 403) {
|
||||
return Membership.notPaid(null, null, "会员接口拒绝访问 HTTP " + status);
|
||||
}
|
||||
String type = res.getHeader(HttpHeaders.CONTENT_TYPE.toString());
|
||||
if (type != null && type.toLowerCase(Locale.ROOT).contains("text/html")) {
|
||||
return Membership.notPaid(null, null, "会员接口返回了 HTML");
|
||||
}
|
||||
JsonObject json;
|
||||
try {
|
||||
json = res.bodyAsJsonObject();
|
||||
} catch (Exception e) {
|
||||
return Membership.notPaid(null, null, "会员接口没有返回 JSON");
|
||||
}
|
||||
if (json == null) {
|
||||
return Membership.notPaid(null, null, "会员接口没有返回 JSON");
|
||||
}
|
||||
Integer code = json.getInteger("code");
|
||||
if (code != null && code != 0) {
|
||||
return Membership.notPaid(null, null, "会员接口失败 code=" + code);
|
||||
}
|
||||
return judgeMembership(json.getJsonObject("data"), System.currentTimeMillis());
|
||||
}
|
||||
|
||||
/**
|
||||
* H5 预览签发的公开文件地址。不带登录 Cookie。探测只读响应头和最多 64 字节,不把文件收进内存。
|
||||
*/
|
||||
public static Future<String> resolveH5Download(WebClient client, Vertx vertx, String pan,
|
||||
String pwdId, String stoken, String fid,
|
||||
String fidToken, String fileName) {
|
||||
if (isBlank(fid) || isBlank(fidToken) || isBlank(pwdId) || isBlank(stoken)) {
|
||||
return Future.failedFuture("分享参数不完整,无法请求 H5 预览");
|
||||
}
|
||||
if (isBlank(fileName)) {
|
||||
return Future.failedFuture("没有真实文件名,不能把预览地址当作下载");
|
||||
}
|
||||
return requestRichText(client, pan, pwdId, stoken, fid, fidToken)
|
||||
.compose(raw -> acceptProbed(vertx, pan, raw, fileName))
|
||||
.recover(richErr -> requestVideo(client, pan, pwdId, stoken, fid, fidToken)
|
||||
.compose(raw -> acceptProbed(vertx, pan, raw, fileName))
|
||||
.recover(videoErr -> Future.failedFuture(joinReasons(richErr, videoErr))));
|
||||
}
|
||||
|
||||
private static Future<String> acceptProbed(Vertx vertx, String pan, String raw, String fileName) {
|
||||
if (raw != null && raw.toLowerCase(Locale.ROOT).contains(".m3u8")) {
|
||||
return Future.failedFuture("只得到 m3u8 播放列表,不是文件");
|
||||
}
|
||||
if (!isPublicFileUrl(raw, pan)) {
|
||||
return Future.failedFuture("预览地址不是公开文件 CDN");
|
||||
}
|
||||
return probeBody(vertx, raw, pan, 1).compose(hit -> {
|
||||
if (!hit.ok) {
|
||||
return Future.failedFuture(hit.reason);
|
||||
}
|
||||
return Future.succeededFuture(withFilename(bareFileUrl(raw), fileName));
|
||||
});
|
||||
}
|
||||
|
||||
private static Future<String> requestRichText(WebClient client, String pan, String pwdId, String stoken,
|
||||
String fid, String fidToken) {
|
||||
boolean uc = isUc(pan);
|
||||
String base = uc ? "https://pc-api.uc.cn/1/clouddrive" : "https://drive.quark.cn/1/clouddrive";
|
||||
String site = uc ? "https://drive.uc.cn" : "https://vt.quark.cn";
|
||||
return requestPreview(client, pan, base, "h5", site, "/share/sharepage/rich_text/preview",
|
||||
pwdId, stoken, fid, fidToken, false);
|
||||
}
|
||||
|
||||
private static Future<String> requestVideo(WebClient client, String pan, String pwdId, String stoken,
|
||||
String fid, String fidToken) {
|
||||
List<String[]> attempts = isUc(pan)
|
||||
? List.of(
|
||||
new String[]{"https://pc-api.uc.cn/1/clouddrive", "h5", "https://drive.uc.cn"},
|
||||
new String[]{"https://pc-api.uc.cn/1/clouddrive", "pc", "https://drive.uc.cn"})
|
||||
: List.of(
|
||||
new String[]{"https://drive.quark.cn/1/clouddrive", "h5", "https://vt.quark.cn"},
|
||||
new String[]{"https://drive.quark.cn/1/clouddrive", "pc", "https://pan.quark.cn"},
|
||||
new String[]{"https://drive-h.quark.cn/1/clouddrive", "h5", "https://pan.quark.cn"});
|
||||
return requestVideoAt(client, pan, attempts, 0, pwdId, stoken, fid, fidToken, null);
|
||||
}
|
||||
|
||||
private static Future<String> requestVideoAt(WebClient client, String pan, List<String[]> attempts, int index,
|
||||
String pwdId, String stoken, String fid, String fidToken,
|
||||
Throwable last) {
|
||||
if (index >= attempts.size()) {
|
||||
return Future.failedFuture(last == null ? new IllegalStateException("视频预览没有公开文件地址") : last);
|
||||
}
|
||||
String[] attempt = attempts.get(index);
|
||||
return requestPreview(client, pan, attempt[0], attempt[1], attempt[2],
|
||||
"/share/sharepage/video/preview", pwdId, stoken, fid, fidToken, true)
|
||||
.recover(err -> requestVideoAt(client, pan, attempts, index + 1, pwdId, stoken, fid, fidToken, err));
|
||||
}
|
||||
|
||||
private static Future<String> requestPreview(WebClient client, String pan, String base, String fr, String site,
|
||||
String path, String pwdId, String stoken, String fid,
|
||||
String fidToken, boolean video) {
|
||||
String pr = isUc(pan) ? "UCBrowser" : "ucpro";
|
||||
var req = client.getAbs(base + path)
|
||||
.putHeader(HttpHeaders.USER_AGENT.toString(), GUEST_UA)
|
||||
.putHeader(HttpHeaders.ACCEPT.toString(), "application/json, text/plain, */*")
|
||||
.putHeader(HttpHeaders.REFERER.toString(), site + "/")
|
||||
.putHeader("Origin", site)
|
||||
.putHeader("x-clouddrive-st", "null")
|
||||
.addQueryParam("fid", fid)
|
||||
.addQueryParam("fid_token", fidToken)
|
||||
.addQueryParam("fr", fr)
|
||||
.addQueryParam("pr", pr)
|
||||
.addQueryParam("pwd_id", pwdId)
|
||||
.addQueryParam("stoken", stoken);
|
||||
if (video) {
|
||||
req.addQueryParam("resolution", "low,normal,high,super,2k,4k");
|
||||
req.addQueryParam("supports", "fmp4,m3u8,dolby_vision");
|
||||
}
|
||||
return req.timeout(10_000).send().compose(res -> interpretPreview(res, pan, video));
|
||||
}
|
||||
|
||||
static Future<String> interpretPreview(HttpResponse<?> res, String pan, boolean video) {
|
||||
int status = res.statusCode();
|
||||
String contentType = res.getHeader(HttpHeaders.CONTENT_TYPE.toString());
|
||||
if (contentType != null && contentType.toLowerCase(Locale.ROOT).contains("text/html")) {
|
||||
return Future.failedFuture("H5 预览返回了 HTML 页面,不是文件");
|
||||
}
|
||||
if (status >= 400) {
|
||||
return Future.failedFuture("H5 预览 HTTP " + status);
|
||||
}
|
||||
JsonObject json;
|
||||
try {
|
||||
json = res.bodyAsJsonObject();
|
||||
} catch (Exception e) {
|
||||
return Future.failedFuture("H5 预览不是 JSON");
|
||||
}
|
||||
if (json == null) {
|
||||
return Future.failedFuture("H5 预览不是 JSON");
|
||||
}
|
||||
int code = json.getInteger("code", -1);
|
||||
if (code != 0) {
|
||||
return Future.failedFuture("H5 预览失败: " + sanitize(json.getString("message", "code=" + code)));
|
||||
}
|
||||
JsonObject data = json.getJsonObject("data", new JsonObject());
|
||||
if (video) {
|
||||
String picked = pickProgressiveFileUrl(data, pan);
|
||||
if (isBlank(picked)) {
|
||||
return Future.failedFuture("视频预览没有公开文件地址");
|
||||
}
|
||||
return Future.succeededFuture(picked);
|
||||
}
|
||||
String download = data.getString("download_url", "");
|
||||
if (isBlank(download)) {
|
||||
return Future.failedFuture("H5 预览没有 download_url");
|
||||
}
|
||||
return Future.succeededFuture(download);
|
||||
}
|
||||
|
||||
/** 从视频预览里选公开 CDN 上的渐进文件。m3u8 和登录态节点丢掉。 */
|
||||
static String pickProgressiveFileUrl(JsonObject data, String pan) {
|
||||
if (data == null) {
|
||||
return "";
|
||||
}
|
||||
String best = "";
|
||||
int bestWidth = -1;
|
||||
JsonArray list = data.getJsonArray("video_list");
|
||||
if (list != null) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
Object raw = list.getValue(i);
|
||||
if (!(raw instanceof JsonObject item)) {
|
||||
continue;
|
||||
}
|
||||
JsonObject info = item.getJsonObject("video_info");
|
||||
String candidate = publicFileCandidate(info == null ? "" : info.getString("url", ""), pan);
|
||||
if (isBlank(candidate)) {
|
||||
candidate = publicFileCandidate(item.getString("url", ""), pan);
|
||||
}
|
||||
if (isBlank(candidate) || candidate.toLowerCase(Locale.ROOT).contains(".m3u8")) {
|
||||
continue;
|
||||
}
|
||||
int width = widthOf(info != null ? info : item);
|
||||
if (width >= bestWidth) {
|
||||
best = candidate;
|
||||
bestWidth = width;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isBlank(best)) {
|
||||
String direct = publicFileCandidate(data.getString("download_url", ""), pan);
|
||||
if (!isBlank(direct) && !direct.toLowerCase(Locale.ROOT).contains(".m3u8")) {
|
||||
best = direct;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static String publicFileCandidate(String url, String pan) {
|
||||
if (isBlank(url) || !isPublicFileUrl(bareFileUrl(url), pan)) {
|
||||
return "";
|
||||
}
|
||||
return withoutFilename(url);
|
||||
}
|
||||
|
||||
private static int widthOf(JsonObject obj) {
|
||||
if (obj == null || !obj.containsKey("width")) {
|
||||
return 0;
|
||||
}
|
||||
Object value = obj.getValue("width");
|
||||
if (value instanceof Number number) {
|
||||
return number.intValue();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 公开文件 CDN。登录态节点(dl-pc、dl-guest、*.u-drive)和预览网页都不是。
|
||||
*/
|
||||
public static boolean isPublicFileUrl(String url, String pan) {
|
||||
if (isBlank(url) || !url.startsWith("https://")) {
|
||||
return false;
|
||||
}
|
||||
String host = hostOf(url);
|
||||
if (host == null) {
|
||||
return false;
|
||||
}
|
||||
String suffix = isUc(pan) ? ".drive.uc.cn" : ".drive.quark.cn";
|
||||
return host.startsWith("dl-c-")
|
||||
&& host.endsWith(suffix)
|
||||
&& !host.contains(".u-drive.")
|
||||
&& host.length() > "dl-c-".length() + suffix.length();
|
||||
}
|
||||
|
||||
private static String hostOf(String url) {
|
||||
int start = "https://".length();
|
||||
int end = url.length();
|
||||
for (int i = start; i < url.length(); i++) {
|
||||
char c = url.charAt(i);
|
||||
if (c == '/' || c == '?' || c == '#') {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (end <= start) {
|
||||
return null;
|
||||
}
|
||||
String host = url.substring(start, end);
|
||||
int colon = host.indexOf(':');
|
||||
if (colon >= 0) {
|
||||
host = host.substring(0, colon);
|
||||
}
|
||||
return host.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
public static String bareFileUrl(String url) {
|
||||
if (isBlank(url) || !url.startsWith("http")) {
|
||||
return url;
|
||||
}
|
||||
int q = url.indexOf('?');
|
||||
if (q < 0) {
|
||||
return url;
|
||||
}
|
||||
String base = url.substring(0, q);
|
||||
StringBuilder kept = new StringBuilder();
|
||||
for (String pair : url.substring(q + 1).split("&")) {
|
||||
int eq = pair.indexOf('=');
|
||||
String key = eq >= 0 ? pair.substring(0, eq) : pair;
|
||||
if (BARE_QUERY.contains(key)) {
|
||||
kept.append(kept.length() == 0 ? '?' : '&').append(pair);
|
||||
}
|
||||
}
|
||||
return base + kept;
|
||||
}
|
||||
|
||||
public static String withoutFilename(String url) {
|
||||
if (isBlank(url) || url.indexOf('?') < 0 || !url.contains("filename=")) {
|
||||
return url;
|
||||
}
|
||||
int q = url.indexOf('?');
|
||||
String base = url.substring(0, q);
|
||||
StringBuilder kept = new StringBuilder();
|
||||
for (String pair : url.substring(q + 1).split("&")) {
|
||||
int eq = pair.indexOf('=');
|
||||
String key = eq >= 0 ? pair.substring(0, eq) : pair;
|
||||
if ("filename".equals(key)) {
|
||||
continue;
|
||||
}
|
||||
kept.append(kept.length() == 0 ? '?' : '&').append(pair);
|
||||
}
|
||||
return base + kept;
|
||||
}
|
||||
|
||||
/** 登录态接口如果实际给了公开 CDN,去掉埋点并补上文件名,调用方不要再附带 Cookie / Referer。 */
|
||||
public static String presentPublicDownload(String url, String pan, String fileName) {
|
||||
if (!isPublicFileUrl(bareFileUrl(url), pan)) {
|
||||
return url;
|
||||
}
|
||||
String bare = bareFileUrl(url);
|
||||
if (isBlank(fileName) || bare.contains("filename=")) {
|
||||
return bare;
|
||||
}
|
||||
return withFilename(bare, fileName);
|
||||
}
|
||||
|
||||
/** CDN 用 {@code filename} 生成 Content-Disposition。跨域时浏览器会忽略 a[download]。 */
|
||||
public static String withFilename(String url, String fileName) {
|
||||
if (isBlank(url) || isBlank(fileName)) {
|
||||
return url;
|
||||
}
|
||||
String encoded = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
return url + (url.contains("?") ? "&" : "?") + "filename=" + encoded;
|
||||
}
|
||||
|
||||
static final class ProbeHit {
|
||||
final boolean ok;
|
||||
final String reason;
|
||||
final int prefixLength;
|
||||
|
||||
ProbeHit(boolean ok, String reason, int prefixLength) {
|
||||
this.ok = ok;
|
||||
this.reason = reason;
|
||||
this.prefixLength = prefixLength;
|
||||
}
|
||||
|
||||
static ProbeHit ok(int prefixLength) {
|
||||
return new ProbeHit(true, null, prefixLength);
|
||||
}
|
||||
|
||||
static ProbeHit fail(String reason) {
|
||||
return new ProbeHit(false, reason, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 匿名探测。只连接已经通过 {@link #isPublicFileUrl} 的地址;测试可直接调用以检查截断和 HTML 判断。
|
||||
* 读满 {@value #PROBE_PREFIX_BYTES} 字节后立刻断开,不缓冲整份文件。
|
||||
*/
|
||||
static Future<ProbeHit> probeBody(Vertx vertx, String url, String pan, int redirectsLeft) {
|
||||
if (isBlank(url) || !(url.startsWith("https://") || url.startsWith("http://127.0.0.1")
|
||||
|| url.startsWith("http://localhost"))) {
|
||||
return Future.succeededFuture(ProbeHit.fail("拒绝探测非公开文件地址"));
|
||||
}
|
||||
if (url.startsWith("https://") && !isPublicFileUrl(url, pan)) {
|
||||
return Future.succeededFuture(ProbeHit.fail("拒绝探测非公开文件地址"));
|
||||
}
|
||||
HttpClient client = vertx.createHttpClient(new HttpClientOptions()
|
||||
.setConnectTimeout(8_000)
|
||||
.setIdleTimeout(10)
|
||||
.setKeepAlive(false)
|
||||
.setMaxHeaderSize(16 * 1024)
|
||||
.setTrustAll(false)
|
||||
.setVerifyHost(true));
|
||||
RequestOptions options = new RequestOptions()
|
||||
.setMethod(HttpMethod.GET)
|
||||
.setAbsoluteURI(url)
|
||||
.setTimeout(8_000);
|
||||
Promise<ProbeHit> promise = Promise.promise();
|
||||
client.request(options).compose(request -> {
|
||||
request.setFollowRedirects(false);
|
||||
request.putHeader(HttpHeaders.USER_AGENT.toString(), GUEST_UA);
|
||||
request.putHeader(HttpHeaders.ACCEPT.toString(), "*/*");
|
||||
request.putHeader("Range", "bytes=0-15");
|
||||
return request.send();
|
||||
}).compose(resp -> readPrefix(resp).compose(prefix -> {
|
||||
int status = resp.statusCode();
|
||||
if (status >= 300 && status < 400 && redirectsLeft > 0) {
|
||||
String location = resp.getHeader(HttpHeaders.LOCATION.toString());
|
||||
if (location != null && isPublicFileUrl(location, pan)) {
|
||||
return probeBody(vertx, location, pan, redirectsLeft - 1);
|
||||
}
|
||||
return Future.succeededFuture(ProbeHit.fail("跳转目标不是公开文件 CDN"));
|
||||
}
|
||||
return Future.succeededFuture(judgeProbe(status,
|
||||
resp.getHeader(HttpHeaders.CONTENT_TYPE.toString()),
|
||||
resp.getHeader("Content-Range"),
|
||||
resp.getHeader(HttpHeaders.CONTENT_LENGTH.toString()),
|
||||
prefix));
|
||||
})).onComplete(ar -> {
|
||||
client.close();
|
||||
if (ar.succeeded()) {
|
||||
promise.tryComplete(ar.result());
|
||||
} else {
|
||||
promise.tryComplete(ProbeHit.fail("探测失败"));
|
||||
}
|
||||
});
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
private static Future<Buffer> readPrefix(HttpClientResponse resp) {
|
||||
Promise<Buffer> promise = Promise.promise();
|
||||
Buffer prefix = Buffer.buffer();
|
||||
boolean[] finished = {false};
|
||||
Runnable finish = () -> {
|
||||
if (finished[0]) {
|
||||
return;
|
||||
}
|
||||
finished[0] = true;
|
||||
try {
|
||||
resp.request().reset();
|
||||
} catch (Exception ignored) {
|
||||
// 对端已结束时 reset 会失败,前缀已经够用。
|
||||
}
|
||||
promise.tryComplete(prefix);
|
||||
};
|
||||
resp.handler(buf -> {
|
||||
if (prefix.length() < PROBE_PREFIX_BYTES) {
|
||||
int n = Math.min(buf.length(), PROBE_PREFIX_BYTES - prefix.length());
|
||||
prefix.appendBuffer(buf, 0, n);
|
||||
}
|
||||
if (prefix.length() >= PROBE_PREFIX_BYTES) {
|
||||
finish.run();
|
||||
}
|
||||
});
|
||||
resp.endHandler(v -> finish.run());
|
||||
resp.exceptionHandler(err -> {
|
||||
if (!finished[0]) {
|
||||
promise.tryFail(err);
|
||||
}
|
||||
});
|
||||
resp.fetch(PROBE_PREFIX_BYTES);
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
static ProbeHit judgeProbe(int status, String contentType, String contentRange, String contentLength, Buffer prefix) {
|
||||
if (status != 200 && status != 206) {
|
||||
return ProbeHit.fail("HTTP " + status);
|
||||
}
|
||||
if (looksLikeHtml(contentType, prefix)) {
|
||||
return ProbeHit.fail("响应是 HTML,不是文件");
|
||||
}
|
||||
if (contentType != null && contentType.toLowerCase(Locale.ROOT).contains("json")) {
|
||||
return ProbeHit.fail("响应是 JSON,不是文件");
|
||||
}
|
||||
boolean ranged = status == 206 && contentRange != null && !contentRange.isBlank();
|
||||
long length = -1;
|
||||
if (contentLength != null && !contentLength.isBlank()) {
|
||||
try {
|
||||
length = Long.parseLong(contentLength.trim());
|
||||
} catch (NumberFormatException ignored) {
|
||||
length = -1;
|
||||
}
|
||||
}
|
||||
if (!ranged && length == 0) {
|
||||
return ProbeHit.fail("响应没有文件内容");
|
||||
}
|
||||
if (!ranged && (contentType == null || contentType.isBlank())) {
|
||||
return ProbeHit.fail("响应没有 Content-Type,不能确认是文件");
|
||||
}
|
||||
return ProbeHit.ok(prefix == null ? 0 : prefix.length());
|
||||
}
|
||||
|
||||
static boolean looksLikeHtml(String contentType, Buffer prefix) {
|
||||
if (contentType != null) {
|
||||
String type = contentType.toLowerCase(Locale.ROOT);
|
||||
if (type.contains("text/html") || type.contains("application/xhtml")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (prefix == null || prefix.length() == 0) {
|
||||
return false;
|
||||
}
|
||||
int n = Math.min(prefix.length(), 32);
|
||||
String head = prefix.getString(0, n, "UTF-8").stripLeading().toLowerCase(Locale.ROOT);
|
||||
return head.startsWith("<!doctype") || head.startsWith("<html") || head.startsWith("<head");
|
||||
}
|
||||
|
||||
/**
|
||||
* 公开文件地址不沿用目录参数里的账号请求头。返回值表示浏览器是否必须改走下载器。
|
||||
*/
|
||||
public static boolean prepareDownloader(Map<String, String> headers, boolean paramNeedsDownloader, boolean publicDirect) {
|
||||
if (publicDirect) {
|
||||
if (headers != null) {
|
||||
headers.clear();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return paramNeedsDownloader || (headers != null && !headers.isEmpty());
|
||||
}
|
||||
|
||||
public static String largeFileError(String pan, Throwable directError, Throwable h5Error) {
|
||||
boolean uc = isUc(pan);
|
||||
StringBuilder message = new StringBuilder();
|
||||
if (uc) {
|
||||
message.append("UC 超过 10MiB(").append(NORMAL_PARSE_MAX_BYTES)
|
||||
.append(" 字节)的文件不能免登录下载。当前没有未过期的 SVIP/VIP,");
|
||||
} else {
|
||||
message.append("夸克超过 10MiB(").append(NORMAL_PARSE_MAX_BYTES)
|
||||
.append(" 字节)的文件没有可用的未过期 SVIP/VIP 直链。");
|
||||
}
|
||||
message.append("H5 预览也没有返回可下载的文件地址。");
|
||||
if (h5Error != null) {
|
||||
message.append(" 预览: ").append(sanitize(h5Error.getMessage()));
|
||||
}
|
||||
if (directError != null) {
|
||||
message.append(" 账号直链: ").append(sanitize(directError.getMessage()));
|
||||
}
|
||||
if (uc) {
|
||||
message.append(" 请配置未过期的 UC SVIP/VIP Cookie:auths.uc.cookie。");
|
||||
} else {
|
||||
message.append(" 请配置未过期的夸克 SVIP/VIP Cookie:auths.qk.cookie。普通或已过期账号不会当作会员。");
|
||||
}
|
||||
return message.toString();
|
||||
}
|
||||
|
||||
static String sanitize(String message) {
|
||||
if (message == null || message.isBlank()) {
|
||||
return "无详情";
|
||||
}
|
||||
String text = message.replaceAll("(?i)(cookie|__pus|__puus|__kp|__kps|__uid)=[^\\s;&,]+", "$1=***");
|
||||
String lower = text.toLowerCase(Locale.ROOT);
|
||||
if (lower.contains("<html") || lower.contains("<!doctype") || lower.contains("<head")) {
|
||||
return "上游返回了 HTML 页面";
|
||||
}
|
||||
if (text.length() > 180) {
|
||||
return text.substring(0, 180);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
private static String joinReasons(Throwable first, Throwable second) {
|
||||
String a = first == null ? "" : sanitize(first.getMessage());
|
||||
String b = second == null ? "" : sanitize(second.getMessage());
|
||||
if (a.isBlank()) {
|
||||
return b;
|
||||
}
|
||||
if (b.isBlank() || b.equals(a)) {
|
||||
return a;
|
||||
}
|
||||
return a + ";" + b;
|
||||
}
|
||||
|
||||
private static boolean isUc(String pan) {
|
||||
return pan != null && pan.equalsIgnoreCase("uc");
|
||||
}
|
||||
|
||||
private static boolean isBlank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.PanBase;
|
||||
import cn.qaiu.parser.TokenCache;
|
||||
import cn.qaiu.util.CommonUtils;
|
||||
import cn.qaiu.util.CookieUtils;
|
||||
import cn.qaiu.util.DateTimeUtils;
|
||||
import cn.qaiu.util.FileSizeConverter;
|
||||
import cn.qaiu.util.HeaderUtils;
|
||||
import cn.qaiu.util.QuarkAccountScope;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Promise;
|
||||
@@ -28,10 +31,7 @@ import java.util.Map;
|
||||
*/
|
||||
public class UcTool extends PanBase {
|
||||
private static final String API_URL_PREFIX = "https://pc-api.uc.cn/1/clouddrive/";
|
||||
|
||||
// 静态变量:缓存 __puus cookie 和过期时间
|
||||
private static volatile String cachedPuus = null;
|
||||
private static volatile long puusExpireTime = 0;
|
||||
|
||||
// __puus 有效期,默认 55 分钟(服务器实际 1 小时过期,提前 5 分钟刷新)
|
||||
private static final long PUUS_TTL_MS = 55 * 60 * 1000L;
|
||||
|
||||
@@ -67,9 +67,17 @@ public class UcTool extends PanBase {
|
||||
|
||||
// 保存 auths 引用,用于更新 cookie
|
||||
private MultiMap auths;
|
||||
private final String cacheKey;
|
||||
/** 本次解析得到的是不带账号的公开文件地址。UC 大文件没有这条地址时不能当成免登录成功。 */
|
||||
private boolean publicDirectLink;
|
||||
|
||||
public UcTool(ShareLinkInfo shareLinkInfo) {
|
||||
super(shareLinkInfo);
|
||||
String accountId = QuarkAccountScope.suffix(shareLinkInfo.getOtherParam());
|
||||
if (accountId == null) {
|
||||
accountId = "_default";
|
||||
}
|
||||
this.cacheKey = TokenCache.key("uc", accountId);
|
||||
// 参考其它网盘实现,从认证配置中取 cookie 放到请求头
|
||||
if (shareLinkInfo.getOtherParam() != null && shareLinkInfo.getOtherParam().containsKey("auths")) {
|
||||
auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
|
||||
@@ -77,18 +85,20 @@ public class UcTool extends PanBase {
|
||||
if (cookie != null && !cookie.isEmpty()) {
|
||||
// 过滤出 UC 网盘所需的 cookie 字段
|
||||
cookie = CookieUtils.filterUcQuarkCookie(cookie);
|
||||
|
||||
// 如果有缓存的 __puus 且未过期,使用缓存的值更新 cookie
|
||||
if (cachedPuus != null && System.currentTimeMillis() < puusExpireTime) {
|
||||
|
||||
// 按账号读取 __puus,避免把别的账号的会话写进当前请求
|
||||
String cachedPuus = TokenCache.getToken(cacheKey);
|
||||
long puusExpire = TokenCache.getExpire(cacheKey);
|
||||
if (cachedPuus != null && System.currentTimeMillis() < puusExpire) {
|
||||
cookie = CookieUtils.updateCookieValue(cookie, "__puus", cachedPuus);
|
||||
log.debug("UC: 使用缓存的 __puus (剩余有效期: {}s)", (puusExpireTime - System.currentTimeMillis()) / 1000);
|
||||
log.debug("UC: 使用缓存的 __puus (剩余有效期: {}s)", (puusExpire - System.currentTimeMillis()) / 1000);
|
||||
}
|
||||
header.set(HttpHeaders.COOKIE, cookie);
|
||||
// 同步更新 auths
|
||||
auths.set("cookie", cookie);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 如果 __puus 已过期或不存在,触发异步刷新
|
||||
if (needRefreshPuus()) {
|
||||
log.debug("UC: __puus 需要刷新,触发异步刷新");
|
||||
@@ -110,7 +120,7 @@ public class UcTool extends PanBase {
|
||||
return false;
|
||||
}
|
||||
// 缓存过期或不存在时需要刷新
|
||||
return cachedPuus == null || System.currentTimeMillis() >= puusExpireTime;
|
||||
return TokenCache.getToken(cacheKey) == null || System.currentTimeMillis() >= TokenCache.getExpire(cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -164,11 +174,10 @@ public class UcTool extends PanBase {
|
||||
auths.set("cookie", updatedCookie);
|
||||
}
|
||||
|
||||
// 更新静态缓存
|
||||
cachedPuus = newPuus;
|
||||
puusExpireTime = System.currentTimeMillis() + PUUS_TTL_MS;
|
||||
|
||||
log.info("UC: __puus cookie 刷新成功,有效期至: {}ms", puusExpireTime);
|
||||
TokenCache.putToken(cacheKey, newPuus);
|
||||
TokenCache.putExpire(cacheKey, System.currentTimeMillis() + PUUS_TTL_MS);
|
||||
|
||||
log.info("UC: __puus cookie 刷新成功,有效期至: {}ms", TokenCache.getExpire(cacheKey));
|
||||
refreshPromise.complete(true);
|
||||
} else {
|
||||
log.debug("UC: 响应中未包含 __puus,可能 cookie 仍然有效");
|
||||
@@ -242,35 +251,16 @@ public class UcTool extends PanBase {
|
||||
log.warn("UC 提取文件信息失败,继续解析: {}", e.getMessage());
|
||||
}
|
||||
|
||||
// 第三次请求获取下载链接
|
||||
var bodyJson = JsonObject.of()
|
||||
.put("fids", JsonArray.of(info.getString("fid")))
|
||||
.put("pwd_id", dataKey)
|
||||
.put("stoken", stoken)
|
||||
.put("fids_token", JsonArray.of(info.getString("share_fid_token")));
|
||||
client.postAbs(THIRD_REQUEST_URL)
|
||||
.putHeaders(header)
|
||||
.sendJsonObject(bodyJson)
|
||||
.onSuccess(res3 -> {
|
||||
log.debug("第三阶段 {}", res3.body());
|
||||
var resJson3 = res3.bodyAsJsonObject();
|
||||
if (resJson3.getInteger("code") != 0) {
|
||||
fail(FIRST_REQUEST_URL + " 返回异常: " + resJson2);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JsonArray dataList = resJson3.getJsonArray("data");
|
||||
if (dataList == null || dataList.isEmpty()) {
|
||||
fail("UC API 返回的下载链接列表为空");
|
||||
return;
|
||||
}
|
||||
String downloadUrl = dataList.getJsonObject(0).getString("download_url");
|
||||
// UC 需配合下载器(带 cookie),保存下载请求头
|
||||
completeWithMeta(downloadUrl, buildDownloadHeaders(null));
|
||||
} catch (Exception e) {
|
||||
fail("解析 UC 下载链接失败: " + e.getMessage());
|
||||
}
|
||||
}).onFailure(handleFail(THIRD_REQUEST_URL));
|
||||
String fid = info.getString("fid");
|
||||
String shareFidToken = info.getString("share_fid_token");
|
||||
Future<String> download;
|
||||
if (QuarkFamilyDownloadPolicy.knownLarge(QuarkFamilyDownloadPolicy.sizeOf(info))) {
|
||||
download = resolveUcLarge(fid, dataKey, stoken, shareFidToken, info.getString("file_name"));
|
||||
} else {
|
||||
download = requestUcDownload(fid, dataKey, stoken, shareFidToken);
|
||||
}
|
||||
download.onSuccess(this::finishUcParse)
|
||||
.onFailure(t -> fail(t.getMessage() == null ? "解析失败" : t.getMessage()));
|
||||
} catch (Exception e) {
|
||||
fail("解析 UC 文件信息失败: " + e.getMessage());
|
||||
}
|
||||
@@ -281,6 +271,108 @@ public class UcTool extends PanBase {
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
/**
|
||||
* 大于 10MiB 才检查会员。有效 SVIP/VIP 仍走原来的账号 {@code /file/download};
|
||||
* 否则只接受探测通过的 H5 文件地址。没有该地址时明确失败,不把 UC 说成免登录。
|
||||
*/
|
||||
private Future<String> resolveUcLarge(String fid, String pwdId, String stoken, String shareFidToken, String fileName) {
|
||||
if (fid == null || fid.isEmpty()) {
|
||||
return Future.failedFuture(QuarkFamilyDownloadPolicy.largeFileError("uc", null,
|
||||
new IllegalStateException("缺少 fid")));
|
||||
}
|
||||
return QuarkFamilyDownloadPolicy.fetchMembership(client, header, true)
|
||||
.compose(member -> {
|
||||
if (!member.validPaid) {
|
||||
return ucH5(pwdId, stoken, fid, shareFidToken, fileName)
|
||||
.recover(h5Error -> Future.failedFuture(
|
||||
QuarkFamilyDownloadPolicy.largeFileError("uc", null, h5Error)));
|
||||
}
|
||||
return requestUcDownload(fid, pwdId, stoken, shareFidToken)
|
||||
.recover(directError -> ucH5(pwdId, stoken, fid, shareFidToken, fileName)
|
||||
.recover(h5Error -> Future.failedFuture(
|
||||
QuarkFamilyDownloadPolicy.largeFileError("uc", directError, h5Error))));
|
||||
});
|
||||
}
|
||||
|
||||
private Future<String> ucH5(String pwdId, String stoken, String fid, String shareFidToken, String fileName) {
|
||||
return QuarkFamilyDownloadPolicy.resolveH5Download(clientNoRedirects, WebClientVertxInit.get(),
|
||||
"uc", pwdId, stoken, fid, shareFidToken, fileName)
|
||||
.map(url -> {
|
||||
publicDirectLink = true;
|
||||
shareLinkInfo.getOtherParam().put("publicDirectLink", true);
|
||||
shareLinkInfo.getOtherParam().put("previewUrl", QuarkFamilyDownloadPolicy.bareFileUrl(url));
|
||||
return url;
|
||||
});
|
||||
}
|
||||
|
||||
private Future<String> requestUcDownload(String fid, String pwdId, String stoken, String shareFidToken) {
|
||||
Promise<String> downloadPromise = Promise.promise();
|
||||
JsonObject bodyJson = JsonObject.of()
|
||||
.put("fids", JsonArray.of(fid))
|
||||
.put("pwd_id", pwdId)
|
||||
.put("stoken", stoken);
|
||||
if (shareFidToken != null && !shareFidToken.isEmpty()) {
|
||||
bodyJson.put("fids_token", JsonArray.of(shareFidToken));
|
||||
}
|
||||
client.postAbs(THIRD_REQUEST_URL)
|
||||
.putHeaders(header)
|
||||
.sendJsonObject(bodyJson)
|
||||
.onSuccess(res3 -> {
|
||||
log.debug("UC 下载接口 {}", res3.body());
|
||||
JsonObject resJson3 = res3.bodyAsJsonObject();
|
||||
if (resJson3.getInteger("code") == null || resJson3.getInteger("code") != 0) {
|
||||
downloadPromise.fail(THIRD_REQUEST_URL + " 返回异常: " + resJson3);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JsonArray dataList = resJson3.getJsonArray("data");
|
||||
if (dataList == null || dataList.isEmpty()) {
|
||||
downloadPromise.fail("UC API 返回的下载链接列表为空");
|
||||
return;
|
||||
}
|
||||
String downloadUrl = dataList.getJsonObject(0).getString("download_url");
|
||||
if (downloadUrl == null || downloadUrl.isEmpty()) {
|
||||
downloadPromise.fail("未找到下载链接");
|
||||
return;
|
||||
}
|
||||
downloadPromise.complete(downloadUrl);
|
||||
} catch (Exception e) {
|
||||
downloadPromise.fail("解析 UC 下载链接失败: " + e.getMessage());
|
||||
}
|
||||
})
|
||||
.onFailure(t -> downloadPromise.fail("请求下载链接失败: " + t.getMessage()));
|
||||
return downloadPromise.future();
|
||||
}
|
||||
|
||||
private void finishUcParse(String downloadUrl) {
|
||||
String presented = presentUcIfPublic(downloadUrl);
|
||||
if (publicDirectLink) {
|
||||
completeWithMeta(presented, Map.of());
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", false);
|
||||
return;
|
||||
}
|
||||
completeWithMeta(presented, buildDownloadHeaders(null));
|
||||
}
|
||||
|
||||
private String presentUcIfPublic(String downloadUrl) {
|
||||
String presented = QuarkFamilyDownloadPolicy.presentPublicDownload(downloadUrl, "uc", currentUcFileName());
|
||||
if (!presented.equals(downloadUrl) || QuarkFamilyDownloadPolicy.isPublicFileUrl(presented, "uc")) {
|
||||
publicDirectLink = true;
|
||||
shareLinkInfo.getOtherParam().put("publicDirectLink", true);
|
||||
shareLinkInfo.getOtherParam().put("previewUrl", QuarkFamilyDownloadPolicy.bareFileUrl(presented));
|
||||
}
|
||||
return presented;
|
||||
}
|
||||
|
||||
private String currentUcFileName() {
|
||||
Object info = shareLinkInfo.getOtherParam().get("fileInfo");
|
||||
if (info instanceof FileInfo file && file.getFileName() != null && !file.getFileName().isBlank()) {
|
||||
return file.getFileName();
|
||||
}
|
||||
Object name = shareLinkInfo.getOtherParam().get("fileName");
|
||||
return name == null ? "" : name.toString();
|
||||
}
|
||||
|
||||
// 目录解析
|
||||
@Override
|
||||
public Future<List<FileInfo>> parseFileList() {
|
||||
@@ -461,6 +553,7 @@ public class UcTool extends PanBase {
|
||||
if (shareFidToken != null) {
|
||||
extParams.put("share_fid_token", shareFidToken);
|
||||
}
|
||||
extParams.put("size", fileSize);
|
||||
extParams.put("needDownloader", true);
|
||||
Map<String, String> dlHeaders = new HashMap<>();
|
||||
String listCookie = header.get(HttpHeaders.COOKIE);
|
||||
@@ -531,49 +624,27 @@ public class UcTool extends PanBase {
|
||||
}
|
||||
|
||||
log.debug("UC parseById: fid={}, pwd_id={}, stoken={}", fid, pwdId, stoken);
|
||||
|
||||
// 调用第三次请求获取下载链接
|
||||
JsonObject bodyJson = JsonObject.of()
|
||||
.put("fids", JsonArray.of(fid))
|
||||
.put("pwd_id", pwdId)
|
||||
.put("stoken", stoken);
|
||||
|
||||
if (shareFidToken != null && !shareFidToken.isEmpty()) {
|
||||
bodyJson.put("fids_token", JsonArray.of(shareFidToken));
|
||||
|
||||
String fileName = paramJson.getString("fileName", "");
|
||||
Future<String> download;
|
||||
if (QuarkFamilyDownloadPolicy.knownLarge(QuarkFamilyDownloadPolicy.sizeOf(paramJson))) {
|
||||
download = resolveUcLarge(fid, pwdId, stoken, shareFidToken, fileName);
|
||||
} else {
|
||||
download = requestUcDownload(fid, pwdId, stoken, shareFidToken);
|
||||
}
|
||||
|
||||
client.postAbs(THIRD_REQUEST_URL)
|
||||
.putHeaders(header)
|
||||
.sendJsonObject(bodyJson)
|
||||
.onSuccess(res -> {
|
||||
log.debug("UC parseById 响应: {}", res.body());
|
||||
JsonObject resJson = res.bodyAsJsonObject();
|
||||
if (resJson.getInteger("code") != 0) {
|
||||
promise.fail(THIRD_REQUEST_URL + " 返回异常: " + resJson);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
JsonArray dataList = resJson.getJsonArray("data");
|
||||
if (dataList == null || dataList.isEmpty()) {
|
||||
promise.fail("UC API 返回的下载链接列表为空");
|
||||
return;
|
||||
}
|
||||
String downloadUrl = dataList.getJsonObject(0).getString("download_url");
|
||||
if (downloadUrl == null || downloadUrl.isEmpty()) {
|
||||
promise.fail("未找到下载链接");
|
||||
return;
|
||||
}
|
||||
// 存储下载请求头,供目录解析 getFileDownInfo 接口使用
|
||||
// 优先用当前会话 cookie;缺失时回退入口参数中已带的 cookie
|
||||
Map<String, String> downloadHeaders = buildDownloadHeaders(paramJson);
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", downloadHeaders);
|
||||
shareLinkInfo.getOtherParam().put("fileName", paramJson.getString("fileName", ""));
|
||||
promise.complete(downloadUrl);
|
||||
} catch (Exception e) {
|
||||
promise.fail("解析 UC 下载链接失败: " + e.getMessage());
|
||||
download.onSuccess(downloadUrl -> {
|
||||
shareLinkInfo.getOtherParam().put("fileName", fileName);
|
||||
String presented = presentUcIfPublic(downloadUrl);
|
||||
if (publicDirectLink) {
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", new HashMap<>());
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", false);
|
||||
} else {
|
||||
shareLinkInfo.getOtherParam().put("downloadHeaders", buildDownloadHeaders(paramJson));
|
||||
shareLinkInfo.getOtherParam().put("needDownloader", true);
|
||||
}
|
||||
promise.complete(presented);
|
||||
})
|
||||
.onFailure(t -> promise.fail("请求下载链接失败: " + t.getMessage()));
|
||||
.onFailure(t -> promise.fail(t.getMessage() == null ? "请求下载链接失败" : t.getMessage()));
|
||||
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package cn.qaiu.util;
|
||||
|
||||
import io.vertx.core.MultiMap;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 夸克 / UC 账号缓存范围。只产出不可逆短指纹,不包含 Cookie 原文。
|
||||
* 有 {@code _configId} 时按配置隔离;否则按过滤后的会话 Cookie 隔离。
|
||||
*/
|
||||
public final class QuarkAccountScope {
|
||||
|
||||
private QuarkAccountScope() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 可放进缓存 key 的短指纹;没有账号时返回 null,调用方继续使用分享级缓存
|
||||
*/
|
||||
public static String suffix(Map<String, Object> otherParam) {
|
||||
if (otherParam == null || !(otherParam.get("auths") instanceof MultiMap auths)) {
|
||||
return null;
|
||||
}
|
||||
String configId = auths.get("_configId");
|
||||
if (configId != null && !configId.isBlank()) {
|
||||
return "cfg-" + digest(configId.trim());
|
||||
}
|
||||
String cookie = CookieUtils.filterUcQuarkCookie(auths.get("cookie"));
|
||||
if (cookie == null || cookie.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return "ck-" + digest(cookie);
|
||||
}
|
||||
|
||||
private static String digest(String value) {
|
||||
try {
|
||||
byte[] hash = MessageDigest.getInstance("SHA-256")
|
||||
.digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder out = new StringBuilder(16);
|
||||
for (int i = 0; i < 8; i++) {
|
||||
out.append(String.format("%02x", hash[i]));
|
||||
}
|
||||
return out.toString();
|
||||
} catch (Exception e) {
|
||||
return Integer.toHexString(value.hashCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,50 +7,7 @@
|
||||
// 全局类型定义,使用JSDoc注释
|
||||
// 这些类型定义将在VSCode中提供代码补全和类型检查
|
||||
|
||||
// ============================================================================
|
||||
// Nashorn Java 互操作全局对象
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Java 全局对象类型定义 (Nashorn引擎提供)
|
||||
* 用于访问Java类型和进行Java互操作
|
||||
* @typedef {Object} JavaGlobal
|
||||
* @property {function(string): any} type - 获取Java类,参数为完整类名(如"java.util.zip.CRC32")
|
||||
* @property {function(any): any} from - 将Java对象转换为JavaScript对象
|
||||
* @property {function(any): any} to - 将JavaScript对象转换为Java对象
|
||||
* @property {function(any): boolean} isType - 检查对象是否为指定Java类型
|
||||
* @property {function(any): boolean} isJavaObject - 检查对象是否为Java对象
|
||||
* @property {function(any): boolean} isJavaMethod - 检查对象是否为Java方法
|
||||
* @property {function(any): boolean} isJavaFunction - 检查对象是否为Java函数
|
||||
*/
|
||||
|
||||
/**
|
||||
* Java 全局对象 (Nashorn引擎提供)
|
||||
* @global
|
||||
* @type {JavaGlobal}
|
||||
*/
|
||||
var Java;
|
||||
|
||||
/**
|
||||
* java 命名空间对象类型定义 (Nashorn引擎提供)
|
||||
* 用于直接访问Java包和类
|
||||
* @typedef {Object} JavaNamespace
|
||||
* @property {Object} lang - java.lang 包
|
||||
* @property {Object} util - java.util 包
|
||||
* @property {Object} io - java.io 包
|
||||
* @property {Object} net - java.net 包
|
||||
* @property {Object} math - java.math 包
|
||||
* @property {Object} security - java.security 包
|
||||
* @property {Object} text - java.text 包
|
||||
* @property {Object} time - java.time 包
|
||||
*/
|
||||
|
||||
/**
|
||||
* java 命名空间对象 (Nashorn引擎提供)
|
||||
* @global
|
||||
* @type {JavaNamespace}
|
||||
*/
|
||||
var java;
|
||||
// 解析脚本通过项目注入的接口访问分享信息、HTTP 和日志。
|
||||
|
||||
/**
|
||||
* @typedef {Object} ShareLinkInfo
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.custom.CustomParserConfig;
|
||||
import io.vertx.core.Vertx;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.script.ScriptEngine;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ParserScriptEngineTest {
|
||||
@Test
|
||||
public void disablesClassLookupAndHostLoadersBeforeRunningScripts() throws Exception {
|
||||
SecurityClassFilter filter = new SecurityClassFilter();
|
||||
assertFalse(filter.exposeToScripts("java.lang.String"));
|
||||
assertFalse(filter.exposeToScripts("java.util.Formatter"));
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
for (String name : new String[]{"Java", "JavaImporter", "Packages", "java", "javax",
|
||||
"org", "com", "edu", "javafx", "load", "loadWithNewGlobal", "engine", "context", "exit", "quit"}) {
|
||||
assertEquals(name, "undefined", engine.eval("typeof " + name));
|
||||
assertEquals(name, Boolean.FALSE, engine.eval("Object.getOwnPropertyDescriptor(this, '" + name + "').writable"));
|
||||
assertEquals(name, Boolean.FALSE, engine.eval("Object.getOwnPropertyDescriptor(this, '" + name + "').configurable"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ordinaryScriptsCanStillCallAnInjectedParserApi() throws Exception {
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
engine.put("logger", new JsPlaygroundLogger());
|
||||
assertEquals("ok", engine.eval("logger.info('parser test'); JSON.parse('{\"result\":\"ok\"}').result"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bothExecutorsPreserveParserApisAndDisableHostGlobals() throws Exception {
|
||||
String script = """
|
||||
function parse(info, http, logger) {
|
||||
logger.info("parser test");
|
||||
return [info.getShareKey(), typeof fetch, typeof java, typeof loadWithNewGlobal].join("|");
|
||||
}
|
||||
""";
|
||||
String expected = "sample|function|undefined|undefined";
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().shareKey("sample").build();
|
||||
CustomParserConfig config = CustomParserConfig.builder()
|
||||
.type("sandbox_test").displayName("Sandbox test").isJsParser(true).jsCode(script).build();
|
||||
Vertx vertx = Vertx.vertx();
|
||||
try {
|
||||
WebClientVertxInit.init(vertx);
|
||||
try (JsPlaygroundExecutor playground = new JsPlaygroundExecutor(info, script);
|
||||
JsParserExecutor registered = new JsParserExecutor(info, config)) {
|
||||
assertEquals(expected, playground.executeParseAsync().toCompletionStage().toCompletableFuture()
|
||||
.get(10, TimeUnit.SECONDS));
|
||||
assertEquals(expected, registered.parse().toCompletionStage().toCompletableFuture()
|
||||
.get(10, TimeUnit.SECONDS));
|
||||
}
|
||||
} finally {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FjDownloadParamsTest {
|
||||
@Test
|
||||
public void anonymousIdentityIsEmptyRatherThanNull() throws Exception {
|
||||
JsonObject params = FjDownloadParams.create("123", null, "uuid", "share", 1000L);
|
||||
assertEquals("123|", decrypt(params.getString("fidEncode")));
|
||||
assertEquals("1000", decrypt(params.getString("ts")));
|
||||
assertEquals("123|1000", decrypt(params.getString("auth")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticatedIdentityAndTimestampAreRegenerated() throws Exception {
|
||||
JsonObject params = FjDownloadParams.create("123", "456", "uuid", "share", 2000L);
|
||||
assertEquals("123|456", decrypt(params.getString("fidEncode")));
|
||||
assertEquals("123|2000", decrypt(params.getString("auth")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void legacyLinksRecoverOnlyFileId() throws Exception {
|
||||
JsonObject old = JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|null"), "ts", "expired");
|
||||
assertEquals("123", FjDownloadParams.fileId(old));
|
||||
assertEquals("789", FjDownloadParams.fileId(JsonObject.of("fileId", "789")));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void invalidLegacyLinkFailsExplicitly() throws Exception {
|
||||
FjDownloadParams.fileId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("invalid")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upstreamErrorPreservesBusinessCodeAndMessage() {
|
||||
String message = FjDownloadParams.missingLocation(200, "{\"code\":401,\"msg\":\"请登录后下载\"}");
|
||||
assertTrue(message.contains("HTTP 200"));
|
||||
assertTrue(message.contains("code=401"));
|
||||
assertTrue(message.contains("请登录后下载"));
|
||||
assertTrue(FjDownloadParams.missingLocation(502, "").contains("响应体为空"));
|
||||
assertTrue(FjDownloadParams.missingLocation(502, "x".repeat(1000)).length() < 600);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ownerIdentityComesFromDirectoryDataOrLegacySignature() throws Exception {
|
||||
assertEquals("11069975", FjDownloadParams.ownerId(JsonObject.of("userId", 11069975L)));
|
||||
assertEquals("11069975", FjDownloadParams.ownerId(
|
||||
JsonObject.of("fidEncode", AESUtils.encrypt2Hex("61731757356|11069975"))));
|
||||
assertNull(FjDownloadParams.ownerId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|null"))));
|
||||
assertNull(FjDownloadParams.ownerId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|"))));
|
||||
}
|
||||
|
||||
private String decrypt(String value) throws Exception {
|
||||
return AESUtils.decryptByHexAES(value, AESUtils.CIPHER_AES0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.client.WebClient;
|
||||
import io.vertx.ext.web.client.WebClientOptions;
|
||||
import io.vertx.uritemplate.UriTemplate;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FjToolDownloadTest {
|
||||
private Vertx vertx;
|
||||
private WebClient local;
|
||||
private HttpServer server;
|
||||
private final AtomicInteger logins = new AtomicInteger();
|
||||
private final AtomicInteger downloads = new AtomicInteger();
|
||||
private String identity;
|
||||
private String businessError;
|
||||
private String contentEncoding;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
FjTool.resetToken();
|
||||
vertx = Vertx.vertx();
|
||||
WebClientVertxInit.init(vertx);
|
||||
local = WebClient.create(vertx, new WebClientOptions().setFollowRedirects(false));
|
||||
server = vertx.createHttpServer().requestHandler(req -> {
|
||||
if (req.path().equals("/ws/login")) {
|
||||
logins.incrementAndGet();
|
||||
req.response().setStatusCode(500).end("Share downloads must not require login");
|
||||
} else if (req.path().equals("/ws/file/redirect")) {
|
||||
downloads.incrementAndGet();
|
||||
try {
|
||||
identity = AESUtils.decryptByHexAES(req.getParam("downloadId"), AESUtils.CIPHER_AES0);
|
||||
long timestamp = Long.parseLong(AESUtils.decryptByHexAES(req.getParam("timestamp"), AESUtils.CIPHER_AES0));
|
||||
assertTrue(Math.abs(System.currentTimeMillis() - timestamp) < 10000);
|
||||
assertEquals(AESUtils.encrypt2Hex("123|" + timestamp), req.getParam("auth"));
|
||||
assertEquals("share", req.getParam("shareId"));
|
||||
if (businessError != null) {
|
||||
if (contentEncoding != null) {
|
||||
req.response().putHeader("Content-Encoding", contentEncoding);
|
||||
}
|
||||
req.response().end(businessError);
|
||||
} else {
|
||||
req.response().setStatusCode(302).putHeader("Location", "https://download.example/file").end();
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
req.response().setStatusCode(500).end(e.toString());
|
||||
}
|
||||
} else {
|
||||
req.response().setStatusCode(404).end();
|
||||
}
|
||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() throws Exception {
|
||||
local.close();
|
||||
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
FjTool.resetToken();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void directoryLinkUsesOwnerEvenWithConfiguredCredentials() throws Exception {
|
||||
ShareLinkInfo info = info();
|
||||
info.getOtherParam().put("auths", MultiMap.caseInsensitiveMultiMap()
|
||||
.set("username", "test-user").set("password", "test-password"));
|
||||
assertEquals("https://download.example/file", tool(info).parseById()
|
||||
.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS));
|
||||
assertEquals(0, logins.get());
|
||||
assertEquals(1, downloads.get());
|
||||
assertEquals("123|11069975", identity);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shareRequestUsesOwnerNotGlobalUserIdentity() throws Exception {
|
||||
FjTool.userId = "other-user";
|
||||
assertEquals("https://download.example/file", tool(info()).parseById()
|
||||
.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS));
|
||||
assertEquals("123|11069975", identity);
|
||||
assertEquals(0, logins.get());
|
||||
FjTool.userId = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upstreamBusinessErrorCompletesFutureWithReason() throws Exception {
|
||||
businessError = "{\"code\":403,\"msg\":\"需要会员\"}";
|
||||
try {
|
||||
tool(info()).parseById().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
fail("Expected upstream error");
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue(e.getCause().getMessage().contains("需要会员"));
|
||||
assertTrue(e.getCause().getMessage().contains("code=403"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unsupportedErrorEncodingFailsWithoutLeavingFuturePending() throws Exception {
|
||||
contentEncoding = "zstd";
|
||||
businessError = "upstream error";
|
||||
assertErrorBodyFailure("zstd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oversizedErrorBodyFailsWithoutLeavingFuturePending() throws Exception {
|
||||
businessError = "x".repeat(8 * 1024 * 1024 + 1);
|
||||
assertErrorBodyFailure("响应体过大");
|
||||
}
|
||||
|
||||
private void assertErrorBodyFailure(String expectedReason) throws Exception {
|
||||
try {
|
||||
tool(info()).parseById().toCompletionStage().toCompletableFuture().get(3, TimeUnit.SECONDS);
|
||||
fail("Expected response decoding error");
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue(e.getCause().getMessage(), e.getCause().getMessage().contains(expectedReason));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingOwnerFailsBeforeDownload() throws Exception {
|
||||
ShareLinkInfo info = info();
|
||||
info.getOtherParam().put("paramJson", JsonObject.of("fileId", "123", "shareId", "share"));
|
||||
try {
|
||||
tool(info).parseById().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
fail("Expected missing owner error");
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue(e.getCause().getMessage().contains("缺少分享者 userId"));
|
||||
}
|
||||
assertEquals(0, downloads.get());
|
||||
}
|
||||
|
||||
private ShareLinkInfo info() {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("fj").shareKey("share")
|
||||
.shareUrl("https://share.feijipan.com/s/share").build();
|
||||
info.getOtherParam().put("paramJson", JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|11069975"),
|
||||
"uuid", "test-uuid", "ts", "expired", "auth", "expired", "shareId", "share"));
|
||||
return info;
|
||||
}
|
||||
|
||||
private FjTool tool(ShareLinkInfo info) {
|
||||
WebClient routed = (WebClient) Proxy.newProxyInstance(WebClient.class.getClassLoader(),
|
||||
new Class<?>[]{WebClient.class}, (proxy, method, args) -> {
|
||||
if (args != null && args.length > 0 && args[0] instanceof UriTemplate template) {
|
||||
args[0] = Proxy.newProxyInstance(UriTemplate.class.getClassLoader(),
|
||||
new Class<?>[]{UriTemplate.class}, (p, m, a) -> {
|
||||
Object expanded = m.invoke(template, a);
|
||||
return expanded instanceof String url
|
||||
? url.replace("https://api.feijipan.com", "http://127.0.0.1:" + server.actualPort())
|
||||
: expanded;
|
||||
});
|
||||
}
|
||||
return method.invoke(local, args);
|
||||
});
|
||||
return new FjTool(info) {{ client = routed; clientNoRedirects = routed; }};
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@@ -36,12 +37,17 @@ public class QkToolGuestFolderLiveTest {
|
||||
String url = tool.parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
||||
assertNotNull(url);
|
||||
assertTrue(url.startsWith("http"));
|
||||
assertTrue("guest download host, got " + url, url.contains("dl-guest"));
|
||||
FileInfo fileInfo = (FileInfo) info.getOtherParam().get("fileInfo");
|
||||
assertNotNull(fileInfo);
|
||||
assertNotNull(fileInfo.getFileName());
|
||||
assertTrue("expected a small file, got " + fileInfo.getSize() + " " + fileInfo.getFileName(),
|
||||
fileInfo.getSize() > 0 && fileInfo.getSize() < 40L * 1024 * 1024);
|
||||
assertTrue(fileInfo.getSize() > 0);
|
||||
if (fileInfo.getSize() > QuarkFamilyDownloadPolicy.NORMAL_PARSE_MAX_BYTES) {
|
||||
assertTrue("large file should be a public dl-c url, got " + url, url.contains("dl-c-"));
|
||||
assertTrue(url.contains("filename="));
|
||||
assertFalse(url.contains("dl-guest"));
|
||||
} else {
|
||||
assertTrue("guest download host, got " + url, url.contains("dl-guest"));
|
||||
}
|
||||
} finally {
|
||||
if (tool != null) {
|
||||
tool.close();
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.impl.QuarkFamilyDownloadPolicy.Membership;
|
||||
import cn.qaiu.parser.impl.QuarkFamilyDownloadPolicy.ProbeHit;
|
||||
import cn.qaiu.util.QuarkAccountScope;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.json.JsonArray;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.client.WebClient;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* 夸克 / UC 大文件策略。会员、体积、文件名和响应分类不访问网盘。
|
||||
* 本地 HTTP 只验证探测不会收完整文件,以及 HTML / JSON 不会被当成下载。
|
||||
*/
|
||||
public class QuarkFamilyDownloadPolicyTest {
|
||||
|
||||
private static final long NOW = 1_700_000_000_000L;
|
||||
private static final String SECRET = "__pus=super-secret-cookie; __puus=another-secret";
|
||||
|
||||
private static Vertx vertx;
|
||||
private static HttpServer server;
|
||||
private static WebClient client;
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void startServer() throws Exception {
|
||||
vertx = Vertx.vertx();
|
||||
client = WebClient.create(vertx);
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
server = vertx.createHttpServer().requestHandler(req -> {
|
||||
String path = req.path();
|
||||
if ("/member-valid".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end(new JsonObject().put("code", 0).put("data", new JsonObject()
|
||||
.put("member_type", "SUPER_VIP").put("exp_at", 4_102_416_000_000L)).encode());
|
||||
} else if ("/member-auth".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end(new JsonObject().put("code", 31001).put("message", "未登录").encode());
|
||||
} else if ("/member-html".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "text/html").end("<html>login</html>");
|
||||
} else if ("/preview-html".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "text/html; charset=utf-8")
|
||||
.end("<!DOCTYPE html><html><body>preview page</body></html>");
|
||||
} else if ("/preview-missing".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end(new JsonObject().put("code", 0).put("data", new JsonObject()).encode());
|
||||
} else if ("/preview-page".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end(new JsonObject().put("code", 0).put("data", new JsonObject()
|
||||
.put("download_url", "https://vt.quark.cn/preview?foo=1")).encode());
|
||||
} else if ("/zip".equals(path)) {
|
||||
byte[] body = new byte[256 * 1024];
|
||||
body[0] = 'P';
|
||||
body[1] = 'K';
|
||||
req.response().putHeader("Content-Type", "application/zip")
|
||||
.putHeader("Content-Length", Integer.toString(body.length))
|
||||
.end(Buffer.buffer(body));
|
||||
} else if ("/html-file".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "text/html")
|
||||
.end("<html><body>not a file</body></html>");
|
||||
} else if ("/json-file".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "application/json")
|
||||
.end("{\"code\":412,\"message\":\"html-not-file\"}");
|
||||
} else if ("/empty".equals(path)) {
|
||||
req.response().putHeader("Content-Type", "text/plain").putHeader("Content-Length", "0").end();
|
||||
} else if ("/redirect".equals(path)) {
|
||||
req.response().setStatusCode(302).putHeader("Location", "https://pan.quark.cn/login").end();
|
||||
} else {
|
||||
req.response().setStatusCode(404).end();
|
||||
}
|
||||
});
|
||||
server.listen(0).onComplete(ar -> {
|
||||
if (ar.succeeded()) {
|
||||
port = ar.result().actualPort();
|
||||
}
|
||||
latch.countDown();
|
||||
});
|
||||
assertTrue(latch.await(10, TimeUnit.SECONDS));
|
||||
assertTrue(port > 0);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void stopServer() {
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
if (server != null) {
|
||||
server.close();
|
||||
}
|
||||
if (vertx != null) {
|
||||
vertx.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void thresholdKeepsEqualSizeOnNormalPath() {
|
||||
long limit = QuarkFamilyDownloadPolicy.NORMAL_PARSE_MAX_BYTES;
|
||||
assertEquals(10L * 1024 * 1024, limit);
|
||||
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(0));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(limit - 1));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(limit));
|
||||
assertTrue(QuarkFamilyDownloadPolicy.knownLarge(limit + 1));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(Long.MAX_VALUE));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.knownLarge(-1));
|
||||
assertEquals(limit, QuarkFamilyDownloadPolicy.sizeOf(new JsonObject().put("size", limit)));
|
||||
assertEquals(Long.MAX_VALUE, QuarkFamilyDownloadPolicy.sizeOf(new JsonObject()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void membershipRequiresTierAndFutureExpiry() {
|
||||
assertTrue(judge("SUPER_VIP", NOW + 1).validPaid);
|
||||
assertTrue(judge("VIP", NOW + 60_000).validPaid);
|
||||
assertTrue(judge("EXP_SVIP", NOW + 60_000).validPaid);
|
||||
assertTrue(judge("EXP_VIP", NOW + 60_000).validPaid);
|
||||
assertTrue(judge("Z_VIP", NOW + 60_000).validPaid);
|
||||
assertTrue(judge("vip", NOW + 1).validPaid);
|
||||
|
||||
Membership expired = judge("SUPER_VIP", NOW);
|
||||
assertFalse(expired.validPaid);
|
||||
assertTrue(expired.reason.contains("过期"));
|
||||
|
||||
Membership past = judge("VIP", NOW - 1);
|
||||
assertFalse(past.validPaid);
|
||||
|
||||
Membership normal = judge("NORMAL", NOW + 60_000);
|
||||
assertFalse(normal.validPaid);
|
||||
assertTrue(normal.reason.contains("不是"));
|
||||
|
||||
Membership unknown = judge("MINI", NOW + 60_000);
|
||||
assertFalse(unknown.validPaid);
|
||||
|
||||
Membership noType = QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject().put("exp_at", NOW + 1), NOW);
|
||||
assertFalse(noType.validPaid);
|
||||
assertTrue(noType.reason.contains("member_type"));
|
||||
|
||||
Membership noExp = QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject().put("member_type", "SVIP"), NOW);
|
||||
assertFalse(noExp.validPaid);
|
||||
|
||||
Membership missingExp = QuarkFamilyDownloadPolicy.judgeMembership(
|
||||
new JsonObject().put("member_type", "SUPER_VIP"), NOW);
|
||||
assertFalse(missingExp.validPaid);
|
||||
assertTrue(missingExp.reason.contains("exp_at"));
|
||||
|
||||
long seconds = (NOW + 5_000) / 1000;
|
||||
assertTrue(QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject()
|
||||
.put("member_type", "VIP").put("exp_at", seconds), NOW).validPaid);
|
||||
assertNull(QuarkFamilyDownloadPolicy.judgeMembership(null, NOW).memberType);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void memberHttpAuthHtmlAndMissingCookieAreNotPaid() throws Exception {
|
||||
Membership valid = await(QuarkFamilyDownloadPolicy.fetchMembership(client, cookieHeaders(),
|
||||
url("/member-valid"), false));
|
||||
assertTrue(valid.validPaid);
|
||||
assertEquals("SUPER_VIP", valid.memberType);
|
||||
|
||||
Membership auth = await(QuarkFamilyDownloadPolicy.fetchMembership(client, cookieHeaders(),
|
||||
url("/member-auth"), true));
|
||||
assertFalse(auth.validPaid);
|
||||
assertTrue(auth.reason.contains("31001"));
|
||||
|
||||
Membership html = await(QuarkFamilyDownloadPolicy.fetchMembership(client, cookieHeaders(),
|
||||
url("/member-html"), true));
|
||||
assertFalse(html.validPaid);
|
||||
assertTrue(html.reason.contains("HTML"));
|
||||
|
||||
Membership missing = await(QuarkFamilyDownloadPolicy.fetchMembership(client, MultiMap.caseInsensitiveMultiMap(),
|
||||
url("/member-valid"), false));
|
||||
assertFalse(missing.validPaid);
|
||||
assertTrue(missing.reason.contains("未配置"));
|
||||
assertFalse(missing.reason.contains("super-secret"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void previewHtmlMissingAndWebpageAreNotDownloads() throws Exception {
|
||||
String html = awaitFailure(client.getAbs(url("/preview-html")).send()
|
||||
.compose(res -> QuarkFamilyDownloadPolicy.interpretPreview(res, "qk", false)));
|
||||
assertTrue(html.contains("HTML"));
|
||||
|
||||
String missing = awaitFailure(client.getAbs(url("/preview-missing")).send()
|
||||
.compose(res -> QuarkFamilyDownloadPolicy.interpretPreview(res, "uc", false)));
|
||||
assertTrue(missing.contains("download_url"));
|
||||
|
||||
String page = await(client.getAbs(url("/preview-page")).send()
|
||||
.compose(res -> QuarkFamilyDownloadPolicy.interpretPreview(res, "qk", false)));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl(page, "qk"));
|
||||
assertTrue(page.contains("vt.quark.cn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void publicCdnHostsAreSeparateForQuarkAndUc() {
|
||||
String quark = "https://dl-c-zb-u.drive.quark.cn/a/b?auth_key=1&sp=100&token=t&abt=9";
|
||||
String uc = "https://dl-c-zb.drive.uc.cn/a/b?auth_key=1&sp=100&token=t";
|
||||
assertTrue(QuarkFamilyDownloadPolicy.isPublicFileUrl(quark, "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl(quark, "uc"));
|
||||
assertTrue(QuarkFamilyDownloadPolicy.isPublicFileUrl(uc, "uc"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl(uc, "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://dl-c-sz.u-drive.quark.cn/a", "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://dl-pc.sz.drive.quark.cn/a", "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://dl-guest-1.drive.quark.cn/a", "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://vt.quark.cn/preview", "qk"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("https://drive.uc.cn/s/abc", "uc"));
|
||||
assertFalse(QuarkFamilyDownloadPolicy.isPublicFileUrl("http://dl-c-zb.drive.uc.cn/a", "uc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filenameUsesUtf8AndDropsTrackingParams() throws Exception {
|
||||
String raw = "https://dl-c-zb.drive.quark.cn/a/b?auth_key=9&abt=1&sp=100&token=abc&filename=old";
|
||||
String bare = QuarkFamilyDownloadPolicy.bareFileUrl(raw);
|
||||
assertFalse(bare.contains("abt="));
|
||||
assertFalse(bare.contains("filename="));
|
||||
String named = QuarkFamilyDownloadPolicy.withFilename(bare, "报告 (1).zip");
|
||||
assertTrue(named.contains("filename="));
|
||||
assertFalse(named.contains("报告"));
|
||||
String value = named.substring(named.indexOf("filename=") + "filename=".length());
|
||||
assertEquals("报告 (1).zip", URLDecoder.decode(value, StandardCharsets.UTF_8));
|
||||
assertFalse(value.contains(" "));
|
||||
assertFalse(value.contains("+"));
|
||||
String fromAccount = QuarkFamilyDownloadPolicy.presentPublicDownload(raw, "qk", "报告 (1).zip");
|
||||
assertTrue(fromAccount.contains("filename="));
|
||||
assertFalse(fromAccount.contains("abt="));
|
||||
assertEquals("https://dl-pc.sz.drive.quark.cn/a?auth_key=1",
|
||||
QuarkFamilyDownloadPolicy.presentPublicDownload(
|
||||
"https://dl-pc.sz.drive.quark.cn/a?auth_key=1", "qk", "a.zip"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void videoPickerKeepsProgressiveFileAndDropsPlaylist() {
|
||||
JsonObject data = new JsonObject().put("video_list", new JsonArray()
|
||||
.add(new JsonObject().put("video_info", new JsonObject()
|
||||
.put("width", 1920)
|
||||
.put("url", "https://dl-c-zb.drive.quark.cn/high.m3u8?auth_key=1&token=t")))
|
||||
.add(new JsonObject().put("video_info", new JsonObject()
|
||||
.put("width", 1280)
|
||||
.put("url", "https://dl-pc.sz.drive.quark.cn/login.mp4?auth_key=1")))
|
||||
.add(new JsonObject().put("video_info", new JsonObject()
|
||||
.put("width", 640)
|
||||
.put("url", "https://dl-c-sz.drive.quark.cn/low.mp4?auth_key=2&token=t&abt=1"))));
|
||||
assertEquals("https://dl-c-sz.drive.quark.cn/low.mp4?auth_key=2&token=t&abt=1",
|
||||
QuarkFamilyDownloadPolicy.pickProgressiveFileUrl(data, "qk"));
|
||||
assertEquals("", QuarkFamilyDownloadPolicy.pickProgressiveFileUrl(new JsonObject()
|
||||
.put("download_url", "https://pan.quark.cn/s/abc"), "qk"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void probeRejectsHtmlJsonAndEmptyAndCapsZipPrefix() throws Exception {
|
||||
ProbeHit zip = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/zip"), "qk", 1));
|
||||
assertTrue(zip.ok);
|
||||
assertTrue(zip.prefixLength > 0);
|
||||
assertTrue(zip.prefixLength <= 64);
|
||||
|
||||
ProbeHit html = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/html-file"), "qk", 1));
|
||||
assertFalse(html.ok);
|
||||
assertTrue(html.reason.contains("HTML"));
|
||||
|
||||
ProbeHit json = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/json-file"), "uc", 1));
|
||||
assertFalse(json.ok);
|
||||
assertTrue(json.reason.contains("JSON"));
|
||||
|
||||
ProbeHit empty = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/empty"), "qk", 1));
|
||||
assertFalse(empty.ok);
|
||||
|
||||
ProbeHit redirect = await(QuarkFamilyDownloadPolicy.probeBody(vertx, url("/redirect"), "qk", 1));
|
||||
assertFalse(redirect.ok);
|
||||
assertTrue(redirect.reason.contains("不是公开文件"));
|
||||
|
||||
ProbeHit rangedHtml = QuarkFamilyDownloadPolicy.judgeProbe(206, "text/html", "bytes 0-0/9", "1",
|
||||
Buffer.buffer("<html>"));
|
||||
assertFalse(rangedHtml.ok);
|
||||
ProbeHit rangedZip = QuarkFamilyDownloadPolicy.judgeProbe(206, "application/zip", "bytes 0-15/99", null,
|
||||
Buffer.buffer("PK"));
|
||||
assertTrue(rangedZip.ok);
|
||||
ProbeHit denied = QuarkFamilyDownloadPolicy.judgeProbe(412, "text/html", null, null, Buffer.buffer("<html>"));
|
||||
assertFalse(denied.ok);
|
||||
assertTrue(denied.reason.contains("412"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void errorsStayActionableAndHideSecrets() {
|
||||
RuntimeException leaked = new RuntimeException("失败 cookie=" + SECRET + " <html>login</html>");
|
||||
String uc = QuarkFamilyDownloadPolicy.largeFileError("uc", leaked,
|
||||
new IllegalStateException("H5 预览没有 download_url"));
|
||||
String qk = QuarkFamilyDownloadPolicy.largeFileError("qk", null,
|
||||
new IllegalStateException("<!DOCTYPE html>"));
|
||||
assertTrue(uc.contains("不能免登录"));
|
||||
assertTrue(uc.contains("auths.uc.cookie"));
|
||||
assertTrue(uc.contains("10MiB"));
|
||||
assertFalse(uc.contains("super-secret"));
|
||||
assertFalse(uc.contains("<html"));
|
||||
assertTrue(qk.contains("auths.qk.cookie"));
|
||||
assertTrue(qk.contains("HTML"));
|
||||
assertFalse(qk.contains("免登录下载"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void publicDirectDropsAccountHeaders() {
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
headers.put("cookie", SECRET);
|
||||
headers.put("Referer", "https://pan.quark.cn/");
|
||||
assertFalse(QuarkFamilyDownloadPolicy.prepareDownloader(headers, true, true));
|
||||
assertTrue(headers.isEmpty());
|
||||
|
||||
Map<String, String> account = new LinkedHashMap<>();
|
||||
account.put("cookie", "account-cookie");
|
||||
assertTrue(QuarkFamilyDownloadPolicy.prepareDownloader(account, true, false));
|
||||
assertEquals("account-cookie", account.get("cookie"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void accountCacheScopeDoesNotReuseAnotherCookie() {
|
||||
Map<String, Object> guest = new HashMap<>();
|
||||
assertNull(QuarkAccountScope.suffix(guest));
|
||||
|
||||
Map<String, Object> first = authParam(SECRET);
|
||||
Map<String, Object> second = authParam("__pus=other-account; __uid=2");
|
||||
Map<String, Object> same = authParam(SECRET);
|
||||
String a = QuarkAccountScope.suffix(first);
|
||||
String b = QuarkAccountScope.suffix(second);
|
||||
assertEquals(a, QuarkAccountScope.suffix(same));
|
||||
assertNotEquals(a, b);
|
||||
assertFalse(a.contains("super-secret"));
|
||||
assertFalse(b.contains("__pus"));
|
||||
|
||||
ShareLinkInfo guestInfo = share("qk", guest);
|
||||
ShareLinkInfo accountInfo = share("qk", first);
|
||||
ShareLinkInfo otherInfo = share("UC", second);
|
||||
assertEquals("qk:key", guestInfo.getCacheKey());
|
||||
assertTrue(accountInfo.getCacheKey().startsWith("qk:key#"));
|
||||
assertNotEquals(accountInfo.getCacheKey(), otherInfo.getCacheKey().replace("UC:", "qk:"));
|
||||
assertFalse(accountInfo.getCacheKey().contains("super-secret"));
|
||||
assertFalse(otherInfo.getCacheKey().contains("other-account"));
|
||||
}
|
||||
|
||||
private static Membership judge(String type, long expAt) {
|
||||
return QuarkFamilyDownloadPolicy.judgeMembership(new JsonObject()
|
||||
.put("member_type", type).put("exp_at", expAt), NOW);
|
||||
}
|
||||
|
||||
private static MultiMap cookieHeaders() {
|
||||
return MultiMap.caseInsensitiveMultiMap().set("cookie", SECRET);
|
||||
}
|
||||
|
||||
private static String url(String path) {
|
||||
return "http://127.0.0.1:" + port + path;
|
||||
}
|
||||
|
||||
private static Map<String, Object> authParam(String cookie) {
|
||||
MultiMap auths = MultiMap.caseInsensitiveMultiMap().set("cookie", cookie);
|
||||
Map<String, Object> other = new HashMap<>();
|
||||
other.put("auths", auths);
|
||||
return other;
|
||||
}
|
||||
|
||||
private static ShareLinkInfo share(String type, Map<String, Object> other) {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().type(type).shareKey("key").build();
|
||||
info.setOtherParam(other);
|
||||
return info;
|
||||
}
|
||||
|
||||
private static <T> T await(io.vertx.core.Future<T> future) throws Exception {
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
AtomicReference<T> value = new AtomicReference<>();
|
||||
AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
future.onComplete(ar -> {
|
||||
if (ar.succeeded()) {
|
||||
value.set(ar.result());
|
||||
} else {
|
||||
error.set(ar.cause());
|
||||
}
|
||||
latch.countDown();
|
||||
});
|
||||
assertTrue(latch.await(10, TimeUnit.SECONDS));
|
||||
if (error.get() != null) {
|
||||
throw new AssertionError(error.get().getMessage(), error.get());
|
||||
}
|
||||
return value.get();
|
||||
}
|
||||
|
||||
private static String awaitFailure(io.vertx.core.Future<?> future) throws Exception {
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
AtomicReference<Throwable> error = new AtomicReference<>();
|
||||
future.onComplete(ar -> {
|
||||
if (ar.failed()) {
|
||||
error.set(ar.cause());
|
||||
}
|
||||
latch.countDown();
|
||||
});
|
||||
assertTrue(latch.await(10, TimeUnit.SECONDS));
|
||||
assertTrue(error.get() != null);
|
||||
return error.get().getMessage() == null ? "" : error.get().getMessage();
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<revision>0.4.8</revision>
|
||||
<revision>0.4.9</revision>
|
||||
<java.version>17</java.version>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nfd-web",
|
||||
"version": "0.4.8",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"serve": "vue-cli-service serve",
|
||||
|
||||
@@ -455,6 +455,7 @@ import fileTypeUtils from '@/utils/fileTypeUtils'
|
||||
import DownloadDialog from '@/components/DownloadDialog.vue'
|
||||
import { testConnection, autoDetect, addDownload, batchAddDownload, getConfig, saveConfig } from '@/utils/downloaderService'
|
||||
import batchTreeCollect from '@/utils/batchTreeCollect'
|
||||
import { openNoReferrer } from '@/utils/openNoReferrer'
|
||||
|
||||
const {
|
||||
DEFAULT_BATCH_MAX_DEPTH,
|
||||
@@ -758,13 +759,7 @@ export default {
|
||||
// 下载文件
|
||||
downloadFile(file) {
|
||||
if (file?.parserUrl) {
|
||||
const a = document.createElement('a')
|
||||
a.href = this.appendToken(file.parserUrl)
|
||||
a.target = '_blank'
|
||||
a.rel = 'noopener noreferrer'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
openNoReferrer(this.appendToken(file.parserUrl))
|
||||
this.$message.success('开始下载文件')
|
||||
} else {
|
||||
this.$message.warning('该文件暂无下载链接')
|
||||
@@ -805,14 +800,7 @@ export default {
|
||||
this.downloadInfo = info
|
||||
this.downloadDialogVisible = true
|
||||
} else if (info.downloadUrl) {
|
||||
// 服务端判断不需要下载器,直接跳转
|
||||
const a = document.createElement('a')
|
||||
a.href = info.downloadUrl
|
||||
a.target = '_blank'
|
||||
a.rel = 'noopener noreferrer'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
openNoReferrer(info.downloadUrl)
|
||||
this.$message.success('开始下载文件')
|
||||
} else {
|
||||
this.downloadFile(file)
|
||||
@@ -948,14 +936,7 @@ export default {
|
||||
},
|
||||
openPreviewInNewTab() {
|
||||
if (this.previewUrl) {
|
||||
// 使用动态 a 标签并设置 noopener noreferrer 以避免携带 Referer,绕过防盗链机制
|
||||
const a = document.createElement('a')
|
||||
a.href = this.previewUrl
|
||||
a.target = '_blank'
|
||||
a.rel = 'noopener noreferrer'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
openNoReferrer(this.previewUrl)
|
||||
}
|
||||
},
|
||||
hasValidTime(value) {
|
||||
@@ -1237,14 +1218,8 @@ export default {
|
||||
this.batchProgress = { current: 0, total: files.length, failed: 0 }
|
||||
for (const file of files) {
|
||||
try {
|
||||
const a = document.createElement('a')
|
||||
const rawUrl = file.parserUrl.startsWith('http') ? file.parserUrl : (window.location.origin + file.parserUrl)
|
||||
a.href = this.appendToken(rawUrl)
|
||||
a.target = '_blank'
|
||||
a.rel = 'noopener noreferrer'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
openNoReferrer(this.appendToken(rawUrl))
|
||||
await new Promise(r => setTimeout(r, 500))
|
||||
} catch {
|
||||
this.batchProgress.failed++
|
||||
|
||||
@@ -105,6 +105,7 @@
|
||||
|
||||
<script>
|
||||
import { testConnection, addDownload, getConfig, hasCookieHeader, hasCustomUaHeader } from '@/utils/downloaderService'
|
||||
import { openNoReferrer } from '@/utils/openNoReferrer'
|
||||
|
||||
export default {
|
||||
name: 'DownloadDialog',
|
||||
@@ -193,13 +194,7 @@ export default {
|
||||
/** 直接打开下载链接(可能因缺请求头而失败) */
|
||||
doDirectDownload() {
|
||||
if (this.info && this.info.downloadUrl) {
|
||||
const a = document.createElement('a')
|
||||
a.href = this.info.downloadUrl
|
||||
a.target = '_blank'
|
||||
a.rel = 'noopener noreferrer'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
openNoReferrer(this.info.downloadUrl)
|
||||
this.dialogVisible = false
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 在用户点击里打开地址,并且不带 Referer。
|
||||
* 夸克 / UC 的公开文件 CDN 遇到站点 Referer 会返回 403 HTML。
|
||||
* 使用 referrerpolicy="no-referrer" 的链接,而不是只依赖 window.open 的特征字符串。
|
||||
*/
|
||||
export function openNoReferrer(url) {
|
||||
if (!url) return
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.target = '_blank'
|
||||
a.rel = 'noreferrer noopener'
|
||||
a.referrerPolicy = 'no-referrer'
|
||||
a.style.display = 'none'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
}
|
||||
@@ -619,6 +619,7 @@ import DirectoryTree from '@/components/DirectoryTree'
|
||||
import ViewModeSwitch from '@/components/ViewModeSwitch'
|
||||
import DownloadDialog from '@/components/DownloadDialog'
|
||||
import parserUrl from '../parserUrl1'
|
||||
import { openNoReferrer } from '../utils/openNoReferrer'
|
||||
import fileTypeUtils from '@/utils/fileTypeUtils'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { playgroundApi } from '@/utils/playgroundApi'
|
||||
@@ -770,15 +771,22 @@ export default {
|
||||
}
|
||||
return map[this.aria2ConfigForm.downloaderType] || 'Aria2'
|
||||
},
|
||||
// 需要下载器(带 cookie 等特殊头)时禁用浏览器下载/复制直链;UC/夸克始终需要
|
||||
// 带 Cookie 的直链浏览器带不上,仍走下载器。
|
||||
// 夸克 / UC 的公开 H5 文件地址没有 Cookie,允许浏览器打开;文件名在 URL 的 filename 上
|
||||
// (跨域时 a[download] 无效,不能靠它改名)。
|
||||
needsDownloader() {
|
||||
const pan = (this.getCurrentPanType() || '').toLowerCase()
|
||||
if (pan === 'uc' || pan === 'qk') return true
|
||||
const data = this.parseResult?.data
|
||||
const pan = (this.getCurrentPanType() || '').toLowerCase()
|
||||
const headers = data && (data.downloadHeaders || data.otherParam?.downloadHeaders)
|
||||
const hasCookie = !!(headers && (headers.cookie || headers.Cookie))
|
||||
if (pan === 'uc' || pan === 'qk') {
|
||||
if (!data) return true
|
||||
if (hasCookie) return true
|
||||
return !!(data.needDownloader || data.otherParam?.needDownloader)
|
||||
}
|
||||
if (!data) return false
|
||||
if (data.needDownloader || data.otherParam?.needDownloader) return true
|
||||
const headers = data.downloadHeaders || data.otherParam?.downloadHeaders
|
||||
return !!(headers && (headers.cookie || headers.Cookie))
|
||||
return hasCookie
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
@@ -1423,7 +1431,7 @@ export default {
|
||||
// 文件点击处理
|
||||
handleFileClick(file) {
|
||||
if (file.parserUrl) {
|
||||
window.open(file.parserUrl, '_blank', 'noopener,noreferrer')
|
||||
openNoReferrer(file.parserUrl)
|
||||
} else {
|
||||
this.$message.warning('该文件暂无下载链接')
|
||||
}
|
||||
@@ -1860,7 +1868,7 @@ export default {
|
||||
}
|
||||
},
|
||||
openUrl(url) {
|
||||
if (url) window.open(url, '_blank', 'noopener,noreferrer')
|
||||
openNoReferrer(url)
|
||||
},
|
||||
async loadDirectoryParseSupportedPans() {
|
||||
try {
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
<el-icon :size="50"><WarningFilled /></el-icon>
|
||||
</div>
|
||||
<div class="auth-title">演练场功能已禁用</div>
|
||||
<div class="auth-subtitle">请联系管理员启用演练场功能</div>
|
||||
<div class="auth-subtitle">请联系管理员检查演练场开关与服务日志。私有模式需要先设置实例专属的访问密码。</div>
|
||||
<el-button type="primary" size="large" @click="goHome" class="auth-button">
|
||||
<span>返回首页</span>
|
||||
</el-button>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<div class="file-meta-info-card">
|
||||
<div class="file-meta-row">
|
||||
<span class="file-meta-label">下载链接:</span>
|
||||
<a :href="downloadUrl" target="_blank" class="file-meta-link">点击下载</a>
|
||||
<a :href="downloadUrl" target="_blank" rel="noreferrer noopener" referrerpolicy="no-referrer" class="file-meta-link">点击下载</a>
|
||||
</div>
|
||||
<div class="file-meta-row">
|
||||
<span class="file-meta-label">文件名:</span>{{ fileTypeUtils.extractFileNameAndExt(downloadUrl).name }}
|
||||
|
||||
@@ -6,15 +6,16 @@ JS解析器演练场现在支持密码保护功能,可以通过配置文件控
|
||||
|
||||
## 配置说明
|
||||
|
||||
在 `web-service/src/main/resources/app-dev.yml` 文件中添加以下配置:
|
||||
编辑当前启用的配置文件。发行包默认使用 `resources/app-dev.yml`。
|
||||
|
||||
```yaml
|
||||
# JS演练场配置
|
||||
playground:
|
||||
enabled: false
|
||||
# 公开模式,默认false需要密码访问,设为true则无需密码
|
||||
public: false
|
||||
# 访问密码,建议修改默认密码!
|
||||
password: 'nfd_playground_2024'
|
||||
# 私有模式启用前须设置实例专属密码
|
||||
password: ''
|
||||
```
|
||||
|
||||
### 配置项说明
|
||||
@@ -24,8 +25,7 @@ playground:
|
||||
- `true`: 公开访问,无需密码
|
||||
|
||||
- `password`: 字符串,访问密码
|
||||
- 默认密码:`nfd_playground_2024`
|
||||
- **强烈建议在生产环境中修改为自定义密码!**
|
||||
- 无默认值。私有模式缺少密码、密码为空白或沿用旧版公开密码时,演练场保持关闭。
|
||||
|
||||
## 功能特点
|
||||
|
||||
@@ -64,24 +64,14 @@ playground:
|
||||
|
||||
⚠️ **重要安全提示:**
|
||||
|
||||
1. **修改默认密码**:在生产环境中,务必修改 `playground.password` 为自定义的强密码
|
||||
1. **设置专属密码**:启用私有模式前,请设置 `playground.password` 为自定义的强密码
|
||||
2. **使用密码保护**:建议保持 `public: false`,避免未授权访问
|
||||
3. **定期更换密码**:定期更换访问密码以提高安全性
|
||||
4. **配置文件保护**:确保配置文件的访问权限受到保护
|
||||
|
||||
## 系统启动提示
|
||||
|
||||
当系统启动时,会在日志中显示当前配置:
|
||||
|
||||
```
|
||||
INFO - Playground配置已加载: public=false, password=已设置
|
||||
```
|
||||
|
||||
如果使用默认密码,会显示警告:
|
||||
|
||||
```
|
||||
WARN - ⚠️ 警告:您正在使用默认密码,建议修改配置文件中的 playground.password 以确保安全!
|
||||
```
|
||||
配置文件及启用开关 `NFD_PLAYGROUND_ENABLED` 生效后,服务会检查私有模式密码。若检查失败,日志会提示配置 `playground.password` 并重启服务,其他功能继续启动。显式选择 `public: true` 会允许免密码访问管理接口。
|
||||
|
||||
## API 端点
|
||||
|
||||
@@ -145,9 +135,9 @@ A: 修改配置文件中的 `playground.password` 为新密码,然后重启服
|
||||
|
||||
A: 当前版本密码以明文形式存储在配置文件中,请确保配置文件的访问权限受到保护
|
||||
|
||||
### Q: Session 有效期多久?
|
||||
### 登录令牌有效期多久?
|
||||
|
||||
A: Session 由 Vert.x 管理,默认在浏览器会话期间有效,关闭浏览器后失效
|
||||
私有模式的令牌自签发起最多有效 24 小时。服务重启或重新加载演练场配置会使已签发的令牌失效。
|
||||
|
||||
## 后续版本计划
|
||||
|
||||
@@ -156,7 +146,6 @@ A: Session 由 Vert.x 管理,默认在浏览器会话期间有效,关闭浏
|
||||
- [ ] 支持环境变量配置密码
|
||||
- [ ] 支持加密存储密码
|
||||
- [ ] 支持多用户账户系统
|
||||
- [ ] 支持 Token 认证方式
|
||||
- [ ] 支持 Session 超时配置
|
||||
|
||||
## 相关文档
|
||||
|
||||
@@ -26,7 +26,7 @@ public class PlaygroundConfig {
|
||||
/**
|
||||
* 单例实例
|
||||
*/
|
||||
private static PlaygroundConfig instance;
|
||||
private static volatile PlaygroundConfig instance = new PlaygroundConfig();
|
||||
|
||||
/**
|
||||
* 已颁发的认证Token及其创建时间
|
||||
@@ -47,9 +47,8 @@ public class PlaygroundConfig {
|
||||
|
||||
/**
|
||||
* 访问密码
|
||||
* 默认密码:nfd_playground_2024
|
||||
*/
|
||||
private String password = "nfd_playground_2024";
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* 私有构造函数
|
||||
@@ -117,13 +116,6 @@ public class PlaygroundConfig {
|
||||
* 获取单例实例
|
||||
*/
|
||||
public static PlaygroundConfig getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (PlaygroundConfig.class) {
|
||||
if (instance == null) {
|
||||
instance = new PlaygroundConfig();
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
@@ -131,23 +123,13 @@ public class PlaygroundConfig {
|
||||
* 从JsonObject加载配置
|
||||
*/
|
||||
public static void loadFromJson(JsonObject config) {
|
||||
PlaygroundConfig cfg = getInstance();
|
||||
if (config != null && config.containsKey("playground")) {
|
||||
JsonObject playgroundConfig = config.getJsonObject("playground");
|
||||
cfg.enabled = playgroundConfig.getBoolean("enabled", false);
|
||||
cfg.isPublic = playgroundConfig.getBoolean("public", false);
|
||||
cfg.password = playgroundConfig.getString("password", "nfd_playground_2024");
|
||||
|
||||
log.info("Playground配置已加载: enabled={}, public={}, password={}",
|
||||
cfg.enabled, cfg.isPublic, cfg.isPublic ? "N/A" : "已设置");
|
||||
|
||||
if (!cfg.enabled) {
|
||||
log.info("演练场功能已禁用");
|
||||
} else if (!cfg.isPublic && "nfd_playground_2024".equals(cfg.password)) {
|
||||
log.warn("⚠️ 警告:您正在使用默认密码,建议修改配置文件中的 playground.password 以确保安全!");
|
||||
PlaygroundConfig cfg = new PlaygroundConfig();
|
||||
if (config != null && config.getValue("playground") instanceof JsonObject playground) {
|
||||
cfg.enabled = playground.getBoolean("enabled", false);
|
||||
cfg.isPublic = playground.getBoolean("public", false);
|
||||
if (playground.getValue("password") instanceof String configuredPassword) {
|
||||
cfg.password = configuredPassword;
|
||||
}
|
||||
} else {
|
||||
log.info("未找到playground配置,使用默认值: enabled=false, public=false");
|
||||
}
|
||||
String enabledOverride = System.getProperty("NFD_PLAYGROUND_ENABLED");
|
||||
if (enabledOverride == null || enabledOverride.isBlank()) {
|
||||
@@ -155,7 +137,16 @@ public class PlaygroundConfig {
|
||||
}
|
||||
if (enabledOverride != null && !enabledOverride.isBlank()) {
|
||||
cfg.enabled = Boolean.parseBoolean(enabledOverride);
|
||||
log.info("Playground enabled 已被 NFD_PLAYGROUND_ENABLED 覆盖为 {}", cfg.enabled);
|
||||
}
|
||||
|
||||
// Validate after all overrides so enabling via the environment follows the same rules.
|
||||
if (cfg.enabled && !cfg.isPublic && (cfg.password == null || cfg.password.isBlank()
|
||||
|| "nfd_playground_2024".equals(cfg.password.strip()))) {
|
||||
cfg.enabled = false;
|
||||
log.warn("演练场已禁用:请在 app-dev.yml 中设置实例专属的 playground.password,替换空值或旧版默认密码,然后重启服务。");
|
||||
} else {
|
||||
log.info("演练场配置已加载:enabled={}, public={}", cfg.enabled, cfg.isPublic);
|
||||
}
|
||||
instance = cfg;
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import cn.qaiu.lz.web.service.DbService;
|
||||
import cn.qaiu.parser.PanDomainTemplate;
|
||||
import cn.qaiu.parser.IPanTool;
|
||||
import cn.qaiu.parser.ParserCreate;
|
||||
import cn.qaiu.parser.impl.QuarkFamilyDownloadPolicy;
|
||||
import cn.qaiu.parser.clientlink.ClientLinkGeneratorFactory;
|
||||
import cn.qaiu.parser.clientlink.ClientLinkType;
|
||||
import cn.qaiu.util.CommonUtils;
|
||||
@@ -318,8 +319,9 @@ public class ParserApi {
|
||||
}
|
||||
}
|
||||
|
||||
boolean needDownloader = Boolean.TRUE.equals(paramJson.getBoolean("needDownloader"))
|
||||
|| !downloadHeaders.isEmpty();
|
||||
boolean publicDirect = Boolean.TRUE.equals(shareLinkInfo.getOtherParam().get("publicDirectLink"));
|
||||
boolean needDownloader = QuarkFamilyDownloadPolicy.prepareDownloader(downloadHeaders,
|
||||
Boolean.TRUE.equals(paramJson.getBoolean("needDownloader")), publicDirect);
|
||||
|
||||
shareLinkInfo.getOtherParam().put("downloadUrl", downloadUrl);
|
||||
if (!downloadHeaders.isEmpty()) {
|
||||
|
||||
@@ -20,8 +20,8 @@ playground:
|
||||
enabled: false
|
||||
# 公开模式,默认false需要密码访问,设为true则无需密码
|
||||
public: false
|
||||
# 访问密码,建议修改默认密码!
|
||||
password: 'nfd_playground_2024'
|
||||
# 私有模式启用前请填写实例专属密码;留空或沿用旧版默认密码将禁用演练场。
|
||||
password: ''
|
||||
|
||||
# vertx核心线程配置(一般无需改的), 为0表示eventLoopPoolSize将会采用默认配置(CPU核心*2) workerPoolSize将会采用默认20
|
||||
vertx:
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package cn.qaiu.lz.web.config;
|
||||
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PlaygroundPasswordTest {
|
||||
@Test
|
||||
public void validatesPrivateModeAfterTheEnableOverride() {
|
||||
String key = "NFD_PLAYGROUND_ENABLED";
|
||||
String previous = System.getProperty(key);
|
||||
try {
|
||||
System.setProperty(key, "true");
|
||||
JsonObject playground = new JsonObject().put("enabled", false);
|
||||
JsonObject config = new JsonObject().put("playground", playground);
|
||||
for (String password : new String[]{null, "", " ", "nfd_playground_2024"}) {
|
||||
playground.put("password", password);
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
}
|
||||
playground.put("password", "instance-specific-test-value");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertTrue(PlaygroundConfig.getInstance().isEnabled());
|
||||
assertEquals(playground.getString("password"), PlaygroundConfig.getInstance().getPassword());
|
||||
String token = PlaygroundConfig.getInstance().generateToken();
|
||||
|
||||
PlaygroundConfig.loadFromJson(new JsonObject());
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
assertFalse(PlaygroundConfig.getInstance().validateToken(token));
|
||||
|
||||
playground.put("public", true).remove("password");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertTrue(PlaygroundConfig.getInstance().isEnabled());
|
||||
System.setProperty(key, "false");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
} finally {
|
||||
if (previous == null) System.clearProperty(key);
|
||||
else System.setProperty(key, previous);
|
||||
PlaygroundConfig.loadFromJson(new JsonObject());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user