Compare commits

..
126 changed files with 2439 additions and 6970 deletions
+38 -220
View File
@@ -1,16 +1,24 @@
name: Java CIMaven 构建 + Docker 镜像 + 原生环境打包)
# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
name: Java CI with Maven
# The API requires write permission on the repository to submit dependencies
permissions:
contents: write
packages: write
on:
workflow_dispatch:
push:
tags:
- '*'
- '*' # 只有推送tag时才会触发构建
branches-ignore:
- '*'
- '*' # 排除所有分支的提交
paths-ignore:
- 'bin/**'
- '.github/**'
@@ -24,260 +32,70 @@ on:
- "main"
jobs:
# ================================================================
# 阶段一:构建前端 + Maven 打包(只执行一次,产物共享)
# ================================================================
build:
name: 编译构建
runs-on: ubuntu-latest
steps:
- name: 检出代码
uses: actions/checkout@v3
- name: 设置 Node.js 18
uses: actions/setup-node@v4
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v4
with:
node-version: '18'
- name: 设置 JDK 17
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: maven
- name: 构建前端
- name: Build Frontend
run: cd web-front && yarn install && yarn run build
- name: Maven 编译打包
- name: Build with Maven
run: mvn -B package -DskipTests --file pom.xml
- name: 更新依赖图谱
# Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive
- name: Update dependency graph
uses: advanced-security/maven-dependency-submission-action@v3
if: github.event_name != 'pull_request'
continue-on-error: true
with:
ignore-maven-wrapper: true
- name: 分享应用打包目录(供原生包和 Docker 复用)
if: github.event_name != 'pull_request'
uses: actions/upload-artifact@v4
with:
name: app-package
path: web-service/target/package/
# - uses: release-drafter/release-drafter@v5
# env:
# GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }}
- name: 分享 bin-zip(供 Docker 复用)
if: github.event_name != 'pull_request'
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: app-bin-zip
path: web-service/target/netdisk-fast-download-bin.zip
# ================================================================
# 阶段二-A:Docker 镜像构建(并行)
# ================================================================
docker:
name: Docker 镜像
needs: build
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
steps:
- name: 检出代码
uses: actions/checkout@v3
- name: 下载 bin-zip 产物
uses: actions/download-artifact@v4
with:
name: app-bin-zip
path: web-service/target/
- name: 登录 GitHub 容器仓库
- name: Login to GitHub Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: 设置 QEMU(多平台构建支持)
uses: docker/setup-qemu-action@v3
- name: 设置 Docker Buildx
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: 生成 Docker 标签
id: docker_tag
shell: bash
- name: Extract git tag
id: tag
run: |
tag="$(printf '%s' "${GITHUB_REF_NAME}" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9_.-]+/-/g; s/^-+//; s/-+$//')"
if [ -z "$tag" ]; then
tag="snapshot"
fi
echo "tag=$tag" >> "$GITHUB_OUTPUT"
GIT_TAG=$(git tag --points-at HEAD | head -n 1)
echo "tag=$GIT_TAG" >> $GITHUB_OUTPUT
- name: 构建并推送 Docker 镜像
- name: Build and push Docker image
if: github.event_name != 'pull_request'
uses: docker/build-push-action@v5
with:
context: .
push: true
platforms: linux/amd64,linux/arm64,linux/arm/v7
tags: |
ghcr.io/${{ github.repository }}:${{ steps.docker_tag.outputs.tag }}
ghcr.io/${{ github.repository }}:latest
# ================================================================
# 阶段二-B:原生环境打包 Linux + Windows(并行)
# ================================================================
native-package:
name: 原生环境打包 → ${{ matrix.artifact-name }}
needs: build
if: github.event_name != 'pull_request'
strategy:
matrix:
include:
- os: ubuntu-latest
artifact-name: netdisk-fast-download-linux-amd64
- os: windows-latest
artifact-name: netdisk-fast-download-windows-amd64
runs-on: ${{ matrix.os }}
defaults:
run:
shell: bash
steps:
- name: 设置 JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
- name: 下载 Maven 构建产物
uses: actions/download-artifact@v4
with:
name: app-package
path: web-service/target/package
# ============================================================
# jdeps 分析 → 确定所需 JDK 模块
# ============================================================
- name: 分析所需 JDK 模块(jdeps
run: |
MAIN_JAR="web-service/target/package/netdisk-fast-download.jar"
LIB_DIR="web-service/target/package/lib"
CP=""
for jar in "$LIB_DIR"/*.jar; do
CP="$CP${CP:+:}$jar"
done
RAW_MODULES=$(jdeps --print-module-deps --ignore-missing-deps --multi-release 17 \
--class-path "$CP" "$MAIN_JAR" 2>/dev/null | head -n 1 | tr -d '\r\n' || true)
if [ -z "$RAW_MODULES" ] || [[ "$RAW_MODULES" == *"Missing"* ]] || [[ "$RAW_MODULES" == *"Error"* ]]; then
# ⚠️ 回退列表:若项目新增了需要 java.* / jdk.* 模块的依赖,需同步更新此处
RAW_MODULES="java.base,java.logging,java.sql,java.naming,java.management,java.xml,jdk.unsupported,java.net.http,java.instrument,java.security.jgss,java.security.sasl,java.desktop,jdk.crypto.ec"
echo "jdeps 分析失败,使用回退模块列表"
else
# 补上 jdeps 无法检测的反射/SPI依赖
RAW_MODULES="$RAW_MODULES,java.desktop,jdk.crypto.ec"
fi
echo "detected modules: $RAW_MODULES"
printf 'JDK_MODULES=%s\n' "$RAW_MODULES" >> $GITHUB_ENV
# ============================================================
# jlink 生成精简 JRE
# ============================================================
- name: 生成精简 JREjlink
run: |
jlink \
--module-path "$JAVA_HOME/jmods" \
--add-modules "$JDK_MODULES" \
--output "native-package/netdisk-fast-download/jre" \
--strip-debug \
--compress=2 \
--no-header-files \
--no-man-pages
echo "JRE size:"
du -sh native-package/netdisk-fast-download/jre || true
# Windows: 确保 MSVC 运行时 DLL 到位
if [[ "$RUNNER_OS" == "Windows" ]]; then
JRE_BIN="native-package/netdisk-fast-download/jre/bin"
for dll in vcruntime140.dll msvcp140.dll vcruntime140_1.dll; do
if [ ! -f "$JRE_BIN/$dll" ] && [ -f "$JAVA_HOME/bin/$dll" ]; then
echo "jlink 未包含 $dll,从 JDK 补拷"
cp "$JAVA_HOME/bin/$dll" "$JRE_BIN/"
fi
done
echo "=== JRE bin 目录 DLL 清单 ==="
ls -la "$JRE_BIN"/*.dll 2>/dev/null || echo "(无 .dll 文件)"
fi
# ============================================================
# 组装包目录
# ============================================================
- name: 组装包目录
run: |
PKG="native-package/netdisk-fast-download"
SRC="web-service/target/package"
cp "$SRC/netdisk-fast-download.jar" "$PKG/"
cp -r "$SRC/lib" "$PKG/"
cp -r "$SRC/resources" "$PKG/"
cp -r "$SRC/webroot" "$PKG/"
mkdir -p "$PKG/db"
mkdir -p "$PKG/logs"
# ============================================================
# 生成启动脚本
# ============================================================
- name: 生成启动脚本(Linux
run: |
PKG="native-package/netdisk-fast-download"
echo '#!/bin/bash' > "$PKG/run.sh"
echo 'DIR="$(cd "$(dirname "$0")" && pwd)"' >> "$PKG/run.sh"
echo 'cd "$DIR" || exit 1' >> "$PKG/run.sh"
echo 'exec "$DIR/jre/bin/java" -Xmx512M -Dfile.encoding=utf-8 -jar "$DIR/netdisk-fast-download.jar" "$@"' >> "$PKG/run.sh"
chmod +x "$PKG/run.sh"
- name: 生成启动脚本(Windows
run: |
PKG="native-package/netdisk-fast-download"
echo '@echo off' > "$PKG/run.bat"
echo 'chcp 65001 > nul' >> "$PKG/run.bat"
echo 'pushd %~dp0' >> "$PKG/run.bat"
echo '"%~dp0jre\bin\java.exe" -Xmx512M -Dfile.encoding=utf-8 -jar "%~dp0netdisk-fast-download.jar" %*' >> "$PKG/run.bat"
# ============================================================
# 打包为 zip
# ============================================================
- name: 打包 ZIPLinux
if: runner.os == 'Linux'
run: |
cd native-package
zip -r "../${{ matrix.artifact-name }}.zip" netdisk-fast-download/
- name: 打包 ZIPWindows
if: runner.os == 'Windows'
shell: pwsh
run: |
Compress-Archive -Path native-package/netdisk-fast-download -DestinationPath "${{ matrix.artifact-name }}.zip"
# ============================================================
# 上传产物
# ============================================================
- name: 上传原生安装包
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.artifact-name }}
path: ${{ matrix.artifact-name }}.zip
- name: 上传到 Release
uses: softprops/action-gh-release@v2
with:
files: ${{ matrix.artifact-name }}.zip
tag_name: ${{ github.ref_name }}
generate_release_notes: true
ghcr.io/qaiu/netdisk-fast-download:${{ steps.tag.outputs.tag }}
ghcr.io/qaiu/netdisk-fast-download:latest
-2
View File
@@ -31,7 +31,6 @@ target/
sdkTest.log
app.yml
app-local.yml
secret.yml
#some local files
@@ -92,4 +91,3 @@ yarn-error.log*
**/${project.build.directory}/
**/${project.basedir}/target/
**/${basedir}/target/
.spec-workflow/
+3 -8
View File
@@ -10,13 +10,8 @@ COPY ./web-service/target/netdisk-fast-download-bin.zip .
RUN unzip netdisk-fast-download-bin.zip && \
mv netdisk-fast-download/* ./ && \
rm netdisk-fast-download-bin.zip && \
chmod +x run.sh && \
mkdir -p db logs
chmod +x run.sh
COPY ./docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
EXPOSE 6400 6401
EXPOSE 6401
RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser
ENTRYPOINT ["/docker-entrypoint.sh"]
ENTRYPOINT ["sh", "run.sh"]
+14 -9
View File
@@ -1,9 +1,9 @@
# 一款网盘分享链接云解析快速下载服务
QQ交流群:1017480890
<p align="center">
<a href="https://github.com/qaiu/netdisk-fast-download/actions/workflows/maven.yml"><img src="https://img.shields.io/github/actions/workflow/status/qaiu/netdisk-fast-download/build.yml?branch=main&style=flat"></a>
<a href="https://github.com/qaiu/netdisk-fast-download/actions/workflows/maven.yml"><img src="https://img.shields.io/github/actions/workflow/status/qaiu/netdisk-fast-download/maven.yml?branch=v0.1.9b8a&style=flat"></a>
<a href="https://www.oracle.com/cn/java/technologies/downloads"><img src="https://img.shields.io/badge/jdk-%3E%3D17-blue"></a>
<a href="https://vertx-china.github.io"><img src="https://img.shields.io/badge/vert.x-4.5.27-blue?style=flat"></a>
<a href="https://vertx-china.github.io"><img src="https://img.shields.io/badge/vert.x-4.5.24-blue?style=flat"></a>
<a href="https://raw.githubusercontent.com/qaiu/netdisk-fast-download/master/LICENSE"><img src="https://img.shields.io/github/license/qaiu/netdisk-fast-download?style=flat"></a>
<a href="https://github.com/qaiu/netdisk-fast-download/releases/"><img src="https://img.shields.io/github/v/release/qaiu/netdisk-fast-download?style=flat"></a>
<a href="https://atomgit.com/QAIU/netdisk-fast-download"><img src="https://atomgit.com/QAIU/netdisk-fast-download/star/badge.svg" alt="AtomGit"></a>
@@ -16,6 +16,10 @@ QQ交流群:1017480890
![alt text](web-front/img/image.png)
## 国内镜像
本项目同步托管于 **AtomGit**,国内访问更流畅:👉 [https://atomgit.com/QAIU/netdisk-fast-download](https://atomgit.com/QAIU/netdisk-fast-download)
## 介绍
> netdisk-fast-download网盘直链解析可以把云盘分享链接转为直链,可广泛应用于各类下载站,资源站,个人博客,图床,APP下载更新,视频点播等领域。支持市面各大主流云盘的文件分享以及文件夹分享链接,已支持蓝奏云/蓝奏云优享/移动云云空间/小飞机盘/亿方云/123云盘/Cloudreve等,支持加密分享,以及部分网盘文件夹分享。
@@ -36,12 +40,12 @@ curl -LOJ "https://lz.qaiu.top/parser?url=https://share.feijipan.com/s/Tk1F2kGQ&
```shell
wget -O bilibili.mp4 "https://lz.qaiu.top/parser?url=https://share.feijipan.com/s/Tk1F2kGQ&pwd=1234"
```
或者使用浏览器[直接访问](https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fparser%3Furl%3Dhttps%3A%2F%2Fwww.ilanzou.com%2Fs%2FCDx6xKbT&name=bilibili.mp4&ext=mp4):
或者使用浏览器[直接访问](https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fparser%3Furl%3Dhttps%3A%2F%2Fshare.feijipan.com%2Fs%2FTk1F2kGQ&name=bilibili.mp4&ext=mp4):
```
### 调用演示站下载:
https://lz.qaiu.top/parser?url=https://www.ilanzou.com/s/CDx6xKbT&pwd=1234
https://lz.qaiu.top/parser?url=https://share.feijipan.com/s/Tk1F2kGQ&pwd=1234
### 调用演示站预览:
https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fparser%3Furl%3Dhttps%3A%2F%2Fwww.ilanzou.com%2Fs%2FCDx6xKbT&name=bilibili.mp4&ext=mp4
https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.top%2Fparser%3Furl%3Dhttps%3A%2F%2Fshare.feijipan.com%2Fs%2FTk1F2kGQ&name=bilibili.mp4&ext=mp4
```
@@ -54,6 +58,7 @@ https://nfd-parser.github.io/nfd-preview/preview.html?src=https%3A%2F%2Flz.qaiu.
**注意⚠️小飞机解析有IP限制,多数云服务商的大陆IP会被拦截(可以自行配置代理),和本程序无关**
**注意⚠️收到很多用户反馈,小飞机近期封号频繁,请尽可能选择其他网盘分享**
**注意⚠️123云盘解析可能受账号地区、访问区域、出口IP等因素影响,即使已配置登录认证,跨区域访问仍可能失败,通常更接近网盘侧限制/风控,和本程序无关**
**注意⚠️请不要过度依赖 lz.qaiu.top,建议本地搭建或者云服务器自行搭建。请求量过多的话服务器可能会被云盘厂商限制,遇到解析失败的分享链接不要着急提issues,请先检查分享是否有效。**
## 网盘支持情况:
@@ -330,7 +335,7 @@ json返回数据格式示例:
| 移动云云空间(个人版) | √ | √(密码可忽略) | 5G(个人) | 不限大小 |
| 小飞机网盘 | √ | √ | 10G | 不限大小 |
| 360亿方云 | √ | √ | 100G(须实名) | 不限大小 |
| 123云盘 | | √ | 2T | 100G>100M需要登录) |
| 123云盘 | x | √ | 2T | 100G>100M需要登录) |
| 文叔叔 | √ | √ | 10G | 5GB |
| WPS云文档 | √ | X | 5G(免费) | 10M(免费)/2G(会员) |
| 夸克网盘 | x | √ | 10G | 不限大小 |
@@ -415,7 +420,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/v3.0.2/netdisk-fast-download-bin.zip
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.1.9b7/netdisk-fast-download-bin.zip
unzip netdisk-fast-download-bin.zip
cd netdisk-fast-download
bash service-install.sh
@@ -488,6 +493,8 @@ auths:
**注意:** 目前仅支持 123(ye)的认证配置。
**补充说明:** 123(ye)登录认证是必要条件之一,但不保证所有部署环境都稳定可用;若公网云服务器解析异常而本地/NAS环境正常,通常更可能与123侧跨区域访问限制或风控相关。建议优先在本地、家庭宽带或NAS环境部署,必要时再结合代理。
**技术栈:**
Jdk17+Vert.x4
@@ -512,5 +519,3 @@ Core模块集成Vert.x实现类似spring的注解式路由API
</p>
+2 -1
View File
@@ -1,5 +1,6 @@
#!/bin/bash
# set -x
LAUNCH_JAR="netdisk-fast-download.jar"
exec java -Xmx${JVM_XMX:-512M} ${JVM_OPTS} -jar "$LAUNCH_JAR" "$@"
nohup java -Xmx512M -jar "$LAUNCH_JAR" "$@" >startup.log 2>&1 &
tail -f startup.log
+1 -1
View File
@@ -65,7 +65,7 @@
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.11</version>
<version>42.7.3</version>
</dependency>
</dependencies>
@@ -53,7 +53,7 @@ public class CreateDatabase {
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS " + dbName + " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
LOGGER.info(">>>>>>>>>>> 数据库'{}'创建成功 <<<<<<<<<<<<", dbName);
} catch (SQLException e) {
LOGGER.error("创建数据库失败", e);
e.printStackTrace();
}
}
@@ -24,39 +24,35 @@ import java.util.*;
* @author <a href="https://qaiu.top">QAIU</a>
*/
public class CreateTable {
public static final Map<Class<?>, String> javaProperty2SqlColumnMap;
static {
Map<Class<?>, String> map = new HashMap<>();
public static Map<Class<?>, String> javaProperty2SqlColumnMap = new HashMap<>() {{
// Java类型到SQL类型的映射
map.put(Integer.class, "INT");
map.put(Short.class, "SMALLINT");
map.put(Byte.class, "TINYINT");
map.put(Long.class, "BIGINT");
map.put(java.math.BigDecimal.class, "DECIMAL");
map.put(Double.class, "DOUBLE");
map.put(Float.class, "REAL");
map.put(Boolean.class, "BOOLEAN");
map.put(String.class, "VARCHAR");
map.put(Date.class, "TIMESTAMP");
map.put(java.time.LocalDateTime.class, "TIMESTAMP");
map.put(java.sql.Timestamp.class, "TIMESTAMP");
map.put(java.sql.Date.class, "DATE");
map.put(java.sql.Time.class, "TIME");
put(Integer.class, "INT");
put(Short.class, "SMALLINT");
put(Byte.class, "TINYINT");
put(Long.class, "BIGINT");
put(java.math.BigDecimal.class, "DECIMAL");
put(Double.class, "DOUBLE");
put(Float.class, "REAL");
put(Boolean.class, "BOOLEAN");
put(String.class, "VARCHAR");
put(Date.class, "TIMESTAMP");
put(java.time.LocalDateTime.class, "TIMESTAMP");
put(java.sql.Timestamp.class, "TIMESTAMP");
put(java.sql.Date.class, "DATE");
put(java.sql.Time.class, "TIME");
// 基本数据类型
map.put(int.class, "INT");
map.put(short.class, "SMALLINT");
map.put(byte.class, "TINYINT");
map.put(long.class, "BIGINT");
map.put(double.class, "DOUBLE");
map.put(float.class, "REAL");
map.put(boolean.class, "BOOLEAN");
javaProperty2SqlColumnMap = Collections.unmodifiableMap(map);
}
put(int.class, "INT");
put(short.class, "SMALLINT");
put(byte.class, "TINYINT");
put(long.class, "BIGINT");
put(double.class, "DOUBLE");
put(float.class, "REAL");
put(boolean.class, "BOOLEAN");
}};
private static final Logger LOGGER = LoggerFactory.getLogger(CreateTable.class);
public static final String UNIQUE_PREFIX = "idx_";
public static String UNIQUE_PREFIX = "idx_";
private static Case getCase(Class<?> clz) {
return switch (clz.getName()) {
@@ -17,7 +17,7 @@ import org.slf4j.LoggerFactory;
*
* @author <a href="https://qaiu.top">QAIU</a>
*/
public class JDBCPoolInit implements AutoCloseable {
public class JDBCPoolInit {
private static final Logger LOGGER = LoggerFactory.getLogger(JDBCPoolInit.class);
@@ -101,16 +101,4 @@ public class JDBCPoolInit implements AutoCloseable {
synchronized public JDBCPool getPool() {
return pool;
}
/**
* 关闭连接池,释放数据库资源
*/
@Override
public synchronized void close() {
if (pool != null) {
pool.close();
LOGGER.info("数据库连接池已关闭: URL={}", url);
pool = null;
}
}
}
+10 -78
View File
@@ -16,13 +16,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.management.ManagementFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.LockSupport;
import static cn.qaiu.vx.core.util.ConfigConstant.*;
@@ -47,25 +43,11 @@ public final class Deploy {
private Handler<JsonObject> handle;
private Thread mainThread;
private final List<Runnable> preShutdownTasks = new CopyOnWriteArrayList<>();
private final List<Runnable> postShutdownTasks = new CopyOnWriteArrayList<>();
public static Deploy instance() {
return INSTANCE;
}
public void addPreShutdownTask(Runnable task) {
if (task != null) {
preShutdownTasks.add(task);
}
}
public void addPostShutdownTask(Runnable task) {
if (task != null) {
postShutdownTasks.add(task);
}
}
/**
*
* @param args 启动参数
@@ -80,19 +62,10 @@ public final class Deploy {
path.append("-").append(args[0].replace("app-",""));
}
// 读取yml配置,优先当前目录,其次 resources/ 子目录
String configFile = path + ".yml";
if (!Files.exists(Path.of(configFile)) && Files.exists(Path.of("resources", configFile))) {
path.insert(0, "resources/");
LOGGER.info("从 resources/ 目录加载配置: {}", path + ".yml");
}
// 读取yml配置
ConfigUtil.readYamlConfig(path.toString(), tempVertx)
.onSuccess(this::readConf)
.onFailure(err -> {
LOGGER.error("读取配置文件失败: {}", err.getMessage(), err);
LockSupport.unpark(mainThread);
System.exit(-1);
});
.onFailure(Throwable::printStackTrace);
LockSupport.park();
deployVerticle();
}
@@ -149,16 +122,9 @@ public final class Deploy {
customConfig = globalConfig.getJsonObject(CUSTOM);
JsonObject vertxConfig = globalConfig.getJsonObject(VERTX);
JsonObject vertxOptionsConfig = vertxConfig.copy();
if (vertxOptionsConfig.getInteger(EVENT_LOOP_POOL_SIZE, 0) == 0) {
vertxOptionsConfig.remove(EVENT_LOOP_POOL_SIZE);
}
if (vertxOptionsConfig.getInteger("workerPoolSize", 0) == 0) {
vertxOptionsConfig.remove("workerPoolSize");
}
Integer vertxConfigELPS = vertxConfig.getInteger(EVENT_LOOP_POOL_SIZE, 0);
var vertxOptions = vertxOptionsConfig.isEmpty() ?
new VertxOptions() : new VertxOptions(vertxOptionsConfig);
Integer vertxConfigELPS = vertxConfig.getInteger(EVENT_LOOP_POOL_SIZE);
var vertxOptions = vertxConfigELPS == 0 ?
new VertxOptions() : new VertxOptions(vertxConfig);
// vertxOptions.setAddressResolverOptions(
// new AddressResolverOptions().
@@ -171,46 +137,30 @@ public final class Deploy {
vertxOptions.getWorkerPoolSize());
var vertx = Vertx.vertx(vertxOptions);
VertxHolder.init(vertx);
// 注册 ShutdownHook,确保进程退出时优雅关闭资源
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
LOGGER.info("JVM shutting down...");
runShutdownTasks("before Vert.x close", preShutdownTasks);
try {
LOGGER.info("Closing Vert.x...");
vertx.close().toCompletionStage().toCompletableFuture().get(10, java.util.concurrent.TimeUnit.SECONDS);
LOGGER.info("Vert.x closed successfully");
} catch (Exception e) {
LOGGER.warn("Vert.x close error or timeout", e);
} finally {
runShutdownTasks("after Vert.x close", postShutdownTasks);
}
}));
//配置保存在共享数据中
var sharedData = vertx.sharedData();
LocalMap<String, Object> localMap = sharedData.getLocalMap(LOCAL);
localMap.put(GLOBAL_CONFIG, globalConfig);
localMap.put(CUSTOM_CONFIG, customConfig);
localMap.put(SERVER, globalConfig.getJsonObject(SERVER));
WorkerExecutor otherHandleExecutor = vertx.createSharedWorkerExecutor("other-handle");
var future0 = otherHandleExecutor.executeBlocking(() -> {
var future0 = vertx.createSharedWorkerExecutor("other-handle")
.executeBlocking(() -> {
handle.handle(globalConfig);
return "Other handle complete";
});
future0.onSuccess(res -> {
otherHandleExecutor.close();
LOGGER.info(res);
// 部署 路由、异步service、反向代理 服务
var future1 = vertx.deployVerticle(RouterVerticle.class, getWorkDeploymentOptions("Router"));
var future2 = vertx.deployVerticle(ServiceVerticle.class, getWorkDeploymentOptions("Service"));
var future3 = vertx.deployVerticle(ReverseProxyVerticle.class, getWorkDeploymentOptions("proxy", 1));
var future3 = vertx.deployVerticle(ReverseProxyVerticle.class, getWorkDeploymentOptions("proxy"));
JsonObject jsonObject = ((JsonObject) localMap.get(GLOBAL_CONFIG)).getJsonObject("proxy-server");
if (jsonObject != null) {
genPwd(jsonObject);
var future4 = vertx.deployVerticle(HttpProxyVerticle.class, getWorkDeploymentOptions("proxy", 1));
var future4 = vertx.deployVerticle(HttpProxyVerticle.class, getWorkDeploymentOptions("proxy"));
future4.onSuccess(LOGGER::info);
future4.onFailure(e -> LOGGER.error("Other handle error", e));
Future.all(future1, future2, future3, future4)
@@ -222,10 +172,7 @@ public final class Deploy {
.onFailure(this::deployVerticalFailed);
}
}).onFailure(e -> {
otherHandleExecutor.close();
LOGGER.error("Other handle error", e);
});
}).onFailure(e -> LOGGER.error("Other handle error", e));
}
private static void genPwd(JsonObject jsonObject) {
@@ -242,21 +189,6 @@ public final class Deploy {
jsonObject.getString("password"));
LOGGER.info("==============server info================");
}
private static void runShutdownTasks(String stage, List<Runnable> tasks) {
if (tasks.isEmpty()) {
return;
}
LOGGER.info("Running {} shutdown tasks: {}", stage, tasks.size());
for (Runnable task : tasks) {
try {
task.run();
} catch (Exception e) {
LOGGER.warn("Shutdown task failed at stage {}", stage, e);
}
}
}
/**
* 部署失败
*
@@ -1,20 +1,14 @@
package cn.qaiu.vx.core.base;
import cn.qaiu.vx.core.annotaions.HandleSortFilter;
import cn.qaiu.vx.core.interceptor.AfterInterceptor;
import cn.qaiu.vx.core.model.JsonResult;
import cn.qaiu.vx.core.util.CommonUtil;
import cn.qaiu.vx.core.util.ReflectionUtil;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static cn.qaiu.vx.core.util.ResponseUtil.*;
@@ -28,10 +22,9 @@ public interface BaseHttpApi {
// 需要扫描注册的Router路径
Reflections reflections = ReflectionUtil.getReflections();
Logger LOGGER = LoggerFactory.getLogger(BaseHttpApi.class);
default void doFireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject) {
if (!isResponseDone(ctx)) {
if (!ctx.response().ended()) {
fireJsonObjectResponse(ctx, jsonObject);
}
handleAfterInterceptor(ctx, jsonObject);
@@ -39,14 +32,14 @@ public interface BaseHttpApi {
default <T> void doFireJsonResultResponse(RoutingContext ctx, JsonResult<T> jsonResult) {
if (!isResponseDone(ctx)) {
if (!ctx.response().ended()) {
fireJsonResultResponse(ctx, jsonResult);
}
handleAfterInterceptor(ctx, jsonResult.toJsonObject());
}
default void doFireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject, int statusCode) {
if (!isResponseDone(ctx)) {
if (!ctx.response().ended()) {
fireJsonObjectResponse(ctx, jsonObject, statusCode);
}
handleAfterInterceptor(ctx, jsonObject);
@@ -54,78 +47,30 @@ public interface BaseHttpApi {
default <T> void doFireJsonResultResponse(RoutingContext ctx, JsonResult<T> jsonResult, int statusCode) {
if (!isResponseDone(ctx)) {
if (!ctx.response().ended()) {
fireJsonResultResponse(ctx, jsonResult, statusCode);
}
handleAfterInterceptor(ctx, jsonResult.toJsonObject());
}
default Set<AfterInterceptor> getAfterInterceptor() {
return AfterInterceptorHolder.INSTANCES;
}
class AfterInterceptorHolder {
private static final Set<AfterInterceptor> INSTANCES = loadAfterInterceptors();
private static Set<AfterInterceptor> loadAfterInterceptors() {
Set<Class<? extends AfterInterceptor>> afterInterceptorClassSet =
reflections.getSubTypesOf(AfterInterceptor.class);
if (afterInterceptorClassSet == null || afterInterceptorClassSet.isEmpty()) {
return Collections.emptySet();
}
return afterInterceptorClassSet.stream()
.filter(AfterInterceptorHolder::isEnabled)
.sorted(AfterInterceptorHolder::compareOrder)
.map(AfterInterceptorHolder::newInterceptor)
.filter(Objects::nonNull)
.collect(Collectors.collectingAndThen(
Collectors.toCollection(LinkedHashSet::new),
Collections::unmodifiableSet));
}
private static boolean isEnabled(Class<? extends AfterInterceptor> clazz) {
HandleSortFilter sort = clazz.getAnnotation(HandleSortFilter.class);
return sort == null || sort.value() >= 0;
}
private static int compareOrder(Class<? extends AfterInterceptor> left, Class<? extends AfterInterceptor> right) {
return Integer.compare(order(left), order(right));
}
private static int order(Class<? extends AfterInterceptor> clazz) {
HandleSortFilter sort = clazz.getAnnotation(HandleSortFilter.class);
return sort == null ? 0 : sort.value();
}
private static AfterInterceptor newInterceptor(Class<? extends AfterInterceptor> clazz) {
try {
return ReflectionUtil.newWithNoParam(clazz);
} catch (Exception e) {
LOGGER.warn("AfterInterceptor 初始化失败,已跳过: {}", clazz.getName(), e);
return null;
}
Set<Class<? extends AfterInterceptor>> afterInterceptorClassSet =
reflections.getSubTypesOf(AfterInterceptor.class);
if (afterInterceptorClassSet == null) {
return null;
}
return CommonUtil.sortClassSet(afterInterceptorClassSet);
}
default void handleAfterInterceptor(RoutingContext ctx, JsonObject jsonObject) {
if (ctx.response().closed()) {
return;
}
Set<AfterInterceptor> afterInterceptor = getAfterInterceptor();
afterInterceptor.forEach(ai -> {
try {
ai.handle(ctx, jsonObject);
} catch (Exception e) {
LOGGER.warn("AfterInterceptor 执行失败: {}", ai.getClass().getName(), e);
}
});
if (!isResponseDone(ctx)) {
if (afterInterceptor != null) {
afterInterceptor.forEach(ai -> ai.handle(ctx, jsonObject));
}
if (!ctx.response().ended()) {
fireTextResponse(ctx, "handleAfterInterceptor: response not end");
}
}
default boolean isResponseDone(RoutingContext ctx) {
return ctx.response().ended() || ctx.response().closed();
}
}
@@ -34,7 +34,6 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -97,9 +96,7 @@ public class RouterHandlerFactory implements BaseHttpApi {
mainRouter.route().handler(CorsHandler.create().addRelativeOrigin(".*").allowCredentials(true).allowedMethods(httpMethods));
// 配置文件上传路径
mainRouter.route().handler(BodyHandler.create()
.setUploadsDirectory("uploads")
.setBodyLimit(2L * 1024 * 1024));
mainRouter.route().handler(BodyHandler.create().setUploadsDirectory("uploads"));
// 拦截器
Set<Handler<RoutingContext>> interceptorSet = getInterceptorSet();
@@ -130,9 +127,8 @@ public class RouterHandlerFactory implements BaseHttpApi {
// 错误请求处理
mainRouter.errorHandler(405, ctx -> doFireJsonResultResponse(ctx, JsonResult
.error("Method Not Allowed", 405)));
mainRouter.errorHandler(404, ctx -> {
ctx.response().setStatusCode(404).end("404 not found");
});
mainRouter.errorHandler(404, ctx -> ctx.response().setStatusCode(404).setChunked(true)
.end("Internal server error: 404 not found"));
return mainRouter;
}
@@ -178,14 +174,13 @@ public class RouterHandlerFactory implements BaseHttpApi {
route.handler(TimeoutHandler.create(SharedDataUtil.getCustomConfig().getInteger(ROUTE_TIME_OUT)));
route.handler(ResponseTimeHandler.create());
route.handler(ctx -> handlerMethod(instance, method, ctx)).failureHandler(ctx -> {
if (isResponseDone(ctx)) return;
if (ctx.response().ended()) return;
// 超时处理器状态码503
if (ctx.statusCode() == 503 || ctx.failure() == null) {
doFireJsonResultResponse(ctx, JsonResult.error("未知异常, 请联系管理员"), 503);
} else {
LOGGER.error("路由处理失败", ctx.failure());
String msg = ctx.failure() != null ? ctx.failure().getMessage() : "未知异常";
doFireJsonResultResponse(ctx, JsonResult.error(msg), 500);
ctx.failure().printStackTrace();
doFireJsonResultResponse(ctx, JsonResult.error(ctx.failure().getMessage()), 500);
}
});
} else if (method.isAnnotationPresent(SockRouteMapper.class)) {
@@ -203,7 +198,7 @@ public class RouterHandlerFactory implements BaseHttpApi {
try {
ReflectionUtil.invokeWithArguments(method, instance, sock);
} catch (Throwable e) {
LOGGER.error("WebSocket处理异常", e);
e.printStackTrace();
}
});
if (url.endsWith("*")) {
@@ -327,7 +322,7 @@ public class RouterHandlerFactory implements BaseHttpApi {
parameterValueList.put(k, entity);
}
} catch (ClassNotFoundException e) {
LOGGER.error("实体类绑定异常: {}", typeName, e);
e.printStackTrace();
}
}
});
@@ -370,7 +365,7 @@ public class RouterHandlerFactory implements BaseHttpApi {
Object entity = ParamUtil.multiMapToEntity(queryParams, aClass);
parameterValueList.put(k, entity);
} catch (Exception e) {
LOGGER.error("参数绑定异常: {}", v.getRight().getName(), e);
e.printStackTrace();
}
} else if (parameterValueList.get(k) == null
&& JsonObject.class.getName().equals(v.getRight().getName())) {
@@ -397,43 +392,38 @@ public class RouterHandlerFactory implements BaseHttpApi {
if (data instanceof JsonResult jsonResult) {
doFireJsonResultResponse(ctx, (JsonResult<?>) data, jsonResult.getCode());
} else if (data instanceof JsonObject) {
}
if (data instanceof JsonObject) {
doFireJsonObjectResponse(ctx, ((JsonObject) data));
} else if (data instanceof Future) { // 处理异步响应
Future<?> responseFuture = (Future<?>) data;
AtomicReference<RoutingContext> ctxRef = new AtomicReference<>(ctx);
ctx.addEndHandler(v -> ctxRef.set(null));
responseFuture.onComplete(ar -> {
RoutingContext responseCtx = ctxRef.getAndSet(null);
if (responseCtx == null || isResponseDone(responseCtx)) {
return;
((Future<?>) data).onSuccess(res -> {
if (res instanceof JsonResult jsonResult) {
doFireJsonResultResponse(ctx, jsonResult, jsonResult.getCode());
}
if (ar.succeeded()) {
Object res = ar.result();
if (res instanceof JsonResult jsonResult) {
doFireJsonResultResponse(responseCtx, jsonResult, jsonResult.getCode());
} else if (res instanceof JsonObject) {
doFireJsonObjectResponse(responseCtx, ((JsonObject) res));
} else if (res != null) {
doFireJsonResultResponse(responseCtx, JsonResult.data(res));
} else {
doFireJsonResultResponse(responseCtx, JsonResult.data(null));
}
if (res instanceof JsonObject) {
doFireJsonObjectResponse(ctx, ((JsonObject) res));
} else if (res != null) {
doFireJsonResultResponse(ctx, JsonResult.data(res));
} else {
Throwable e = ar.cause();
LOGGER.error("请求处理失败", e);
String msg = e != null && e.getMessage() != null ? e.getMessage() : "服务器内部错误";
doFireJsonResultResponse(responseCtx, JsonResult.error(msg), 500);
doFireJsonResultResponse(ctx, JsonResult.data(null));
}
});
}).onFailure(e -> doFireJsonResultResponse(ctx, JsonResult.error(e.getMessage()), 500));
} else {
doFireJsonResultResponse(ctx, JsonResult.data(data));
}
}
} catch (Throwable e) {
LOGGER.error("请求处理异常", e);
String msg = e.getMessage() != null ? e.getMessage() : "服务器内部错误";
doFireJsonResultResponse(ctx, JsonResult.error(msg), 500);
e.printStackTrace();
String err = e.getMessage();
if (e.getCause() != null) {
if (e.getCause() instanceof InvocationTargetException) {
err = ((InvocationTargetException) e.getCause()).getTargetException().getMessage();
} else {
err = e.getCause().getMessage();
}
}
doFireJsonResultResponse(ctx, JsonResult.error(err), 500);
}
}
@@ -17,8 +17,6 @@ import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
@@ -31,16 +29,6 @@ public class CommonUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(CommonUtil.class);
/** 正则表达式缓存,避免每次调用重新编译 */
private static final ConcurrentHashMap<String, Pattern> PATTERN_CACHE = new ConcurrentHashMap<>();
/**
* 获取预编译的 Pattern(带缓存)
*/
private static Pattern getCachedPattern(String regex) {
return PATTERN_CACHE.computeIfAbsent(regex, Pattern::compile);
}
/**
* 匹配正则list
*
@@ -51,7 +39,7 @@ public class CommonUtil {
public static boolean matchRegList(List<?> regList, String destStr) {
// 判断是否忽略
for (Object ignores : regList) {
if (getCachedPattern(ignores.toString()).matcher(destStr).matches()) {
if (destStr.matches(ignores.toString())) {
return true;
}
}
@@ -159,15 +147,13 @@ public class CommonUtil {
public static String getAppVersion() {
if (null == appVersion) {
Properties properties = new Properties();
try (var is = CommonUtil.class.getClassLoader().getResourceAsStream("app.properties")) {
if (is != null) {
properties.load(is);
if (!properties.isEmpty()) {
appVersion = properties.getProperty("app.version") + "build" + properties.getProperty("build");
}
try {
properties.load(CommonUtil.class.getClassLoader().getResourceAsStream("app.properties"));
if (!properties.isEmpty()) {
appVersion = properties.getProperty("app.version") + "build" + properties.getProperty("build");
}
} catch (IOException e) {
LOGGER.error("读取app.properties失败", e);
e.printStackTrace();
}
}
return appVersion;
@@ -10,8 +10,6 @@ import io.vertx.core.json.JsonObject;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* 异步读取配置工具类
@@ -64,35 +62,12 @@ public class ConfigUtil {
// 异步获取配置
// 成功直接完成 promise
retriever.getConfig()
.onSuccess(config -> {
promise.complete(config);
retriever.close();
})
.onSuccess(promise::complete)
.onFailure(err -> {
// 配置读取失败,直接返回失败 Future
promise.fail(new RuntimeException(
"读取配置文件失败: " + path, err));
retriever.close();
// 读取失败时,尝试从 resources/ 子目录读取(兼容 Docker 卷挂载场景)
String resourcesPath = "resources/" + path;
if (!path.startsWith("resources/") && Files.exists(Path.of(resourcesPath))) {
ConfigStoreOptions fallbackStore = new ConfigStoreOptions()
.setType("file")
.setFormat(format)
.setConfig(new JsonObject().put("path", resourcesPath));
ConfigRetriever fallbackRetriever = ConfigRetriever
.create(vertx, new ConfigRetrieverOptions().addStore(fallbackStore));
fallbackRetriever.getConfig()
.onSuccess(config -> {
promise.complete(config);
fallbackRetriever.close();
})
.onFailure(e2 -> {
promise.fail(new RuntimeException(
"读取配置文件失败: " + path + " (也尝试了 " + resourcesPath + ")", e2));
fallbackRetriever.close();
});
} else {
promise.fail(new RuntimeException(
"读取配置文件失败: " + path, err));
}
});
return promise.future();
@@ -4,41 +4,17 @@ import io.vertx.core.Future;
import io.vertx.core.Promise;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureUtils {
/** 默认同步等待超时时间(秒) */
private static final long DEFAULT_TIMEOUT_SECONDS = 120;
public static <T> T getResult(Future<T> future) {
try {
return future.toCompletionStage().toCompletableFuture()
.get(DEFAULT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("线程被中断", e);
} catch (TimeoutException e) {
throw new RuntimeException("等待Future超时(" + DEFAULT_TIMEOUT_SECONDS + "秒)", e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
throw new RuntimeException(cause != null ? cause : e);
}
}
public static <T> T getResult(Future<T> future) {
try {
return future.toCompletionStage().toCompletableFuture().get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
public static <T> T getResult(Promise<T> promise) {
try {
return promise.future().toCompletionStage().toCompletableFuture()
.get(DEFAULT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("线程被中断", e);
} catch (TimeoutException e) {
throw new RuntimeException("等待Promise超时(" + DEFAULT_TIMEOUT_SECONDS + "秒)", e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
throw new RuntimeException(cause != null ? cause : e);
}
return promise.future().toCompletionStage().toCompletableFuture().join();
}
}
@@ -1,7 +1,7 @@
package cn.qaiu.vx.core.util;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* vertx 上下文外的本地容器 为不在vertx线程的方法传递数据
@@ -10,10 +10,11 @@ import java.util.concurrent.ConcurrentHashMap;
* @author <a href="https://qaiu.top">QAIU</a>
*/
public class LocalConstant {
private static final Map<String, Object> LOCAL_CONST = new ConcurrentHashMap<>();
private static final Map<String, Object> LOCAL_CONST = new HashMap<>();
public static Map<String, Object> put(String k, Object v) {
LOCAL_CONST.putIfAbsent(k, v);
if (LOCAL_CONST.containsKey(k)) return LOCAL_CONST;
LOCAL_CONST.put(k, v);
return LOCAL_CONST;
}
@@ -36,20 +36,16 @@ public final class ParamUtil {
public static MultiMap paramsToMap(String paramString) {
MultiMap entries = MultiMap.caseInsensitiveMultiMap();
if (paramString == null || paramString.isEmpty()) return entries;
if (paramString == null) return entries;
String[] params = paramString.split("&");
if (params.length == 0) return entries;
for (String param : params) {
if (param == null || param.isEmpty()) {
continue;
}
String[] kv = param.split("=", 2);
String[] kv = param.split("=");
if (kv.length == 2) {
entries.set(kv[0], kv[1]);
} else if (kv.length == 1) {
} else {
entries.set(kv[0], "");
}
// kv.length == 0 时(空字符串),跳过
}
return entries;
}
@@ -24,10 +24,6 @@ import java.lang.reflect.Method;
import java.net.URL;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static cn.qaiu.vx.core.util.ConfigConstant.BASE_LOCATIONS;
@@ -40,17 +36,9 @@ import static cn.qaiu.vx.core.util.ConfigConstant.BASE_LOCATIONS;
*/
public final class ReflectionUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);
// 缓存Reflections实例,避免重复扫描(每次扫描约35K+值,耗时1-3秒,占用大量内存)
private static final Map<String, Reflections> REFLECTIONS_CACHE = new java.util.concurrent.ConcurrentHashMap<>();
// 预编译的类型匹配正则,避免每次请求重新编译
private static final Pattern BASIC_TYPE_PATTERN = Pattern.compile(
"^java\\.lang\\.((Boolean)|(Character)|(Byte)|(Short)|(Integer)|(Long)|(Float)|(Double)|(String))$");
private static final Pattern BASIC_TYPE_ARRAY_PATTERN = Pattern.compile(
"^(boolean|char|byte|short|int|long|float|double|String)\\[]$");
/**
* 以默认配置的基础包路径获取反射器
*
@@ -140,7 +128,7 @@ public final class ReflectionUtil {
parameterTypes[j - k]));
}
} catch (NotFoundException e) {
LOGGER.error("获取方法参数失败", e);
e.printStackTrace();
}
return paramMap;
}
@@ -195,7 +183,7 @@ public final class ReflectionUtil {
try {
return DateUtils.parseDate(value, fmt);
} catch (ParseException e) {
LOGGER.error("日期解析失败: {}", value, e);
e.printStackTrace();
throw new RuntimeException("无法将格式化日期");
}
default:
@@ -227,7 +215,7 @@ public final class ReflectionUtil {
}
return arr;
} catch (Exception e) {
LOGGER.error("数组类型转换失败: {}", value, e);
e.printStackTrace();
}
return null;
}
@@ -241,7 +229,8 @@ public final class ReflectionUtil {
if (ctClass.isPrimitive() || "java.util.Date".equals(ctClass.getName())) {
return true;
}
return BASIC_TYPE_PATTERN.matcher(ctClass.getName()).matches();
return ctClass.getName().matches("^java\\.lang\\.((Boolean)|(Character)|(Byte)|(Short)|(Integer)|(Long)|" +
"(Float)|(Double)|(String))$");
}
/**
@@ -252,7 +241,7 @@ public final class ReflectionUtil {
public static boolean isBasicTypeArray(CtClass ctClass) {
if (!ctClass.isArray()) {
return false;
} else return BASIC_TYPE_ARRAY_PATTERN.matcher(ctClass.getName()).matches();
} else return (ctClass.getName().matches("^(boolen|char|byte|short|int|long|float|double|String)\\[]$"));
}
/**
@@ -12,21 +12,14 @@ import static io.vertx.core.http.HttpHeaders.CONTENT_TYPE;
public class ResponseUtil {
public static void redirect(HttpServerResponse response, String url) {
if (response.ended() || response.closed()) {
return;
}
response.putHeader(CONTENT_TYPE, "text/html; charset=utf-8")
.putHeader("Referrer-Policy", "no-referrer")
.putHeader(HttpHeaders.LOCATION, url).setStatusCode(302).end();
}
public static void redirect(HttpServerResponse response, String url, Promise<?> promise) {
try {
redirect(response, url);
promise.tryComplete();
} catch (Throwable t) {
promise.tryFail(t);
}
redirect(response, url);
promise.complete();
}
public static void fireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject) {
@@ -38,18 +31,12 @@ public class ResponseUtil {
}
public static void fireJsonObjectResponse(RoutingContext ctx, JsonObject jsonObject, int statusCode) {
if (ctx.response().ended() || ctx.response().closed()) {
return;
}
ctx.response().putHeader(CONTENT_TYPE, "application/json; charset=utf-8")
.setStatusCode(statusCode)
.end(jsonObject.encode());
}
public static void fireJsonObjectResponse(HttpServerResponse ctx, JsonObject jsonObject, int statusCode) {
if (ctx.ended() || ctx.closed()) {
return;
}
ctx.putHeader(CONTENT_TYPE, "application/json; charset=utf-8")
.setStatusCode(statusCode)
.end(jsonObject.encode());
@@ -68,16 +55,10 @@ public class ResponseUtil {
}
public static void fireTextResponse(RoutingContext ctx, String text) {
if (ctx.response().ended() || ctx.response().closed()) {
return;
}
ctx.response().putHeader(CONTENT_TYPE, "text/html; charset=utf-8").end(text);
}
public static void sendError(RoutingContext ctx, int statusCode) {
if (ctx.response().ended() || ctx.response().closed()) {
return;
}
ctx.response().setStatusCode(statusCode).end();
}
}
@@ -3,6 +3,7 @@ package cn.qaiu.vx.core.util;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.shareddata.LocalMap;
import io.vertx.core.shareddata.SharedData;
/**
* vertx 共享数据
@@ -12,8 +13,10 @@ import io.vertx.core.shareddata.LocalMap;
*/
public class SharedDataUtil {
public static io.vertx.core.shareddata.SharedData shareData() {
return VertxHolder.getVertxInstance().sharedData();
private static final SharedData sharedData = VertxHolder.getVertxInstance().sharedData();
public static SharedData shareData() {
return sharedData;
}
public static LocalMap<String, Object> getLocalMap(String key) {
@@ -21,7 +24,7 @@ public class SharedDataUtil {
}
public static <T> LocalMap<String, T> getLocalMapWithCast(String key) {
return shareData().getLocalMap(key);
return sharedData.getLocalMap(key);
}
public static JsonObject getJsonConfig(String key) {
@@ -1,13 +1,10 @@
package cn.qaiu.vx.core.verticle;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.http.*;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetSocket;
import io.vertx.core.net.ProxyOptions;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@@ -27,16 +24,13 @@ public class HttpProxyVerticle extends AbstractVerticle {
private HttpClient httpClient;
private NetClient netClient;
private HttpServer httpServer;
private volatile boolean stopping = false;
private JsonObject proxyPreConf;
private JsonObject proxyServerConf;
@Override
public void start(io.vertx.core.Promise<Void> startPromise) {
stopping = false;
public void start() {
proxyServerConf = ((JsonObject)vertx.sharedData().getLocalMap(LOCAL).get(GLOBAL_CONFIG)).getJsonObject("proxy-server");
proxyPreConf = ((JsonObject)vertx.sharedData().getLocalMap(LOCAL).get(GLOBAL_CONFIG)).getJsonObject("proxy-pre");
Integer serverPort = proxyServerConf.getInteger("port");
@@ -47,12 +41,7 @@ public class HttpProxyVerticle extends AbstractVerticle {
}
// 初始化 HTTP 客户端,用于向目标服务器发送 HTTP 请求
HttpClientOptions httpClientOptions = new HttpClientOptions()
.setMaxPoolSize(64)
.setMaxWaitQueueSize(256)
.setConnectTimeout(15000)
.setIdleTimeout(60)
.setKeepAlive(true);
HttpClientOptions httpClientOptions = new HttpClientOptions();
if (proxyOptions != null) {
httpClientOptions.setProxyOptions(proxyOptions);
}
@@ -65,14 +54,14 @@ public class HttpProxyVerticle extends AbstractVerticle {
httpServerOptions.setClientAuth(ClientAuth.REQUIRED);
}
httpServer = vertx.createHttpServer(httpServerOptions);
httpServer.requestHandler(this::handleClientRequest);
HttpServer server = vertx.createHttpServer();
server.requestHandler(this::handleClientRequest);
// 初始化 NetClient,用于在 CONNECT 请求中建立 TCP 连接隧道
NetClientOptions netClientOptions = new NetClientOptions();
if (proxyOptions != null) {
netClientOptions.setProxyOptions(proxyOptions);
httpClientOptions.setProxyOptions(proxyOptions);
}
netClient = vertx.createNetClient(netClientOptions
@@ -80,22 +69,16 @@ public class HttpProxyVerticle extends AbstractVerticle {
.setTrustAll(true));
// 启动 HTTP 代理服务器
httpServer.listen(serverPort)
.onSuccess(res -> {
LOGGER.info("HTTP Proxy server started on port {}", serverPort);
startPromise.complete();
})
.onFailure(err -> {
LOGGER.error("Failed to start HTTP Proxy server: " + err.getMessage(), err);
closeClients().onComplete(close -> startPromise.fail(err));
});
server.listen(serverPort)
.onSuccess(res-> LOGGER.info("HTTP Proxy server started on port {}", serverPort))
.onFailure(err-> LOGGER.error("Failed to start HTTP Proxy server: " + err.getMessage()));
}
// 处理 HTTP CONNECT 请求,用于代理 HTTPS 流量
private void handleConnectRequest(HttpServerRequest clientRequest) {
String[] uriParts = clientRequest.uri().split(":");
if (uriParts.length != 2) {
failClientResponse(clientRequest.response(), 400, "Bad Request: Invalid URI format");
clientRequest.response().setStatusCode(400).end("Bad Request: Invalid URI format");
return;
}
@@ -105,82 +88,57 @@ public class HttpProxyVerticle extends AbstractVerticle {
try {
targetPort = Integer.parseInt(uriParts[1]);
} catch (NumberFormatException e) {
failClientResponse(clientRequest.response(), 400, "Bad Request: Invalid port");
clientRequest.response().setStatusCode(400).end("Bad Request: Invalid port");
return;
}
clientRequest.pause();
// 通过 NetClient 连接目标服务器并创建隧道
try {
netClient.connect(targetPort, targetHost)
.onSuccess(targetSocket -> {
// Upgrade client connection to NetSocket and implement bidirectional data flow
clientRequest.toNetSocket()
.onSuccess(clientSocket -> {
clientSocket.pipeTo(targetSocket)
.onFailure(err -> {
LOGGER.debug("CONNECT client -> target pipe closed", err);
closeTunnelSockets(clientSocket, targetSocket);
});
targetSocket.pipeTo(clientSocket)
.onFailure(err -> {
LOGGER.debug("CONNECT target -> client pipe closed", err);
closeTunnelSockets(clientSocket, targetSocket);
});
netClient.connect(targetPort, targetHost)
.onSuccess(targetSocket -> {
// Upgrade client connection to NetSocket and implement bidirectional data flow
clientRequest.toNetSocket()
.onSuccess(clientSocket -> {
// Set up bidirectional data forwarding
clientSocket.handler(targetSocket::write);
targetSocket.handler(clientSocket::write);
// Close the other socket when one side closes
clientSocket.closeHandler(v -> targetSocket.close());
targetSocket.closeHandler(v -> clientSocket.close());
})
.onFailure(clientSocketAttempt -> {
System.err.println("Failed to upgrade client connection to socket: " + clientSocketAttempt.getMessage());
targetSocket.close();
failClientRequestAndClose(clientRequest, 500, "Internal Server Error");
});
})
.onFailure(connectionAttempt -> {
LOGGER.warn("Failed to connect to target: {}", connectionAttempt.getMessage());
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Unable to connect to target");
});
} catch (Exception e) {
LOGGER.warn("CONNECT 请求创建失败", e);
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Unable to connect to target");
}
// Close the other socket when one side closes
clientSocket.closeHandler(v -> targetSocket.close());
targetSocket.closeHandler(v -> clientSocket.close());
})
.onFailure(clientSocketAttempt -> {
System.err.println("Failed to upgrade client connection to socket: " + clientSocketAttempt.getMessage());
targetSocket.close();
clientRequest.response().setStatusCode(500).end("Internal Server Error");
});
})
.onFailure(connectionAttempt -> {
System.err.println("Failed to connect to target: " + connectionAttempt.getMessage());
clientRequest.response().setStatusCode(502).end("Bad Gateway: Unable to connect to target");
});
}
// 处理客户端的 HTTP 请求
private void handleClientRequest(HttpServerRequest clientRequest) {
if (stopping) {
failClientResponse(clientRequest.response(), 503, "Service Unavailable");
return;
}
// 打印来源ip和访问目标URI
LOGGER.debug("source: {}, target: {}", clientRequest.remoteAddress().toString(), clientRequest.uri());
if (proxyServerConf.containsKey("username") &&
StringUtils.isNotBlank(proxyServerConf.getString("username"))) {
String s = clientRequest.headers().get("Proxy-Authorization");
if (s == null) {
failClientResponse(clientRequest.response(), 403, null);
clientRequest.response().setStatusCode(403).end();
return;
}
String[] split;
try {
split = new String(Base64.getDecoder().decode(s.replace("Basic ", ""))).split(":");
} catch (IllegalArgumentException e) {
LOGGER.warn("Proxy-Authorization header is not valid Base64");
failClientResponse(clientRequest.response(), 403, null);
return;
}
if (split.length <= 1) {
LOGGER.warn("Proxy-Authorization header format invalid: missing username:password separator");
failClientResponse(clientRequest.response(), 403, null);
return;
}
String username = proxyServerConf.getString("username");
String password = proxyServerConf.getString("password");
if (!split[0].equals(username) || !split[1].equals(password)) {
LOGGER.info("-----auth failed------\nusername: {}", split[0]);
failClientResponse(clientRequest.response(), 403, null);
return;
String[] split = new String(Base64.getDecoder().decode(s.replace("Basic ", ""))).split(":");
if (split.length > 1) {
// TODO
String username = proxyServerConf.getString("username");
String password = proxyServerConf.getString("password");
if (!split[0].equals(username) || !split[1].equals(password)) {
LOGGER.info("-----auth failed------\nusername: {}\npassword: {}", username, password);
clientRequest.response().setStatusCode(403).end();
return;
}
}
}
@@ -198,147 +156,40 @@ public class HttpProxyVerticle extends AbstractVerticle {
// 获取目标主机
String hostHeader = clientRequest.getHeader("Host");
if (hostHeader == null) {
failClientResponse(clientRequest.response(), 400, "Host header is missing");
clientRequest.response().setStatusCode(400).end("Host header is missing");
return;
}
HostAndPort target;
try {
target = parseHostHeader(hostHeader);
} catch (IllegalArgumentException e) {
failClientResponse(clientRequest.response(), 400, "Bad Request: Invalid Host header");
return;
}
String targetHost = target.host();
int targetPort = extractPortFromUrl(clientRequest.uri(), target.port()); // 默认为 HTTP 的端口
if (targetPort <= 0) {
failClientResponse(clientRequest.response(), 400, "Bad Request: Invalid target port");
return;
}
clientRequest.pause(); // 暂停客户端请求的读取,等上游请求创建完成
String targetHost = hostHeader.split(":")[0];
int targetPort = extractPortFromUrl(clientRequest.uri()); // 默认为 HTTP 的端口
clientRequest.pause(); // 暂停客户端请求的读取,避免数据丢失
try {
httpClient.request(clientRequest.method(), targetPort, targetHost, clientRequest.uri())
.onSuccess(request -> {
// 逐个设置请求头
clientRequest.headers().forEach(header -> request.putHeader(header.getKey(), header.getValue()));
httpClient.request(clientRequest.method(), targetPort, targetHost, clientRequest.uri())
.onSuccess(request -> {
clientRequest.resume(); // 恢复客户端请求的读取
request.response()
.onSuccess(response -> {
HttpServerResponse clientResponse = clientRequest.response();
if (clientResponse.ended() || clientResponse.closed()) {
response.resume();
return;
}
clientResponse.setStatusCode(response.statusCode());
clientResponse.headers().setAll(response.headers());
response.pipeTo(clientResponse)
.onFailure(err -> {
LOGGER.error("HTTP代理响应转发失败", err);
try {
response.request().reset();
} catch (Exception e) {
LOGGER.debug("HTTP代理上游响应已关闭", e);
}
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Unable to reach target");
});
})
.onFailure(err -> {
LOGGER.error("HTTP代理响应失败", err);
try {
request.reset();
} catch (Exception e) {
LOGGER.debug("HTTP代理上游请求已关闭", e);
}
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Unable to reach target");
});
// 逐个设置请求头
clientRequest.headers().forEach(header -> request.putHeader(header.getKey(), header.getValue()));
clientRequest.pipeTo(request)
.onFailure(err -> {
LOGGER.error("HTTP代理请求转发失败", err);
try {
request.reset();
} catch (Exception e) {
LOGGER.debug("HTTP代理上游请求已关闭", e);
}
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Unable to reach target");
});
clientRequest.resume();
})
.onFailure(err -> {
LOGGER.error("HTTP请求失败", err);
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Request failed");
});
} catch (Exception e) {
LOGGER.error("HTTP请求创建失败", e);
failClientRequestAndClose(clientRequest, 502, "Bad Gateway: Request failed");
}
}
private void failClientResponse(HttpServerResponse response, String message) {
failClientResponse(response, 502, message);
}
private void failClientResponse(HttpServerResponse response, int statusCode, String message) {
if (response.ended() || response.closed()) {
return;
}
try {
if (!response.headWritten()) {
response.setStatusCode(statusCode);
if (message == null) {
response.end();
} else {
response.end(message);
}
} else {
response.reset();
}
} catch (Exception e) {
LOGGER.debug("客户端响应已关闭,忽略代理错误响应", e);
}
}
private void failClientRequestAndClose(HttpServerRequest request, int statusCode, String message) {
HttpServerResponse response = request.response();
if (response.ended() || response.closed()) {
closeClientConnection(request);
return;
}
try {
if (!response.headWritten()) {
response.setStatusCode(statusCode);
Future<Void> endFuture = message == null ? response.end() : response.end(message);
endFuture.onComplete(v -> closeClientConnection(request));
} else {
response.reset();
closeClientConnection(request);
}
} catch (Exception e) {
LOGGER.debug("客户端响应已关闭,关闭代理连接", e);
closeClientConnection(request);
}
}
private void closeClientConnection(HttpServerRequest request) {
try {
request.connection().close();
} catch (Exception e) {
LOGGER.debug("关闭客户端代理连接失败", e);
}
}
private void closeTunnelSockets(NetSocket clientSocket, NetSocket targetSocket) {
try {
clientSocket.close();
} catch (Exception e) {
LOGGER.debug("关闭CONNECT客户端socket失败", e);
}
try {
targetSocket.close();
} catch (Exception e) {
LOGGER.debug("关闭CONNECT目标socket失败", e);
}
// 将客户端请求的 body 转发给目标服务器
clientRequest.bodyHandler(body ->
request.send(body)
.onSuccess(response -> {
clientRequest.response().setStatusCode(response.statusCode());
clientRequest.response().headers().setAll(response.headers());
response.body()
.onSuccess(b -> clientRequest.response().end(b))
.onFailure(err -> clientRequest.response()
.setStatusCode(502).end("Bad Gateway: Unable to reach target"));
})
.onFailure(err -> clientRequest.response()
.setStatusCode(502).end("Bad Gateway: Unable to reach target"))
);
})
.onFailure(err -> {
err.printStackTrace();
clientRequest.response().setStatusCode(502).end("Bad Gateway: Request failed");
});
}
@@ -349,10 +200,6 @@ public class HttpProxyVerticle extends AbstractVerticle {
* @return 提取的端口号,如果没有指定端口,则返回默认端口
*/
public static int extractPortFromUrl(String urlString) {
return extractPortFromUrl(urlString, 80);
}
public static int extractPortFromUrl(String urlString, int defaultPort) {
try {
URI uri = new URI(urlString);
int port = uri.getPort();
@@ -361,59 +208,27 @@ public class HttpProxyVerticle extends AbstractVerticle {
if ("https".equalsIgnoreCase(uri.getScheme())) {
port = 443; // HTTPS 默认端口
} else {
port = defaultPort; // HTTP 默认端口
port = 80; // HTTP 默认端口
}
}
return port;
} catch (Exception e) {
LOGGER.error("提取端口失败: {}", urlString, e);
e.printStackTrace();
// 出现异常时返回 -1,表示提取失败
return -1;
}
}
private HostAndPort parseHostHeader(String hostHeader) {
if (hostHeader.startsWith("[")) {
int end = hostHeader.indexOf(']');
if (end > 0) {
String host = hostHeader.substring(1, end);
int port = 80;
if (hostHeader.length() > end + 2 && hostHeader.charAt(end + 1) == ':') {
port = Integer.parseInt(hostHeader.substring(end + 2));
}
return new HostAndPort(host, port);
}
}
int lastColon = hostHeader.lastIndexOf(':');
if (lastColon > 0 && hostHeader.indexOf(':') == lastColon) {
return new HostAndPort(hostHeader.substring(0, lastColon), Integer.parseInt(hostHeader.substring(lastColon + 1)));
}
return new HostAndPort(hostHeader, 80);
}
private record HostAndPort(String host, int port) {
}
@Override
public void stop(Promise<Void> stopPromise) {
stopping = true;
Future<Void> serverClose = httpServer == null ? Future.succeededFuture() : httpServer.close();
serverClose.onComplete(serverResult -> closeClients().onComplete(clientResult -> {
if (serverResult.failed()) {
stopPromise.fail(serverResult.cause());
} else if (clientResult.failed()) {
stopPromise.fail(clientResult.cause());
} else {
stopPromise.complete();
}
}));
}
private Future<Void> closeClients() {
Future<Void> httpClientClose = httpClient == null ? Future.succeededFuture() : httpClient.close();
Future<Void> netClientClose = netClient == null ? Future.succeededFuture() : netClient.close();
return Future.all(httpClientClose, netClientClose).mapEmpty();
public void stop() {
// 停止 HTTP 客户端以释放资源
if (httpClient != null) {
httpClient.close();
}
if (netClient != null) {
netClient.close();
}
}
}
@@ -46,7 +46,7 @@ public class PostExecVerticle extends AbstractVerticle {
return;
}
LOGGER.info("PostExecVerticle 开始执行...");
if (appRunImplementations != null && !appRunImplementations.isEmpty()) {
appRunImplementations.forEach(appRun -> {
try {
@@ -61,7 +61,7 @@ public class PostExecVerticle extends AbstractVerticle {
} else {
LOGGER.info("未找到 AppRun 接口的实现类");
}
LOGGER.info("PostExecVerticle 执行完成");
startPromise.complete();
}
@@ -3,20 +3,17 @@ package cn.qaiu.vx.core.verticle;
import cn.qaiu.vx.core.util.*;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.PemKeyCertOptions;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.proxy.handler.ProxyHandler;
import io.vertx.httpproxy.HttpProxy;
@@ -30,9 +27,7 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -50,6 +45,10 @@ public class ReverseProxyVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(ReverseProxyVerticle.class);
private static final String PATH_PROXY_CONFIG = SharedDataUtil
.getJsonConfig(ConfigConstant.GLOBAL_CONFIG)
.getString("proxyConf");
private static final Future<JsonObject> CONFIG = ConfigUtil.readYamlConfig(PATH_PROXY_CONFIG);
private static final String DEFAULT_PATH_404 = "webroot/err/page404.html";
private static String serverName = "Vert.x-proxy-server"; //Server name in Http response header
@@ -59,40 +58,26 @@ public class ReverseProxyVerticle extends AbstractVerticle {
/**
* 【优化】HttpClient连接池,按host:port缓存复用,避免每个请求都创建新连接
*/
private final Map<String, HttpClientEntry> httpClientPool = new ConcurrentHashMap<>();
private final List<HttpServer> httpServers = new ArrayList<>();
private volatile boolean stopping = false;
/**
* 连接池条目。HttpProxy 会持有这里的 HttpClient 引用,不能在路由仍可用时关闭。
*/
private static class HttpClientEntry {
final HttpClient client;
HttpClientEntry(HttpClient client) {
this.client = client;
}
}
private final Map<String, HttpClient> httpClientPool = new ConcurrentHashMap<>();
/**
* 【优化】高并发场景下的HttpClient配置
*/
private static final int MAX_POOL_SIZE = 32; // 最大连接池大小
private static final int MAX_WAIT_QUEUE_SIZE = 128; // 最大等待队列大小
private static final int MAX_POOL_SIZE = 100; // 最大连接池大小
private static final int MAX_WAIT_QUEUE_SIZE = 500; // 最大等待队列大小
private static final int CONNECT_TIMEOUT = 30000; // 连接超时30秒
private static final int IDLE_TIMEOUT = 60; // 空闲超时60秒
private static final boolean KEEP_ALIVE = true; // 启用Keep-Alive
private static final boolean PIPELINING = false; // 代理场景关闭管线化,避免慢响应堆积
private static final boolean PIPELINING = true; // 启用HTTP管线化
@Override
public void start(Promise<Void> startPromise) {
stopping = false;
String pathProxyConfig = SharedDataUtil
.getJsonConfig(ConfigConstant.GLOBAL_CONFIG)
.getString("proxyConf");
ConfigUtil.readYamlConfig(pathProxyConfig).onSuccess(config -> startProxyServers(config).onComplete(startPromise)).onFailure(e -> {
CONFIG.onSuccess(this::handleProxyConfList).onFailure(e -> {
LOGGER.info("web代理配置已禁用,当前仅支持API调用");
startPromise.complete();
});
// createFileListener
startPromise.complete();
}
/**
@@ -100,49 +85,16 @@ public class ReverseProxyVerticle extends AbstractVerticle {
*/
@Override
public void stop(Promise<Void> stopPromise) {
stopping = true;
LOGGER.info("Stopping ReverseProxyVerticle, closing {} servers and {} HttpClient connections...",
httpServers.size(), httpClientPool.size());
List<Future<Void>> serverCloseFutures = new ArrayList<>();
httpServers.forEach(server -> serverCloseFutures.add(server.close()));
Future<Void> serverCloseFuture = serverCloseFutures.isEmpty()
? Future.succeededFuture()
: Future.all(serverCloseFutures).mapEmpty();
serverCloseFuture.onComplete(serverClose -> {
List<Future<Void>> clientCloseFutures = new ArrayList<>();
closeHttpClients(clientCloseFutures);
Future<Void> clientCloseFuture = clientCloseFutures.isEmpty()
? Future.succeededFuture()
: Future.all(clientCloseFutures).mapEmpty();
clientCloseFuture.onComplete(clientClose -> {
if (serverClose.succeeded()) {
httpServers.clear();
}
if (clientClose.succeeded()) {
httpClientPool.clear();
}
if (serverClose.failed()) {
stopPromise.fail(serverClose.cause());
} else if (clientClose.failed()) {
stopPromise.fail(clientClose.cause());
} else {
stopPromise.complete();
}
});
});
}
private void closeHttpClients(List<Future<Void>> closeFutures) {
httpClientPool.values().forEach(entry -> {
LOGGER.info("Stopping ReverseProxyVerticle, closing {} HttpClient connections...", httpClientPool.size());
httpClientPool.values().forEach(client -> {
try {
closeFutures.add(entry.client.close());
client.close();
} catch (Exception e) {
LOGGER.warn("Error closing HttpClient: {}", e.getMessage());
}
});
httpClientPool.clear();
stopPromise.complete();
}
/**
@@ -153,7 +105,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
*/
private HttpClient getOrCreateHttpClient(String host, int port) {
String key = host + ":" + port;
HttpClientEntry entry = httpClientPool.computeIfAbsent(key, k -> {
return httpClientPool.computeIfAbsent(key, k -> {
LOGGER.info("Creating new HttpClient for {}", key);
HttpClientOptions options = new HttpClientOptions()
.setMaxPoolSize(MAX_POOL_SIZE) // 连接池大小
@@ -164,16 +116,15 @@ public class ReverseProxyVerticle extends AbstractVerticle {
.setKeepAliveTimeout(120) // Keep-Alive超时120秒
.setPipelining(PIPELINING) // HTTP管线化
.setPipeliningLimit(10) // 管线化限制
.setDecompressionSupported(false) // 代理不解压,避免放大内存
.setDecompressionSupported(true) // 支持解压响应
.setTcpKeepAlive(true) // TCP Keep-Alive
.setTcpNoDelay(true) // 禁用Nagle算法,降低延迟
.setTcpFastOpen(true) // 启用TCP Fast Open
.setTcpQuickAck(true) // 启用TCP Quick ACK
.setReuseAddress(true) // 允许地址重用
.setReusePort(true); // 允许端口重用
return new HttpClientEntry(vertx.createHttpClient(options));
return vertx.createHttpClient(options);
});
return entry.client;
}
/**
@@ -186,7 +137,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
*
* @param config proxy config
*/
private Future<Void> startProxyServers(JsonObject config) {
private void handleProxyConfList(JsonObject config) {
serverName = config.getString("server-name");
// 解析全局 trusted-proxies
JsonArray trustedArr = config.getJsonArray("trusted-proxies");
@@ -198,15 +149,13 @@ public class ReverseProxyVerticle extends AbstractVerticle {
});
}
JsonArray proxyConfList = config.getJsonArray("proxy");
List<Future<Void>> listenFutures = new ArrayList<>();
if (proxyConfList != null) {
proxyConfList.forEach(proxyConf -> {
if (proxyConf instanceof JsonObject) {
listenFutures.add(handleProxyConf((JsonObject) proxyConf));
handleProxyConf((JsonObject) proxyConf);
}
});
}
return listenFutures.isEmpty() ? Future.succeededFuture() : Future.all(listenFutures).mapEmpty();
}
/**
@@ -252,7 +201,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
*
* @param proxyConf 代理配置
*/
private Future<Void> handleProxyConf(JsonObject proxyConf) {
private void handleProxyConf(JsonObject proxyConf) {
// page404 path
if (proxyConf.containsKey(
@@ -277,10 +226,6 @@ public class ReverseProxyVerticle extends AbstractVerticle {
// Add Server name header
proxyRouter.route().handler(ctx -> {
if (stopping) {
sendProxyError(ctx, 503, "Service Unavailable");
return;
}
String realPath = ctx.request().uri();
if (realPath.startsWith(REROUTE_PATH_PREFIX)) {
// vertx web proxy暂不支持rewrite, 所以这里进行手动替换, 请求地址中的请求path前缀替换为originPath
@@ -289,9 +234,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
return;
}
if (!ctx.response().ended() && !ctx.response().closed()) {
ctx.response().putHeader("Server", serverName);
}
ctx.response().putHeader("Server", serverName);
ctx.next();
});
@@ -307,19 +250,15 @@ public class ReverseProxyVerticle extends AbstractVerticle {
// Send page404 page
proxyRouter.errorHandler(404, ctx -> {
sendNotFoundPage(ctx, proxyConf.getString("page404"));
ctx.response().sendFile(proxyConf.getString("page404"));
});
proxyRouter.errorHandler(500, this::handleProxyFailure);
HttpServer server = getHttpsServer(proxyConf);
server.requestHandler(proxyRouter);
Integer port = proxyConf.getInteger("listen");
LOGGER.info("proxy server start on {} port", port);
return server.listen(port)
.onSuccess(s -> httpServers.add(s))
.onFailure(e -> LOGGER.error("proxy server start failed on {} port", port, e))
.mapEmpty();
server.listen(port);
}
private HttpServer getHttpsServer(JsonObject proxyConf) {
@@ -328,7 +267,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
.setTcpKeepAlive(true) // TCP Keep-Alive
.setTcpNoDelay(true) // 禁用Nagle算法
.setCompressionSupported(true) // 启用压缩
.setAcceptBacklog(1024) // 限制积压队列,避免小容器内存膨胀
.setAcceptBacklog(50000) // 增加积压队列到50000
.setIdleTimeout(120) // 空闲超时120秒
.setTcpFastOpen(true) // 启用TCP Fast Open
.setTcpQuickAck(true) // 启用TCP Quick ACK
@@ -364,67 +303,6 @@ public class ReverseProxyVerticle extends AbstractVerticle {
return vertx.createHttpServer(httpServerOptions);
}
private void addProxyHandler(Route route, HttpProxy httpProxy) {
Handler<RoutingContext> proxyHandler = ProxyHandler.create(httpProxy);
route.handler(ctx -> {
try {
proxyHandler.handle(ctx);
} catch (Throwable t) {
LOGGER.error("反向代理处理异常", t);
ctx.fail(t);
}
}).failureHandler(this::handleProxyFailure);
}
private void handleProxyFailure(RoutingContext ctx) {
Throwable failure = ctx.failure();
if (failure != null) {
LOGGER.error("反向代理路由失败", failure);
}
int statusCode = ctx.statusCode() > 0 ? ctx.statusCode() : 502;
if (statusCode < 400) {
statusCode = 502;
}
sendProxyError(ctx, statusCode, "Bad Gateway");
}
private void sendNotFoundPage(RoutingContext ctx, String page404) {
HttpServerResponse response = ctx.response();
if (response.ended() || response.closed()) {
return;
}
try {
if (response.headWritten()) {
response.reset();
return;
}
response.sendFile(page404)
.onFailure(e -> {
LOGGER.warn("发送代理 404 页面失败: {}", page404, e);
sendProxyError(ctx, 404, "404 not found");
});
} catch (Exception e) {
LOGGER.warn("发送代理 404 页面异常: {}", page404, e);
sendProxyError(ctx, 404, "404 not found");
}
}
private void sendProxyError(RoutingContext ctx, int statusCode, String message) {
HttpServerResponse response = ctx.response();
if (response.ended() || response.closed()) {
return;
}
try {
if (!response.headWritten()) {
response.setStatusCode(statusCode).end(message);
} else {
response.reset();
}
} catch (Exception e) {
LOGGER.debug("代理响应已关闭,忽略错误响应", e);
}
}
/**
* 处理静态资源配置
*
@@ -473,7 +351,7 @@ public class ReverseProxyVerticle extends AbstractVerticle {
String host = url.getHost();
int port = url.getPort();
if (port == -1) {
port = 443;
port = 80;
}
String originPath = url.getPath();
LOGGER.info("path {}, originPath {}, to {}:{}", path, originPath, host, port);
@@ -513,14 +391,15 @@ public class ReverseProxyVerticle extends AbstractVerticle {
if (StringUtils.isEmpty(originPath) || path.equals(originPath)) {
Route route = path.startsWith("~") ? proxyRouter.routeWithRegex(path.substring(1))
: proxyRouter.route(path);
addProxyHandler(route, httpProxy);
// 【优化】为代理处理器添加超时
route.handler(ProxyHandler.create(httpProxy));
} else {
// 配置 /api/, / => 请求 /api/test 代理后 /test
// 配置 /api/, /xxx => 请求 /api/test 代理后 /xxx/test
final String path0 = path;
final String originPath0 = REROUTE_PATH_PREFIX + originPath;
addProxyHandler(proxyRouter.route(originPath0 + "*"), httpProxy);
proxyRouter.route(originPath0 + "*").handler(ProxyHandler.create(httpProxy));
proxyRouter.route(path0 + "*").handler(ctx -> {
String realPath = ctx.request().uri();
if (realPath.startsWith(path0)) {
@@ -22,22 +22,22 @@ public class RouterVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(RouterVerticle.class);
private static final int port = SharedDataUtil.getValueForServerConfig("port");
private static final Router router = new RouterHandlerFactory(
SharedDataUtil.getJsonStringForServerConfig("contextPath")).createRouter();
private static final JsonObject globalConfig = SharedDataUtil.getJsonConfig("globalConfig");
private HttpServer server;
private Router router;
private int port;
private JsonObject globalConfig;
static {
LOGGER.info(JacksonConfig.class.getSimpleName() + " >> ");
JacksonConfig.nothing();
LOGGER.info("To start listening to port {} ......", port);
}
@Override
public void start(Promise<Void> startPromise) {
port = SharedDataUtil.getValueForServerConfig("port");
globalConfig = SharedDataUtil.getJsonConfig("globalConfig");
LOGGER.info("To start listening to port {} ......", port);
// 端口是否占用
if (CommonUtil.isPortUsing(port)) {
throw new RuntimeException("Start fail: the '" + port + "' port is already in use...");
@@ -61,11 +61,9 @@ public class RouterVerticle extends AbstractVerticle {
.setReuseAddress(true) // 允许地址重用
.setReusePort(true); // 允许端口重用
router = new RouterHandlerFactory(
SharedDataUtil.getJsonStringForServerConfig("contextPath")).createRouter();
server = vertx.createHttpServer(options);
server.requestHandler(router).listen()
server.requestHandler(router).webSocketHandler(s->{}).listen()
.onSuccess(s -> startPromise.complete())
.onFailure(e -> startPromise.fail(e.getCause()));
}
@@ -5,15 +5,11 @@ import cn.qaiu.vx.core.base.BaseAsyncService;
import cn.qaiu.vx.core.util.ReflectionUtil;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.json.JsonObject;
import io.vertx.serviceproxy.ServiceBinder;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
@@ -28,7 +24,6 @@ public class ServiceVerticle extends AbstractVerticle {
Logger LOGGER = LoggerFactory.getLogger(ServiceVerticle.class);
private static final AtomicInteger ID = new AtomicInteger(1);
private static final Set<Class<?>> handlers;
private final List<MessageConsumer<JsonObject>> consumers = new ArrayList<>();
static {
Reflections reflections = ReflectionUtil.getReflections();
@@ -44,10 +39,7 @@ public class ServiceVerticle extends AbstractVerticle {
try {
serviceNames.append(asyncService.getName()).append("|");
BaseAsyncService asInstance = (BaseAsyncService) ReflectionUtil.newWithNoParam(asyncService);
String address = asInstance.getAddress();
MessageConsumer<JsonObject> consumer = binder.setAddress(address)
.register(asInstance.getAsyncInterfaceClass(), asInstance);
consumers.add(consumer);
binder.setAddress(asInstance.getAddress()).register(asInstance.getAsyncInterfaceClass(), asInstance);
} catch (Exception e) {
LOGGER.error("Failed to register service: {}", asyncService.getName(), e);
}
@@ -57,19 +49,4 @@ public class ServiceVerticle extends AbstractVerticle {
}
startPromise.complete();
}
@Override
public void stop(Promise<Void> stopPromise) {
int count = consumers.size();
consumers.forEach(consumer -> {
try {
consumer.unregister();
} catch (Exception e) {
LOGGER.warn("Failed to unregister service consumer at address: {}", consumer.address(), e);
}
});
consumers.clear();
LOGGER.info("ServiceVerticle stopped, unregistered {} services", count);
stopPromise.complete();
}
}
@@ -32,7 +32,7 @@ public class HttpProxyConf {
public HttpProxyConf() {
this.username = DEFAULT_USERNAME;
this.password = DEFAULT_PASSWORD;
this.port = DEFAULT_PORT;
this.timeout = DEFAULT_PORT;
this.timeout = DEFAULT_TIMEOUT;
this.preProxyOptions = new ProxyOptions();
}
-13
View File
@@ -1,13 +0,0 @@
#!/bin/sh
set -e
# Fix permissions on volume-mounted directories (runs as root)
chown -R appuser:appgroup /app/db /app/logs /app/resources 2>/dev/null || true
# Run Java directly - entrypoint is PID 1, exec makes Java PID 1
# Docker SIGTERM goes directly to Java, triggering ShutdownHook
DEFAULT_JVM_OPTS="-Xmx${JVM_XMX:-512M} -Xss${JVM_XSS:-512k} -XX:MaxDirectMemorySize=${JVM_MAX_DIRECT_MEMORY:-256M} -DNFD_LOG_LEVEL=${NFD_LOG_LEVEL:-info} -DNFD_PLAYGROUND_ENABLED=${NFD_PLAYGROUND_ENABLED:-false}"
if [ -n "${JVM_MAX_METASPACE:-}" ]; then
DEFAULT_JVM_OPTS="$DEFAULT_JVM_OPTS -XX:MaxMetaspaceSize=$JVM_MAX_METASPACE"
fi
exec java ${DEFAULT_JVM_OPTS} ${JVM_OPTS} -Duser.timezone=${TZ:-Asia/Shanghai} -jar /app/netdisk-fast-download.jar
+4 -4
View File
@@ -4,26 +4,26 @@ NFD 解析器模块:聚合各类网盘/分享页解析,统一输出文件列
- 语言:Java 17
- 构建:Maven
- 模块版本:10.2.5
- 模块版本:10.1.17
## 依赖(Maven Central
```xml
<dependency>
<groupId>cn.qaiu</groupId>
<artifactId>parser</artifactId>
<version>10.2.5</version>
<version>10.1.17</version>
</dependency>
```
- Gradle Groovy DSL
```groovy
dependencies {
implementation 'cn.qaiu:parser:10.2.5'
implementation 'cn.qaiu:parser:10.1.17'
}
```
- Gradle Kotlin DSL
```kotlin
dependencies {
implementation("cn.qaiu:parser:10.2.5")
implementation("cn.qaiu:parser:10.1.17")
}
```
+1 -1
View File
@@ -28,7 +28,7 @@
<dependency>
<groupId>cn.qaiu</groupId>
<artifactId>parser</artifactId>
<version>10.2.5</version>
<version>10.1.17</version>
</dependency>
```
+1 -1
View File
@@ -11,7 +11,7 @@
<dependency>
<groupId>cn.qaiu</groupId>
<artifactId>parser</artifactId>
<version>10.2.5</version>
<version>10.1.17</version>
</dependency>
```
+3 -3
View File
@@ -240,13 +240,13 @@ var encoded = JsHttpClient.urlEncode("hello world"); // "hello%20world"
var decoded = JsHttpClient.urlDecode("hello%20world"); // "hello world"
// 发送简单表单数据
var formResponse = http.sendForm("https://api.example.com/login", {
var formResponse = http.sendForm({
username: "user",
password: "pass"
});
// 发送JSON数据
var jsonResponse = http.sendJson("https://api.example.com/submit", {
var jsonResponse = http.sendJson({
name: "test",
value: 123
});
@@ -637,7 +637,7 @@ A: 使用 `shareLinkInfo.getSharePassword()` 方法。
### Q: 如何处理需要登录的网盘?
A: 使用 `http.putHeader()` 设置认证头,或使用 `http.sendForm(url, data)` 发送登录表单。
A: 使用 `http.putHeader()` 设置认证头,或使用 `http.sendForm()` 发送登录表单。
### Q: 如何解析复杂的HTML
+1 -1
View File
@@ -68,7 +68,7 @@ List<FileInfo> files = tool.parseFileListSync();
```
要点:
- 必须先 WebClientVertxInit.init(Vertx)未初始化时会直接报错,避免解析器偷偷创建第二个 Vert.x 实例
- 必须先 WebClientVertxInit.init(Vertx)若未显式初始化,内部将懒加载 Vertx.vertx(),建议显式注入以统一生命周期
- 支持三种同步方法:
- `parseSync()`: 解析单个文件下载链接
- `parseFileListSync()`: 解析文件列表
+1 -1
View File
@@ -17,7 +17,7 @@
this.temporaryExecutor = WebClientVertxInit.get().createSharedWorkerExecutor(
"playground-temp-" + System.currentTimeMillis(),
1, // 每个请求只需要1个线程
10000000000L // 设置非常长的超时,避免触发Vert.x阻塞线程告警
10000000000L // 设置非常长的超时,避免被vertx强制中断
);
// 执行完成或超时后关闭
+1 -1
View File
@@ -106,7 +106,7 @@ executionFuture.toCompletionStage()
### 长期方案(需大量工作)
1. **迁移到GraalVM JavaScript引擎**
- 支持CPU时间限制
- 相比Nashorn更容易实现受控取消
- 可以强制中断
- 更好的性能
- 但需要额外依赖
+7 -41
View File
@@ -12,7 +12,7 @@
<groupId>cn.qaiu</groupId>
<artifactId>parser</artifactId>
<version>${parserVersion}</version>
<version>10.2.5</version>
<packaging>jar</packaging>
<name>cn.qaiu:parser</name>
@@ -35,9 +35,9 @@
</developers>
<scm>
<connection>scm:git:https://github.com/${github.owner}/${github.repo}.git</connection>
<developerConnection>scm:git:ssh://[email protected]:${github.owner}/${github.repo}.git</developerConnection>
<url>https://github.com/${github.owner}/${github.repo}</url>
<connection>scm:git:https://github.com/qaiu/netdisk-fast-download.git</connection>
<developerConnection>scm:git:ssh://[email protected]:qaiu/netdisk-fast-download.git</developerConnection>
<url>https://github.com/qaiu/netdisk-fast-download</url>
</scm>
<distributionManagement>
@@ -52,19 +52,20 @@
</distributionManagement>
<properties>
<revision>0.2.1</revision>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Versions -->
<vertx.version>4.5.27</vertx.version>
<vertx.version>4.5.24</vertx.version>
<org.reflections.version>0.10.2</org.reflections.version>
<lombok.version>1.18.38</lombok.version>
<slf4j.version>2.0.16</slf4j.version>
<commons-lang3.version>3.18.0</commons-lang3.version>
<jackson.version>2.18.6</jackson.version>
<logback.version>1.5.32</logback.version>
<logback.version>1.5.19</logback.version>
<junit.version>4.13.2</junit.version>
</properties>
@@ -123,41 +124,6 @@
<build>
<plugins>
<!-- 从 git remote origin 自动识别 GitHub 仓库地址 -->
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>4.1.1</version>
<dependencies>
<dependency>
<groupId>org.apache.groovy</groupId>
<artifactId>groovy</artifactId>
<version>4.0.24</version>
</dependency>
</dependencies>
<executions>
<execution>
<phase>initialize</phase>
<goals><goal>execute</goal></goals>
<configuration>
<scripts>
<script>
def url = 'git remote get-url origin'.execute().text.trim()
def m = (url =~ 'github\\.com[:/]([^/]+)/([^/.]+?)(?:\\.git)?$')
if (m.find()) {
project.properties.setProperty('github.owner', m.group(1))
project.properties.setProperty('github.repo', m.group(2))
} else {
project.properties.setProperty('github.owner', 'qaiu')
project.properties.setProperty('github.repo', 'netdisk-fast-download')
}
</script>
</scripts>
</configuration>
</execution>
</executions>
</plugin>
<!-- 编译 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -7,15 +7,12 @@ import org.slf4j.LoggerFactory;
import cn.qaiu.parser.custom.CustomParserRegistry;
public class WebClientVertxInit {
private volatile Vertx vertx = null;
private Vertx vertx = null;
private static final WebClientVertxInit INSTANCE = new WebClientVertxInit();
private static final Logger log = LoggerFactory.getLogger(WebClientVertxInit.class);
public static synchronized void init(Vertx vx) {
if (vx == null) {
throw new IllegalArgumentException("Vertx instance must not be null");
}
public static void init(Vertx vx) {
INSTANCE.vertx = vx;
// 自动加载JavaScript解析器脚本
@@ -26,10 +23,18 @@ public class WebClientVertxInit {
}
}
public static synchronized Vertx get() {
public static Vertx get() {
if (INSTANCE.vertx == null) {
throw new IllegalStateException("Vertx实例未初始化,请先调用 WebClientVertxInit.init(vertx)");
log.info("getVertx: Vertx实例不存在, 创建Vertx实例.");
INSTANCE.vertx = Vertx.vertx();
// 如果Vertx实例是新创建的,也尝试加载JavaScript脚本
try {
CustomParserRegistry.autoLoadJsScripts();
} catch (Exception e) {
log.warn("自动加载JavaScript解析器脚本失败", e);
}
}
return INSTANCE.vertx;
}
}
}
@@ -86,10 +86,7 @@ public class ShareLinkInfo {
// 将type和shareKey组合成一个字符串作为缓存key
String key = type + ":" + shareKey;
if (type.equals("p115")) {
Object ua = otherParam != null ? otherParam.get("UA") : null;
if (ua != null) {
key += ("_" + ua.toString().hashCode());
}
key += ("_" + otherParam.get("UA").toString().hashCode());
}
return key;
}
@@ -1,6 +1,5 @@
package cn.qaiu.parser;//package cn.qaiu.lz.common.parser;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.clientlink.ClientLinkGeneratorFactory;
@@ -8,26 +7,10 @@ import cn.qaiu.parser.clientlink.ClientLinkType;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import java.util.function.Supplier;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
public interface IPanTool extends AutoCloseable {
/** 同步等待超时时间(秒) */
long SYNC_TIMEOUT_SECONDS = 120;
ScheduledExecutorService CLOSE_AFTER_SCHEDULER = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "pan-tool-close-after");
t.setDaemon(true);
return t;
});
public interface IPanTool {
/**
* 解析文件
@@ -35,72 +18,8 @@ public interface IPanTool extends AutoCloseable {
*/
Future<String> parse();
static <T> Future<T> closeAfter(IPanTool tool, Supplier<Future<T>> action) {
Promise<T> promise = Promise.promise();
AtomicBoolean cleanupDone = new AtomicBoolean(false);
ScheduledFuture<?> cleanupTask = null;
try {
Future<T> future = action.get();
if (future == null) {
closeQuietly(tool);
return Future.failedFuture("解析器返回空 Future");
}
cleanupTask = CLOSE_AFTER_SCHEDULER.schedule(() -> {
if (cleanupDone.compareAndSet(false, true)) {
closeQuietly(tool);
failOnVertxContext(promise, "解析超时(" + SYNC_TIMEOUT_SECONDS + "秒)");
}
}, SYNC_TIMEOUT_SECONDS, TimeUnit.SECONDS);
ScheduledFuture<?> scheduledCleanupTask = cleanupTask;
future.onComplete(ar -> {
scheduledCleanupTask.cancel(false);
if (!cleanupDone.compareAndSet(false, true)) {
return;
}
closeQuietly(tool);
if (ar.succeeded()) {
promise.tryComplete(ar.result());
} else {
promise.tryFail(ar.cause());
}
});
return promise.future();
} catch (Throwable t) {
if (cleanupTask != null) {
cleanupTask.cancel(false);
}
closeQuietly(tool);
return Future.failedFuture(t);
}
}
private static <T> void failOnVertxContext(Promise<T> promise, String message) {
try {
WebClientVertxInit.get().runOnContext(ignored -> promise.tryFail(message));
} catch (Exception ignored) {
promise.tryFail(message);
}
}
static void closeQuietly(IPanTool tool) {
if (tool == null) {
return;
}
try {
tool.close();
} catch (Exception ignored) {
// ignore cleanup failures
}
}
static void shutdownCloseAfterScheduler() {
CLOSE_AFTER_SCHEDULER.shutdownNow();
}
default String parseSync() {
return timedJoin(parse());
return parse().toCompletionStage().toCompletableFuture().join();
}
/**
@@ -114,7 +33,7 @@ public interface IPanTool extends AutoCloseable {
}
default List<FileInfo> parseFileListSync() {
return timedJoin(parseFileList());
return parseFileList().toCompletionStage().toCompletableFuture().join();
}
/**
@@ -128,7 +47,7 @@ public interface IPanTool extends AutoCloseable {
}
default String parseByIdSync() {
return timedJoin(parseById());
return parseById().toCompletionStage().toCompletableFuture().join();
}
/**
@@ -207,7 +126,7 @@ public interface IPanTool extends AutoCloseable {
* @return Map<ClientLinkType, String> 客户端下载链接集合
*/
default Map<ClientLinkType, String> parseWithClientLinksSync() {
return timedJoin(parseWithClientLinks());
return parseWithClientLinks().toCompletionStage().toCompletableFuture().join();
}
/**
@@ -218,26 +137,4 @@ public interface IPanTool extends AutoCloseable {
default ShareLinkInfo getShareLinkInfo() {
return null;
}
@Override
default void close() {
// default no-op
}
/**
* 带超时的同步等待工具方法,替代无超时的 join()
*/
private static <T> T timedJoin(Future<T> future) {
try {
return future.toCompletionStage().toCompletableFuture()
.get(SYNC_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("线程被中断", e);
} catch (TimeoutException e) {
throw new RuntimeException("同步等待超时(" + SYNC_TIMEOUT_SECONDS + "秒)", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException(e.getCause() != null ? e.getCause() : e);
}
}
}
+42 -194
View File
@@ -34,65 +34,36 @@ import java.util.zip.GZIPInputStream;
* <p>{网盘标识}Tool, 网盘标识不超过5个字符, 可以取网盘名称首字母缩写或拼音首字母, <br>
* 音乐类型的解析以M开头, 例如网易云音乐Mne</p>
*/
public abstract class PanBase implements IPanTool, Closeable {
public abstract class PanBase implements IPanTool {
protected Logger log = LoggerFactory.getLogger(this.getClass());
protected Promise<String> promise = Promise.promise();
private static final int MAX_COMPRESSED_RESPONSE_BYTES = 8 * 1024 * 1024;
private static final int MAX_DECOMPRESSED_RESPONSE_CHARS = 16 * 1024 * 1024;
private static final int MAX_ERROR_BODY_CHARS = 4096;
/**
* 共享的 WebClient 配置(设置超时避免连接无限期占用)
* Http client
*/
private static final WebClientOptions SHARED_OPTIONS = new WebClientOptions()
.setConnectTimeout(10000) // 连接超时 10 秒
.setIdleTimeout(30) // 空闲超时 30 秒
.setIdleTimeoutUnit(java.util.concurrent.TimeUnit.SECONDS);
private static final Object SHARED_CLIENT_LOCK = new Object();
protected WebClient client = WebClient.create(WebClientVertxInit.get(),
new WebClientOptions());
/**
* 共享的 WebClient 实例(线程安全,避免每请求创建导致资源泄漏)
*/
private static volatile WebClient sharedClient;
private static volatile WebClient sharedClientNoRedirects;
private static volatile WebClient sharedClientDisableUA;
private static volatile boolean sharedClientsShutdown = false;
/**
* Http client (默认使用共享实例,代理模式下使用独立实例)
*/
protected WebClient client = sharedClient();
/**
* Http client session (会话管理, 带cookie请求, 每实例独立)
* Http client session (会话管理, 带cookie请求)
*/
protected WebClientSession clientSession = WebClientSession.create(client);
/**
* Http client 不自动跳转
*/
protected WebClient clientNoRedirects = sharedClientNoRedirects();
protected WebClient clientNoRedirects = WebClient.create(WebClientVertxInit.get(),
new WebClientOptions().setFollowRedirects(false));
/**
* Http client disable UserAgent
*/
protected WebClient clientDisableUA = sharedClientDisableUA();
protected WebClient clientDisableUA = WebClient.create(WebClientVertxInit.get()
, new WebClientOptions().setUserAgentEnabled(false)
);
protected ShareLinkInfo shareLinkInfo;
/**
* 标记是否为代理模式(代理模式创建的 WebClient 需要手动关闭)
*/
private boolean isProxyMode = false;
/**
* 代理模式下创建的独立 WebClient 实例(需要在 close 时释放)
*/
private WebClient proxyClient = null;
private WebClient proxyClientNoRedirects = null;
/**
@@ -109,7 +80,6 @@ public abstract class PanBase implements IPanTool, Closeable {
public PanBase(ShareLinkInfo shareLinkInfo) {
this.shareLinkInfo = shareLinkInfo;
if (shareLinkInfo.getOtherParam().containsKey("proxy")) {
this.isProxyMode = true;
JsonObject proxy = (JsonObject) shareLinkInfo.getOtherParam().get("proxy");
ProxyOptions proxyOptions = new ProxyOptions()
.setType(ProxyType.valueOf(proxy.getString("type").toUpperCase()))
@@ -121,86 +91,22 @@ public abstract class PanBase implements IPanTool, Closeable {
if (StringUtils.isNotEmpty(proxy.getString("password"))) {
proxyOptions.setPassword(proxy.getString("password"));
}
// 代理模式下创建独立的 WebClient 实例(应用超时配置)
this.proxyClient = WebClient.create(WebClientVertxInit.get(),
new WebClientOptions(SHARED_OPTIONS)
.setUserAgentEnabled(false)
.setProxyOptions(proxyOptions));
this.proxyClientNoRedirects = WebClient.create(WebClientVertxInit.get(),
new WebClientOptions(SHARED_OPTIONS).setFollowRedirects(false)
this.client = WebClient.create(WebClientVertxInit.get(),
new WebClientOptions()
.setUserAgentEnabled(false)
.setProxyOptions(proxyOptions));
this.client = proxyClient;
this.clientSession = WebClientSession.create(client);
this.clientNoRedirects = proxyClientNoRedirects;
this.clientNoRedirects = WebClient.create(WebClientVertxInit.get(),
new WebClientOptions().setFollowRedirects(false)
.setUserAgentEnabled(false)
.setProxyOptions(proxyOptions));
}
}
protected PanBase() {
}
private static WebClient sharedClient() {
synchronized (SHARED_CLIENT_LOCK) {
if (sharedClientsShutdown) {
throw new IllegalStateException("共享 WebClient 已关闭");
}
if (sharedClient == null) {
sharedClient = WebClient.create(WebClientVertxInit.get(), new WebClientOptions(SHARED_OPTIONS));
}
return sharedClient;
}
}
private static WebClient sharedClientNoRedirects() {
synchronized (SHARED_CLIENT_LOCK) {
if (sharedClientsShutdown) {
throw new IllegalStateException("共享 WebClient 已关闭");
}
if (sharedClientNoRedirects == null) {
sharedClientNoRedirects = WebClient.create(WebClientVertxInit.get(),
new WebClientOptions(SHARED_OPTIONS).setFollowRedirects(false));
}
return sharedClientNoRedirects;
}
}
private static WebClient sharedClientDisableUA() {
synchronized (SHARED_CLIENT_LOCK) {
if (sharedClientsShutdown) {
throw new IllegalStateException("共享 WebClient 已关闭");
}
if (sharedClientDisableUA == null) {
sharedClientDisableUA = WebClient.create(WebClientVertxInit.get(),
new WebClientOptions(SHARED_OPTIONS).setUserAgentEnabled(false));
}
return sharedClientDisableUA;
}
}
public static void shutdownSharedClients() {
synchronized (SHARED_CLIENT_LOCK) {
sharedClientsShutdown = true;
closeSharedClient(sharedClient, "shared WebClient");
closeSharedClient(sharedClientNoRedirects, "shared WebClientNoRedirects");
closeSharedClient(sharedClientDisableUA, "shared WebClientDisableUA");
sharedClient = null;
sharedClientNoRedirects = null;
sharedClientDisableUA = null;
}
}
private static void closeSharedClient(WebClient client, String name) {
if (client == null) {
return;
}
try {
client.close();
} catch (Exception e) {
LoggerFactory.getLogger(PanBase.class).warn("关闭 {} 失败: {}", name, e.getMessage());
}
}
protected String baseMsg() {
if (shareLinkInfo.getShareUrl() != null) {
return shareLinkInfo.getPanName() + "-" + shareLinkInfo.getType() + ": url=" + shareLinkInfo.getShareUrl();
@@ -225,19 +131,16 @@ public abstract class PanBase implements IPanTool, Closeable {
return;
}
String s = String.format(errorMsg.replaceAll("\\{}", "%s"), args);
// 只记录异常消息和类型,不调用 fillInStackTrace 避免产生巨大栈信息
log.error("解析异常: {} - {}: {}", s, t.getClass().getSimpleName(), t.getMessage());
// 只传递异常消息,不传递完整异常对象,减少内存占用
String failMsg = baseMsg() + ": 解析异常: " + s + " -> " + t.getClass().getSimpleName() + ": " + t.getMessage();
promise.fail(failMsg);
log.error("解析异常: " + s, t.fillInStackTrace());
promise.fail(baseMsg() + ": 解析异常: " + s + " -> " + t);
} catch (Exception e) {
log.error("ErrorMsg format fail. The parameter has been discarded", e);
log.error("解析异常: {} - {}: {}", errorMsg, t.getClass().getSimpleName(), t.getMessage());
log.error("解析异常: " + errorMsg, t.fillInStackTrace());
if (promise.future().isComplete()) {
log.warn("ErrorMsg format. Promise 已经完成, 无法再次失败: {}", errorMsg);
return;
}
promise.fail(baseMsg() + ": 解析异常: " + errorMsg + " -> " + t.getClass().getSimpleName() + ": " + t.getMessage());
promise.fail(baseMsg() + ": 解析异常: " + errorMsg + " -> " + t);
}
}
@@ -277,7 +180,7 @@ public abstract class PanBase implements IPanTool, Closeable {
* @return Handler
*/
protected Handler<Throwable> handleFail(String errorMsg) {
return t -> fail(baseMsg() + " - 请求异常 {}: -> {}", errorMsg, t.getClass().getSimpleName() + ": " + t.getMessage());
return t -> fail(baseMsg() + " - 请求异常 {}: -> {}", errorMsg, t.fillInStackTrace());
}
protected Handler<Throwable> handleFail() {
@@ -296,22 +199,28 @@ public abstract class PanBase implements IPanTool, Closeable {
String contentEncoding = res.getHeader("Content-Encoding");
try {
if ("gzip".equalsIgnoreCase(contentEncoding)) {
// 如果是gzip压缩的响应体,解压(只解压一次,缓存结果)
String decompressed = decompressGzip((Buffer) res.body());
return new JsonObject(decompressed);
// 如果是gzip压缩的响应体,解压
return new JsonObject(decompressGzip((Buffer) res.body()));
} else {
return res.bodyAsJsonObject();
}
} catch (Exception e) {
if ("gzip".equalsIgnoreCase(contentEncoding)) {
// gzip解压失败,记录错误
log.error("响应gzip解压或JSON解析失败: {}", e.getMessage());
fail("响应gzip解压或JSON解析失败: {}", e.getMessage());
// 如果是gzip压缩的响应体,解压
try {
log.error(decompressGzip((Buffer) res.body()));
fail(decompressGzip((Buffer) res.body()));
//throw new RuntimeException("响应不是JSON格式");
} catch (IOException ex) {
log.error("响应gzip解压失败");
fail("响应gzip解压失败: {}", ex.getMessage());
//throw new RuntimeException("响应gzip解压失败", ex);
}
} else {
String bodyPreview = responseBodyPreview(res);
log.error("解析失败: json格式异常: {}", bodyPreview);
fail("解析失败: json格式异常: {}", bodyPreview);
log.error("解析失败: json格式异常: {}", res.bodyAsString());
fail("解析失败: json格式异常: {}", res.bodyAsString());
//throw new RuntimeException("解析失败: json格式异常");
}
return JsonObject.of();
}
@@ -374,15 +283,11 @@ public abstract class PanBase implements IPanTool, Closeable {
if (iterator.hasNext()) {
PanDomainTemplate next = iterator.next();
log.debug("规则不匹配, 处理解析器转发: {} -> {}", shareLinkInfo.getPanName(), next.getDisplayName());
try {
IPanTool nextTool = ParserCreate.fromType(next.name())
.fromAnyShareUrl(shareLinkInfo.getShareUrl())
.createTool();
IPanTool.closeAfter(nextTool, nextTool::parse)
.onComplete(promise);
} catch (Exception e) {
fail(e, "转发到下一个解析器失败: {}", next.getDisplayName());
}
ParserCreate.fromType(next.name())
.fromAnyShareUrl(shareLinkInfo.getShareUrl())
.createTool()
.parse()
.onComplete(promise);
} else {
fail("error: 没有下一个解析处理器");
}
@@ -398,12 +303,6 @@ public abstract class PanBase implements IPanTool, Closeable {
* @throws IOException IOException
*/
private String decompressGzip(Buffer compressedData) throws IOException {
if (compressedData == null) {
return "";
}
if (compressedData.length() > MAX_COMPRESSED_RESPONSE_BYTES) {
throw new IOException("gzip响应体过大: " + compressedData.length() + " bytes");
}
try (ByteArrayInputStream bais = new ByteArrayInputStream(compressedData.getBytes());
GZIPInputStream gzis = new GZIPInputStream(bais);
InputStreamReader isr = new InputStreamReader(gzis, StandardCharsets.UTF_8);
@@ -412,39 +311,12 @@ public abstract class PanBase implements IPanTool, Closeable {
char[] buffer = new char[4096];
int n;
while ((n = isr.read(buffer)) != -1) {
writeLimited(writer, buffer, n);
writer.write(buffer, 0, n);
}
return writer.toString();
}
}
private void writeLimited(StringWriter writer, char[] buffer, int len) throws IOException {
if (writer.getBuffer().length() + len > MAX_DECOMPRESSED_RESPONSE_CHARS) {
throw new IOException("gzip解压后响应体过大");
}
writer.write(buffer, 0, len);
}
private String responseBodyPreview(HttpResponse<?> res) {
if (res == null || res.body() == null) {
return "";
}
try {
if (res.body() instanceof Buffer body) {
int length = Math.min(body.length(), MAX_ERROR_BODY_CHARS);
String preview = new String(body.getBytes(0, length), StandardCharsets.UTF_8);
return body.length() > length ? preview + "...(truncated " + body.length() + " bytes)" : preview;
}
String text = res.bodyAsString();
if (text == null || text.length() <= MAX_ERROR_BODY_CHARS) {
return text;
}
return text.substring(0, MAX_ERROR_BODY_CHARS) + "...(truncated " + text.length() + " chars)";
} catch (Exception e) {
return "<body preview failed: " + e.getMessage() + ">";
}
}
protected String getDomainName(){
return shareLinkInfo.getOtherParam().getOrDefault("domainName", "").toString();
}
@@ -453,28 +325,4 @@ public abstract class PanBase implements IPanTool, Closeable {
public ShareLinkInfo getShareLinkInfo() {
return shareLinkInfo;
}
/**
* 关闭代理模式下创建的 WebClient 资源
* 非代理模式使用共享实例,不需要关闭
*/
@Override
public void close() {
if (isProxyMode) {
try {
if (proxyClient != null) {
proxyClient.close();
}
} catch (Exception e) {
log.warn("关闭代理 WebClient 失败: {}", e.getMessage());
}
try {
if (proxyClientNoRedirects != null) {
proxyClientNoRedirects.close();
}
} catch (Exception e) {
log.warn("关闭代理 WebClientNoRedirects 失败: {}", e.getMessage());
}
}
}
}
@@ -208,7 +208,7 @@ public enum PanDomainTemplate {
123795.com
*/
YE("123网盘",
compile("https://(?:[a-zA-Z\\d-]+\\.)*(" +
compile("https://www\\.(" +
"123254\\.com|" +
"123957\\.com|" +
"123295\\.com|" +
@@ -232,7 +232,7 @@ public enum PanDomainTemplate {
"123635\\.com|" +
"123242\\.com|" +
"123795\\.com" +
")/(?:(?:s|123pan)/|(?:[^/?#]+/)+)?(?<KEY>[a-zA-Z0-9]+-[a-zA-Z0-9]+|[a-zA-Z0-9_-]+)(?:\\.html)?(?:\\?.*)?"),
")/s/(?<KEY>[a-zA-Z0-9_-]+)(?:\\.html)?"),
"https://www.123pan.com/s/{shareKey}",
Ye2Tool.class),
// https://www.ecpan.cn/web/#/yunpanProxy?path=%2F%23%2Fdrive%2Foutside&data={code}&isShare=1
@@ -247,15 +247,9 @@ public enum PanDomainTemplate {
"https://cowtransfer.com/s/{shareKey}",
CowTool.class),
CT("城通网盘",
compile("https?://(?:[a-zA-Z\\d-]+\\.)?(ctfile|545c|u062|ghpym|474b)\\.com/f(ile)?/" +
"(?<KEY>[0-9a-zA-Z_-]+)/?(?:\\?(?:(?:[^#&]*&)*p=(?<PWD>\\w+)(?:&[^#]*)?|[^#]*))?"),
"https://ctfile.com/file/{shareKey}",
CtTool.class),
// https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609&d=164803691&fk=decb36
CTD("城通网盘-目录",
compile("https?://(?:[a-zA-Z\\d-]+\\.)?(ctfile|545c|u062|ghpym|474b)\\.com/d/" +
"(?<KEY>[0-9a-zA-Z_-]+)/?(?:\\?(?:(?:[^#&]*&)*p=(?<PWD>\\w+)(?:&[^#]*)?|[^#]*))?"),
"https://ctfile.com/d/{shareKey}",
compile("https://(?:[a-zA-Z\\d-]+\\.)?(ctfile|545c|u062|ghpym|474b)\\.com/f(ile)?/" +
"(?<KEY>[0-9a-zA-Z_-]+)(\\?p=(?<PWD>\\w+))?"),
"https://474b.com/file/{shareKey}",
CtTool.class),
// https://www.vyuyun.com/s/QMa6ie?password=I4KG7H
// https://www.vyuyun.com/s/QMa6ie/file?password=I4KG7H
@@ -9,8 +9,6 @@ import org.apache.commons.lang3.StringUtils;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.EnumSet;
import java.util.Set;
import java.util.regex.Matcher;
import static cn.qaiu.parser.PanDomainTemplate.KEY;
@@ -25,9 +23,6 @@ import static cn.qaiu.parser.PanDomainTemplate.PWD;
* Create at 2024/9/15 14:10
*/
public class ParserCreate {
private static final Set<PanDomainTemplate> GENERIC_BUILT_IN_PARSERS =
EnumSet.of(PanDomainTemplate.CE, PanDomainTemplate.KD, PanDomainTemplate.OTHER);
private final PanDomainTemplate panDomainTemplate;
private final ShareLinkInfo shareLinkInfo;
@@ -86,16 +81,16 @@ public class ParserCreate {
if (shareKey != null) {
shareLinkInfo.setShareKey(shareKey);
}
} catch (IllegalStateException | IllegalArgumentException ignored) {}
} catch (Exception ignored) {}
// 提取密码
try {
String pwd = matcher.group("PWD");
if (StringUtils.isNotEmpty(pwd)) {
shareLinkInfo.setSharePassword(pwd);
}
} catch (IllegalStateException | IllegalArgumentException ignored) {}
} catch (Exception ignored) {}
// 设置标准URL
if (customParserConfig.getStandardUrlTemplate() != null) {
String standardUrl = customParserConfig.getStandardUrlTemplate()
@@ -137,12 +132,12 @@ public class ParserCreate {
if (StringUtils.isNotEmpty(pwd)) {
shareLinkInfo.setSharePassword(pwd);
}
standardUrl = standardUrl.replace("{pwd}", StringUtils.defaultString(pwd));
} catch (IllegalStateException | IllegalArgumentException ignored) {}
standardUrl = standardUrl.replace("{pwd}", pwd);
} catch (Exception ignored) {}
shareLinkInfo.setShareUrl(shareUrl);
shareLinkInfo.setShareKey(shareKey);
if (!isGenericBuiltInParser(panDomainTemplate)) {
if (!(panDomainTemplate.ordinal() >= PanDomainTemplate.CE.ordinal())) {
shareLinkInfo.setStandardUrl(standardUrl);
}
return this;
@@ -202,7 +197,7 @@ public class ParserCreate {
}
// 内置解析器处理
if (isGenericBuiltInParser(panDomainTemplate)) {
if (panDomainTemplate.ordinal() >= PanDomainTemplate.CE.ordinal()) {
// 处理Cloudreve(ce): pan.huang1111.cn_s_wDz5TK _ -> /
String[] s = shareKey.split("_");
String standardUrl = "https://" + String.join("/", s);
@@ -252,19 +247,9 @@ public class ParserCreate {
return this;
}
// 根据分享链接获取PanDomainTemplate实例
// 根据分享链接获取PanDomainTemplate实例优先匹配自定义解析器
public synchronized static ParserCreate fromShareUrl(String shareUrl) {
if (StringUtils.isBlank(shareUrl)) {
throw new IllegalArgumentException("shareUrl不能为空");
}
shareUrl = shareUrl.trim();
ParserCreate builtInParser = fromBuiltInShareUrl(shareUrl, false);
if (builtInParser != null) {
return builtInParser;
}
// 明确内置解析器未命中时再查找支持正则匹配的自定义解析器
// 优先查找支持正则匹配的自定义解析器
for (CustomParserConfig customConfig : CustomParserRegistry.getAll().values()) {
if (customConfig.supportsFromShareUrl()) {
Matcher matcher = customConfig.getMatchPattern().matcher(shareUrl);
@@ -281,15 +266,15 @@ public class ParserCreate {
if (shareKey != null) {
shareLinkInfo.setShareKey(shareKey);
}
} catch (IllegalStateException | IllegalArgumentException ignored) {}
} catch (Exception ignored) {}
try {
String password = matcher.group("PWD");
if (password != null) {
shareLinkInfo.setSharePassword(password);
}
} catch (IllegalStateException | IllegalArgumentException ignored) {}
} catch (Exception ignored) {}
// 设置标准URL如果有模板
if (customConfig.getStandardUrlTemplate() != null) {
String standardUrl = customConfig.getStandardUrlTemplate()
@@ -310,35 +295,22 @@ public class ParserCreate {
}
}
}
// 最后再走 Cloudreve/可道云/其他网盘这类泛化兜底避免抢走自定义解析器
builtInParser = fromBuiltInShareUrl(shareUrl, true);
if (builtInParser != null) {
return builtInParser;
}
throw new IllegalArgumentException("Unsupported share URL");
}
private static ParserCreate fromBuiltInShareUrl(String shareUrl, boolean genericOnly) {
// 查找内置解析器
for (PanDomainTemplate panDomainTemplate : PanDomainTemplate.values()) {
boolean genericParser = isGenericBuiltInParser(panDomainTemplate);
if (genericOnly != genericParser) {
continue;
}
if (panDomainTemplate.getPattern().matcher(shareUrl).matches()) {
ShareLinkInfo shareLinkInfo = ShareLinkInfo.newBuilder()
.type(panDomainTemplate.name().toLowerCase())
.panName(panDomainTemplate.getDisplayName())
.shareUrl(shareUrl).build();
if (isGenericBuiltInParser(panDomainTemplate)) {
if (panDomainTemplate.ordinal() >= PanDomainTemplate.CE.ordinal()) {
shareLinkInfo.setStandardUrl(shareUrl);
}
ParserCreate parserCreate = new ParserCreate(panDomainTemplate, shareLinkInfo);
return parserCreate.normalizeShareLink();
}
}
return null;
throw new IllegalArgumentException("Unsupported share URL");
}
// 根据type获取枚举实例优先查找自定义解析器
@@ -381,7 +353,7 @@ public class ParserCreate {
// 自定义解析器处理
if (isCustomParser) {
path = this.shareLinkInfo.getType() + "/" + this.shareLinkInfo.getShareKey();
} else if (isGenericBuiltInParser(panDomainTemplate)) {
} else if (panDomainTemplate.ordinal() >= PanDomainTemplate.CE.ordinal()) {
// 处理Cloudreve(ce): pan.huang1111.cn_s_wDz5TK _ -> /
path = this.shareLinkInfo.getType() + "/"
+ this.shareLinkInfo.getShareUrl()
@@ -409,11 +381,7 @@ public class ParserCreate {
public CustomParserConfig getCustomParserConfig() {
return customParserConfig;
}
private static boolean isGenericBuiltInParser(PanDomainTemplate panDomainTemplate) {
return GENERIC_BUILT_IN_PARSERS.contains(panDomainTemplate);
}
/**
* 获取内置解析器模板仅当isCustomParser为false时有效
* @return 内置解析器模板如果是自定义解析器则返回null
@@ -1,53 +0,0 @@
package cn.qaiu.parser;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Parser token cache keyed by parser type and account identity.
*/
public final class TokenCache {
private static final Map<String, String> TOKENS = new ConcurrentHashMap<>();
private static final Map<String, Long> EXPIRES = new ConcurrentHashMap<>();
private TokenCache() {
}
public static String key(String type, String accountId) {
return type + ":" + (StringUtils.isBlank(accountId) ? "_default" : accountId);
}
public static void putToken(String key, String token) {
if (StringUtils.isBlank(key) || StringUtils.isBlank(token)) {
return;
}
TOKENS.put(key, token);
}
public static String getToken(String key) {
if (StringUtils.isBlank(key)) {
return null;
}
if (isExpired(key)) {
TOKENS.remove(key);
EXPIRES.remove(key);
return null;
}
return TOKENS.get(key);
}
public static void putExpire(String key, long expireTimeMillis) {
if (StringUtils.isBlank(key)) {
return;
}
EXPIRES.put(key, expireTimeMillis);
}
public static boolean isExpired(String key) {
Long expireTimeMillis = EXPIRES.get(key);
return expireTimeMillis != null && System.currentTimeMillis() > expireTimeMillis;
}
}
@@ -21,7 +21,6 @@ import java.util.concurrent.ConcurrentHashMap;
public class CustomParserRegistry {
private static final Logger log = LoggerFactory.getLogger(CustomParserRegistry.class);
private static final int MAX_CUSTOM_PARSERS = Integer.getInteger("parser.custom.maxRegistrySize", 256);
/**
* 存储自定义解析器配置的Mapkey为类型标识value为配置对象
@@ -34,7 +33,7 @@ public class CustomParserRegistry {
* @param config 解析器配置
* @throws IllegalArgumentException 如果type已存在或与内置解析器冲突
*/
public static synchronized void register(CustomParserConfig config) {
public static void register(CustomParserConfig config) {
if (config == null) {
throw new IllegalArgumentException("config不能为空");
}
@@ -60,11 +59,6 @@ public class CustomParserRegistry {
"类型标识 '" + type + "' 已被注册,请先注销或使用其他标识"
);
}
if (CUSTOM_PARSERS.size() >= MAX_CUSTOM_PARSERS) {
throw new IllegalArgumentException(
"自定义解析器数量已达到上限(" + MAX_CUSTOM_PARSERS + "个),请先注销不需要的解析器"
);
}
CUSTOM_PARSERS.put(type, config);
log.info("注册自定义解析器成功: {} ({})", config.getDisplayName(), type);
@@ -177,7 +171,7 @@ public class CustomParserRegistry {
* @param type 解析器类型标识
* @return 是否注销成功
*/
public static synchronized boolean unregister(String type) {
public static boolean unregister(String type) {
if (type == null || type.trim().isEmpty()) {
return false;
}
@@ -219,7 +213,7 @@ public class CustomParserRegistry {
/**
* 清空所有自定义解析器
*/
public static synchronized void clear() {
public static void clear() {
CUSTOM_PARSERS.clear();
}
@@ -2,21 +2,19 @@ package cn.qaiu.parser.customjs;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.util.HttpResponseHelper;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
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.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.ProxyOptions;
import io.vertx.core.net.ProxyType;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.vertx.ext.web.client.WebClientSession;
import io.vertx.ext.web.multipart.MultipartForm;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -29,13 +27,8 @@ import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
/**
@@ -46,60 +39,11 @@ import java.util.regex.Pattern;
* Create at 2025/10/17
*/
public class JsHttpClient {
private static final Logger log = LoggerFactory.getLogger(JsHttpClient.class);
private static final int MAX_RESPONSE_BODY_BYTES = 8 * 1024 * 1024;
private static final int MAX_REQUEST_BODY_BYTES = 8 * 1024 * 1024;
private static final int MAX_HEADER_COUNT = 64;
private static final int MAX_HEADER_VALUE_LENGTH = 4096;
private static final int MAX_TIMEOUT_SECONDS = 120;
private static final int MAX_REDIRECTS = 5;
private static final String DEFAULT_ACCEPT_ENCODING = "gzip, deflate, br";
private static final Object SHARED_CLIENT_LOCK = new Object();
// 共享 HttpClient 实例非代理模式懒加载避免类初始化阶段抢跑 Vert.x
private static volatile HttpClient sharedClient;
private static volatile boolean sharedClientShutdown = false;
/**
* 关闭共享 HttpClient应用关闭时调用
*/
public static void shutdownSharedClient() {
synchronized (SHARED_CLIENT_LOCK) {
sharedClientShutdown = true;
if (sharedClient != null) {
sharedClient.close();
sharedClient = null;
}
}
}
private static HttpClient sharedClient() {
synchronized (SHARED_CLIENT_LOCK) {
ensureSharedClientAvailable();
if (sharedClient == null) {
sharedClient = WebClientVertxInit.get().createHttpClient(
new HttpClientOptions()
.setConnectTimeout(10000)
.setIdleTimeout(30)
.setIdleTimeoutUnit(TimeUnit.SECONDS)
.setMaxPoolSize(64));
}
return sharedClient;
}
}
private static void ensureSharedClientAvailable() {
if (sharedClientShutdown) {
throw new IllegalStateException("共享 JavaScript HttpClient 已关闭");
}
}
private final HttpClient client;
private final boolean ownClient; // 标记是否为自建 client需要 close
private final AtomicBoolean closed = new AtomicBoolean(false);
private final Object requestLock = new Object();
private final Set<HttpClientRequest> activeRequests = ConcurrentHashMap.newKeySet();
private final WebClient client;
private final WebClientSession clientSession;
private MultiMap headers;
private int timeoutSeconds = 30; // 默认超时时间30秒
@@ -117,12 +61,11 @@ public class JsHttpClient {
};
public JsHttpClient() {
ensureSharedClientAvailable();
this.client = sharedClient();
this.ownClient = false;
this.client = WebClient.create(WebClientVertxInit.get(), new WebClientOptions());;
this.clientSession = WebClientSession.create(client);
this.headers = MultiMap.caseInsensitiveMultiMap();
// 设置默认的Accept-Encoding头以支持压缩响应
this.headers.set("Accept-Encoding", DEFAULT_ACCEPT_ENCODING);
this.headers.set("Accept-Encoding", "gzip, deflate, br, zstd");
// 设置默认的User-Agent头
this.headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
// 设置默认的Accept-Language头
@@ -134,35 +77,31 @@ public class JsHttpClient {
* @param proxyConfig 代理配置JsonObject包含typehostportusernamepassword
*/
public JsHttpClient(JsonObject proxyConfig) {
ensureSharedClientAvailable();
if (proxyConfig != null && proxyConfig.containsKey("type")) {
ProxyOptions proxyOptions = new ProxyOptions()
.setType(ProxyType.valueOf(proxyConfig.getString("type").toUpperCase()))
.setHost(proxyConfig.getString("host"))
.setPort(proxyConfig.getInteger("port"));
if (StringUtils.isNotEmpty(proxyConfig.getString("username"))) {
proxyOptions.setUsername(proxyConfig.getString("username"));
}
if (StringUtils.isNotEmpty(proxyConfig.getString("password"))) {
proxyOptions.setPassword(proxyConfig.getString("password"));
}
this.client = WebClientVertxInit.get().createHttpClient(
new HttpClientOptions()
.setConnectTimeout(10000)
.setIdleTimeout(30)
.setIdleTimeoutUnit(TimeUnit.SECONDS)
.setMaxPoolSize(16)
this.client = WebClient.create(WebClientVertxInit.get(),
new WebClientOptions()
.setUserAgentEnabled(false)
.setProxyOptions(proxyOptions));
this.ownClient = true;
this.clientSession = WebClientSession.create(client);
} else {
this.client = sharedClient();
this.ownClient = false;
this.client = WebClient.create(WebClientVertxInit.get());
this.clientSession = WebClientSession.create(client);
}
this.headers = MultiMap.caseInsensitiveMultiMap();
// 设置默认的Accept-Encoding头以支持压缩响应
this.headers.set("Accept-Encoding", DEFAULT_ACCEPT_ENCODING);
this.headers.set("Accept-Encoding", "gzip, deflate, br, zstd");
// 设置默认的User-Agent头
this.headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
// 设置默认的Accept-Language头
@@ -244,7 +183,13 @@ public class JsHttpClient {
*/
public JsHttpResponse get(String url) {
validateUrlSecurity(url);
return executeRequest(HttpMethod.GET, url, null, false);
return executeRequest(() -> {
HttpRequest<Buffer> request = client.getAbs(url);
if (!headers.isEmpty()) {
request.putHeaders(headers);
}
return request.send();
});
}
/**
@@ -253,25 +198,16 @@ public class JsHttpClient {
* @return HTTP响应
*/
public JsHttpResponse getWithRedirect(String url) {
String currentUrl = url;
for (int redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount++) {
validateUrlSecurity(currentUrl);
JsHttpResponse response = executeRequest(HttpMethod.GET, currentUrl, null, false);
if (!isRedirectStatus(response.statusCode())) {
return response;
validateUrlSecurity(url);
return executeRequest(() -> {
HttpRequest<Buffer> request = client.getAbs(url);
if (!headers.isEmpty()) {
request.putHeaders(headers);
}
if (redirectCount == MAX_REDIRECTS) {
throw new RuntimeException("重定向次数超过限制: " + MAX_REDIRECTS);
}
String location = response.header(HttpHeaders.LOCATION.toString());
if (StringUtils.isBlank(location)) {
throw new RuntimeException("重定向响应缺少Location头");
}
currentUrl = resolveRedirectUrl(currentUrl, location);
}
throw new RuntimeException("重定向处理失败");
// 设置跟随重定向
request.followRedirects(true);
return request.send();
});
}
/**
@@ -281,7 +217,15 @@ public class JsHttpClient {
*/
public JsHttpResponse getNoRedirect(String url) {
validateUrlSecurity(url);
return executeRequest(HttpMethod.GET, url, null, false);
return executeRequest(() -> {
HttpRequest<Buffer> request = client.getAbs(url);
if (!headers.isEmpty()) {
request.putHeaders(headers);
}
// 设置不跟随重定向
request.followRedirects(false);
return request.send();
});
}
/**
@@ -292,7 +236,26 @@ public class JsHttpClient {
*/
public JsHttpResponse post(String url, Object data) {
validateUrlSecurity(url);
return executeRequest(HttpMethod.POST, url, bodyFromData(data), false);
return executeRequest(() -> {
HttpRequest<Buffer> request = client.postAbs(url);
if (!headers.isEmpty()) {
request.putHeaders(headers);
}
if (data != null) {
if (data instanceof String) {
return request.sendBuffer(Buffer.buffer((String) data));
} else if (data instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, String> mapData = (Map<String, String>) data;
return request.sendForm(MultiMap.caseInsensitiveMultiMap().addAll(mapData));
} else {
return request.sendJson(data);
}
} else {
return request.send();
}
});
}
/**
@@ -303,7 +266,26 @@ public class JsHttpClient {
*/
public JsHttpResponse put(String url, Object data) {
validateUrlSecurity(url);
return executeRequest(HttpMethod.PUT, url, bodyFromData(data), false);
return executeRequest(() -> {
HttpRequest<Buffer> request = client.putAbs(url);
if (!headers.isEmpty()) {
request.putHeaders(headers);
}
if (data != null) {
if (data instanceof String) {
return request.sendBuffer(Buffer.buffer((String) data));
} else if (data instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, String> mapData = (Map<String, String>) data;
return request.sendForm(MultiMap.caseInsensitiveMultiMap().addAll(mapData));
} else {
return request.sendJson(data);
}
} else {
return request.send();
}
});
}
/**
@@ -312,8 +294,13 @@ public class JsHttpClient {
* @return HTTP响应
*/
public JsHttpResponse delete(String url) {
validateUrlSecurity(url);
return executeRequest(HttpMethod.DELETE, url, null, false);
return executeRequest(() -> {
HttpRequest<Buffer> request = client.deleteAbs(url);
if (!headers.isEmpty()) {
request.putHeaders(headers);
}
return request.send();
});
}
/**
@@ -323,8 +310,26 @@ public class JsHttpClient {
* @return HTTP响应
*/
public JsHttpResponse patch(String url, Object data) {
validateUrlSecurity(url);
return executeRequest(HttpMethod.PATCH, url, bodyFromData(data), false);
return executeRequest(() -> {
HttpRequest<Buffer> request = client.patchAbs(url);
if (!headers.isEmpty()) {
request.putHeaders(headers);
}
if (data != null) {
if (data instanceof String) {
return request.sendBuffer(Buffer.buffer((String) data));
} else if (data instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, String> mapData = (Map<String, String>) data;
return request.sendForm(MultiMap.caseInsensitiveMultiMap().addAll(mapData));
} else {
return request.sendJson(data);
}
} else {
return request.send();
}
});
}
/**
@@ -335,12 +340,6 @@ public class JsHttpClient {
*/
public JsHttpClient putHeader(String name, String value) {
if (name != null && value != null) {
if (headers.size() >= MAX_HEADER_COUNT && !headers.contains(name)) {
throw new IllegalArgumentException("请求头数量超过限制");
}
if (value.length() > MAX_HEADER_VALUE_LENGTH) {
throw new IllegalArgumentException("请求头过长: " + name);
}
headers.set(name, value);
}
return this;
@@ -354,7 +353,9 @@ public class JsHttpClient {
public JsHttpClient putHeaders(Map<String, String> headersMap) {
if (headersMap != null) {
for (Map.Entry<String, String> entry : headersMap.entrySet()) {
putHeader(entry.getKey(), entry.getValue());
if (entry.getKey() != null && entry.getValue() != null) {
headers.set(entry.getKey(), entry.getValue());
}
}
}
return this;
@@ -379,7 +380,7 @@ public class JsHttpClient {
public JsHttpClient clearHeaders() {
headers.clear();
// 重新设置默认头
headers.set("Accept-Encoding", DEFAULT_ACCEPT_ENCODING);
headers.set("Accept-Encoding", "gzip, deflate, br, zstd");
headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0");
headers.set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
return this;
@@ -404,7 +405,7 @@ public class JsHttpClient {
*/
public JsHttpClient setTimeout(int seconds) {
if (seconds > 0) {
this.timeoutSeconds = Math.min(seconds, MAX_TIMEOUT_SECONDS);
this.timeoutSeconds = seconds;
}
return this;
}
@@ -449,12 +450,19 @@ public class JsHttpClient {
* @return HTTP响应
*/
public JsHttpResponse sendForm(Map<String, String> data) {
throw new IllegalArgumentException("sendForm(data) 缺少请求URL,请使用 post(url, data)");
}
public JsHttpResponse sendForm(String url, Map<String, String> data) {
validateUrlSecurity(url);
return executeRequest(HttpMethod.POST, url, formBody(data), false);
return executeRequest(() -> {
HttpRequest<Buffer> request = client.postAbs("");
if (!headers.isEmpty()) {
request.putHeaders(headers);
}
MultiMap formData = MultiMap.caseInsensitiveMultiMap();
if (data != null) {
formData.addAll(data);
}
return request.sendForm(formData);
});
}
/**
@@ -466,8 +474,34 @@ public class JsHttpClient {
* @return HTTP响应
*/
public JsHttpResponse sendMultipartForm(String url, Map<String, Object> data) {
validateUrlSecurity(url);
return executeRequest(HttpMethod.POST, url, multipartBody(data), false);
return executeRequest(() -> {
HttpRequest<Buffer> request = client.postAbs(url);
if (!headers.isEmpty()) {
request.putHeaders(headers);
}
MultipartForm form = MultipartForm.create();
if (data != null) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String) {
form.attribute(key, (String) value);
} else if (value instanceof byte[]) {
form.binaryFileUpload(key, key, Buffer.buffer((byte[]) value), "application/octet-stream");
} else if (value instanceof Buffer) {
form.binaryFileUpload(key, key, (Buffer) value, "application/octet-stream");
} else if (value != null) {
// 其他类型转换为字符串
form.attribute(key, value.toString());
}
}
}
return request.sendMultipartForm(form);
});
}
/**
@@ -476,103 +510,44 @@ public class JsHttpClient {
* @return HTTP响应
*/
public JsHttpResponse sendJson(Object data) {
throw new IllegalArgumentException("sendJson(data) 缺少请求URL,请使用 post(url, data)");
}
public JsHttpResponse sendJson(String url, Object data) {
validateUrlSecurity(url);
return executeRequest(HttpMethod.POST, url, jsonBody(data), false);
return executeRequest(() -> {
HttpRequest<Buffer> request = client.postAbs("");
if (!headers.isEmpty()) {
request.putHeaders(headers);
}
return request.sendJson(data);
});
}
/**
* 执行HTTP请求同步
*/
private JsHttpResponse executeRequest(HttpMethod method, String url, RequestBody requestBody, boolean followRedirects) {
if (closed.get()) {
throw new IllegalStateException("HTTP客户端已关闭");
}
AtomicReference<HttpClientRequest> requestRef = new AtomicReference<>();
AtomicBoolean abandoned = new AtomicBoolean(false);
private JsHttpResponse executeRequest(RequestExecutor executor) {
try {
Promise<JsHttpResponse> promise = Promise.promise();
RequestOptions options = new RequestOptions()
.setMethod(method)
.setAbsoluteURI(url)
.setFollowRedirects(followRedirects)
.setTimeout(TimeUnit.SECONDS.toMillis(timeoutSeconds))
.setHeaders(MultiMap.caseInsensitiveMultiMap().setAll(headers));
client.request(options).onComplete(ar -> {
if (ar.failed()) {
promise.tryFail(ar.cause());
return;
Promise<HttpResponse<Buffer>> promise = Promise.promise();
Future<HttpResponse<Buffer>> future = executor.execute();
future.onComplete(result -> {
if (result.succeeded()) {
promise.complete(result.result());
} else {
promise.fail(result.cause());
}
HttpClientRequest request = ar.result();
synchronized (requestLock) {
if (closed.get() || abandoned.get()) {
request.reset();
promise.tryFail("HTTP客户端已关闭");
return;
}
activeRequests.add(request);
requestRef.set(request);
request.exceptionHandler(e -> {
finishRequest(request);
promise.tryFail(e);
});
request.response().onComplete(responseAr -> {
if (responseAr.succeeded()) {
collectResponse(request, responseAr.result(), promise);
} else {
finishRequest(request);
promise.tryFail(responseAr.cause());
}
});
if (closed.get() || abandoned.get()) {
request.reset();
finishRequest(request);
promise.tryFail("HTTP客户端已关闭");
return;
}
if (requestBody == null || requestBody.body() == null) {
request.end().onFailure(e -> {
finishRequest(request);
promise.tryFail(e);
});
} else {
request.headers().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(requestBody.body().length()));
if (StringUtils.isNotEmpty(requestBody.contentType())) {
request.headers().set(HttpHeaders.CONTENT_TYPE, requestBody.contentType());
}
request.end(requestBody.body()).onFailure(e -> {
finishRequest(request);
promise.tryFail(e);
});
}
}
});
return promise.future().toCompletionStage()
}).onFailure(Throwable::printStackTrace);
// 等待响应完成使用配置的超时时间
HttpResponse<Buffer> response = promise.future().toCompletionStage()
.toCompletableFuture()
.get(timeoutSeconds, TimeUnit.SECONDS);
return new JsHttpResponse(response);
} catch (TimeoutException e) {
// RequestOptions timeout 通常会先触发这里再兜底避免等待线程返回后请求还在后台下载
String errorMsg = "HTTP请求超时(" + timeoutSeconds + "秒)";
abandoned.set(true);
synchronized (requestLock) {
abortRequest(requestRef);
}
log.error(errorMsg, e);
throw new RuntimeException(errorMsg, e);
} catch (Exception e) {
abandoned.set(true);
synchronized (requestLock) {
abortRequest(requestRef);
}
String errorMsg = e.getMessage();
if (errorMsg == null || errorMsg.trim().isEmpty()) {
errorMsg = e.getClass().getSimpleName();
@@ -584,196 +559,13 @@ public class JsHttpClient {
throw new RuntimeException("HTTP请求执行失败: " + errorMsg, e);
}
}
private static boolean isRedirectStatus(int statusCode) {
return statusCode == 301 || statusCode == 302 || statusCode == 303
|| statusCode == 307 || statusCode == 308;
}
private String resolveRedirectUrl(String currentUrl, String location) {
try {
URI redirectUri = new URI(currentUrl).resolve(location.trim());
String scheme = redirectUri.getScheme();
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
throw new SecurityException("🔒 安全拦截: 重定向协议不被允许");
}
String redirectUrl = redirectUri.toString();
validateUrlSecurity(redirectUrl);
return redirectUrl;
} catch (SecurityException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("解析重定向地址失败: " + e.getMessage(), e);
}
}
private void collectResponse(HttpClientRequest request, HttpClientResponse response, Promise<JsHttpResponse> promise) {
Buffer body = Buffer.buffer();
AtomicBoolean done = new AtomicBoolean(false);
String contentLengthHeader = response.getHeader(HttpHeaders.CONTENT_LENGTH.toString());
if (StringUtils.isNumeric(contentLengthHeader)) {
long contentLength = Long.parseLong(contentLengthHeader);
if (contentLength > MAX_RESPONSE_BODY_BYTES) {
done.set(true);
request.reset();
finishRequest(request);
promise.tryFail("响应体过大: " + contentLength + " bytes");
return;
}
}
response.exceptionHandler(e -> {
if (done.compareAndSet(false, true)) {
finishRequest(request);
promise.tryFail(e);
}
});
response.handler(chunk -> {
if (done.get()) {
return;
}
if (body.length() + chunk.length() > MAX_RESPONSE_BODY_BYTES) {
if (done.compareAndSet(false, true)) {
request.reset();
finishRequest(request);
promise.tryFail("响应体过大: " + (body.length() + chunk.length()) + " bytes");
}
return;
}
body.appendBuffer(chunk);
});
response.endHandler(v -> {
if (done.compareAndSet(false, true)) {
finishRequest(request);
promise.tryComplete(new JsHttpResponse(
response.statusCode(),
MultiMap.caseInsensitiveMultiMap().setAll(response.headers()),
body,
response.statusMessage(),
null
));
}
});
response.resume();
}
private void finishRequest(HttpClientRequest request) {
if (request != null) {
activeRequests.remove(request);
}
}
private void abortRequest(AtomicReference<HttpClientRequest> requestRef) {
HttpClientRequest request = requestRef.get();
if (request != null) {
try {
request.reset();
} finally {
finishRequest(request);
}
}
}
private RequestBody bodyFromData(Object data) {
if (data == null) {
return null;
}
if (data instanceof String str) {
return plainTextBody(str);
}
if (data instanceof Buffer buffer) {
return limitedBody(buffer, null);
}
if (data instanceof byte[] bytes) {
return limitedBody(Buffer.buffer(bytes), null);
}
if (data instanceof Map<?, ?> map) {
Map<String, String> formMap = new HashMap<>();
map.forEach((key, value) -> {
if (key != null && value != null) {
formMap.put(String.valueOf(key), String.valueOf(value));
}
});
return formBody(formMap);
}
return jsonBody(data);
}
private RequestBody plainTextBody(String data) {
return limitedBody(Buffer.buffer(data, StandardCharsets.UTF_8.name()), null);
}
private RequestBody jsonBody(Object data) {
Buffer body = data == null ? Buffer.buffer() : Buffer.buffer(Json.encode(data), StandardCharsets.UTF_8.name());
return limitedBody(body, "application/json; charset=utf-8");
}
private RequestBody formBody(Map<String, String> data) {
StringBuilder encoded = new StringBuilder();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
if (encoded.length() > 0) {
encoded.append('&');
}
encoded.append(urlEncode(entry.getKey()));
encoded.append('=');
encoded.append(urlEncode(entry.getValue()));
}
}
return limitedBody(Buffer.buffer(encoded.toString(), StandardCharsets.UTF_8.name()),
"application/x-www-form-urlencoded; charset=utf-8");
}
private RequestBody multipartBody(Map<String, Object> data) {
String boundary = "----NetdiskJsHttpClientBoundary" + UUID.randomUUID().toString().replace("-", "");
Buffer body = Buffer.buffer();
if (data != null) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key == null || value == null) {
continue;
}
appendAscii(body, "--" + boundary + "\r\n");
if (value instanceof byte[] bytes) {
appendAscii(body, "Content-Disposition: form-data; name=\"" + escapeMultipart(key)
+ "\"; filename=\"" + escapeMultipart(key) + "\"\r\n");
appendAscii(body, "Content-Type: application/octet-stream\r\n\r\n");
body.appendBytes(bytes);
appendAscii(body, "\r\n");
} else if (value instanceof Buffer buffer) {
appendAscii(body, "Content-Disposition: form-data; name=\"" + escapeMultipart(key)
+ "\"; filename=\"" + escapeMultipart(key) + "\"\r\n");
appendAscii(body, "Content-Type: application/octet-stream\r\n\r\n");
body.appendBuffer(buffer);
appendAscii(body, "\r\n");
} else {
appendAscii(body, "Content-Disposition: form-data; name=\"" + escapeMultipart(key) + "\"\r\n\r\n");
body.appendString(String.valueOf(value), StandardCharsets.UTF_8.name());
appendAscii(body, "\r\n");
}
ensureRequestBodyLimit(body);
}
}
appendAscii(body, "--" + boundary + "--\r\n");
return limitedBody(body, "multipart/form-data; boundary=" + boundary);
}
private static void appendAscii(Buffer body, String value) {
body.appendString(value, StandardCharsets.US_ASCII.name());
}
private static String escapeMultipart(String value) {
return value.replace("\\", "\\\\").replace("\"", "\\\"");
}
private static RequestBody limitedBody(Buffer body, String contentType) {
ensureRequestBodyLimit(body);
return new RequestBody(body, contentType);
}
private record RequestBody(Buffer body, String contentType) {
/**
* 请求执行器接口
*/
@FunctionalInterface
private interface RequestExecutor {
Future<HttpResponse<Buffer>> execute();
}
/**
@@ -781,29 +573,10 @@ public class JsHttpClient {
*/
public static class JsHttpResponse {
private final int statusCode;
private final MultiMap headers;
private final Buffer body;
private final String statusMessage;
private final HttpResponse<Buffer> originalResponse;
private final HttpResponse<Buffer> response;
public JsHttpResponse(HttpResponse<Buffer> response) {
this(
response.statusCode(),
MultiMap.caseInsensitiveMultiMap().setAll(response.headers()),
response.body(),
response.statusMessage(),
response
);
}
public JsHttpResponse(int statusCode, MultiMap headers, Buffer body, String statusMessage,
HttpResponse<Buffer> originalResponse) {
this.statusCode = statusCode;
this.headers = headers == null ? MultiMap.caseInsensitiveMultiMap() : headers;
this.body = body == null ? Buffer.buffer() : body;
this.statusMessage = statusMessage;
this.originalResponse = originalResponse;
this.response = response;
}
/**
@@ -811,7 +584,7 @@ public class JsHttpClient {
* @return 响应体字符串
*/
public String body() {
return HttpResponseHelper.asText(body, header(HttpHeaders.CONTENT_ENCODING.toString()));
return HttpResponseHelper.asText(response);
}
/**
@@ -820,7 +593,7 @@ public class JsHttpClient {
*/
public Object json() {
try {
JsonObject jsonObject = HttpResponseHelper.asJson(body, header(HttpHeaders.CONTENT_ENCODING.toString()));
JsonObject jsonObject = HttpResponseHelper.asJson(response);
if (jsonObject == null || jsonObject.isEmpty()) {
return null;
}
@@ -838,7 +611,7 @@ public class JsHttpClient {
* @return 状态码
*/
public int statusCode() {
return statusCode;
return response.statusCode();
}
/**
@@ -847,7 +620,7 @@ public class JsHttpClient {
* @return 头值
*/
public String header(String name) {
return headers.get(name);
return response.getHeader(name);
}
/**
@@ -855,9 +628,10 @@ public class JsHttpClient {
* @return 响应头Map
*/
public Map<String, String> headers() {
MultiMap responseHeaders = response.headers();
Map<String, String> result = new HashMap<>();
for (String name : headers.names()) {
result.put(name, headers.get(name));
for (String name : responseHeaders.names()) {
result.put(name, responseHeaders.get(name));
}
return result;
}
@@ -875,14 +649,8 @@ public class JsHttpClient {
* 获取原始响应对象
* @return HttpResponse对象
*/
@Deprecated
public HttpResponse<Buffer> getOriginalResponse() {
if (originalResponse == null) {
throw new UnsupportedOperationException(
"流式HTTP客户端不再保留原始Vert.x HttpResponse,请使用statusCode/header/headers/body/bodyBytes方法"
);
}
return originalResponse;
return response;
}
/**
@@ -890,8 +658,11 @@ public class JsHttpClient {
* @return 响应体字节数组
*/
public byte[] bodyBytes() {
ensureResponseBodyLimit(body);
return body.getBytes();
Buffer buffer = response.body();
if (buffer == null) {
return new byte[0];
}
return buffer.getBytes();
}
/**
@@ -899,46 +670,11 @@ public class JsHttpClient {
* @return 响应体大小字节
*/
public long bodySize() {
return body.length();
}
public String statusMessage() {
return statusMessage;
}
}
/**
* 关闭 HttpClient 释放连接池资源
* 仅关闭自建的 client代理模式共享实例不关闭
*/
public void close() {
if (!closed.compareAndSet(false, true)) {
return;
}
synchronized (requestLock) {
for (HttpClientRequest request : activeRequests) {
try {
request.reset();
} catch (Exception e) {
log.debug("重置 JavaScript HTTP 请求失败: {}", e.getMessage());
}
Buffer buffer = response.body();
if (buffer == null) {
return 0;
}
activeRequests.clear();
}
if (ownClient && client != null) {
client.close();
}
}
private static void ensureResponseBodyLimit(Buffer buffer) {
if (buffer != null && buffer.length() > MAX_RESPONSE_BODY_BYTES) {
throw new IllegalArgumentException("响应体过大: " + buffer.length() + " bytes");
}
}
private static void ensureRequestBodyLimit(Buffer buffer) {
if (buffer != null && buffer.length() > MAX_REQUEST_BODY_BYTES) {
throw new IllegalArgumentException("请求体过大: " + buffer.length() + " bytes");
return buffer.length();
}
}
}
@@ -6,7 +6,6 @@ import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.IPanTool;
import cn.qaiu.parser.custom.CustomParserConfig;
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;
@@ -21,13 +20,6 @@ import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
/**
@@ -37,46 +29,21 @@ import java.util.stream.Collectors;
* @author <a href="https://qaiu.top">QAIU</a>
* Create at 2025/10/17
*/
public class JsParserExecutor implements IPanTool, AutoCloseable {
public class JsParserExecutor implements IPanTool {
private static final Logger log = LoggerFactory.getLogger(JsParserExecutor.class);
private static volatile WorkerExecutor EXECUTOR;
private static final Object EXECUTOR_LOCK = new Object();
private static volatile boolean executorShutdown = false;
/** 安全网调度器:当 onComplete 未触发时,延迟强制释放资源 */
private static final ScheduledExecutorService CLEANUP_SCHEDULER =
Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "js-parser-cleanup-safety");
t.setDaemon(true);
return t;
});
private static final long EXECUTION_TIMEOUT_SECONDS = 30;
private static final int MAX_RESULT_STRING_LENGTH = 1024 * 1024;
private static final int MAX_FILE_LIST_SIZE = 1000;
private static final int MAX_FILE_FIELD_LENGTH = 4096;
private static final int MAX_CONCURRENT_EXECUTIONS =
Math.max(1, Integer.getInteger("parser.custom.js.maxConcurrentExecutions", 32));
private static final Semaphore EXECUTION_PERMITS = new Semaphore(MAX_CONCURRENT_EXECUTIONS);
private static volatile String FETCH_RUNTIME_JS = null;
private static final WorkerExecutor EXECUTOR = WebClientVertxInit.get().createSharedWorkerExecutor("parser-executor", 32);
private static String FETCH_RUNTIME_JS = null;
private final CustomParserConfig config;
private final ShareLinkInfo shareLinkInfo;
private volatile ScriptEngine engine;
private final Object engineLock = new Object();
private final ScriptEngine engine;
private final JsHttpClient httpClient;
private final JsLogger jsLogger;
private final JsShareLinkInfoWrapper shareLinkInfoWrapper;
private final JsFetchBridge fetchBridge;
/** 标记是否已释放,防止重复关闭 */
private final AtomicBoolean closed = new AtomicBoolean(false);
private final Object lifecycleLock = new Object();
private volatile boolean running = false;
private volatile boolean closeRequested = false;
/** 安全网定时任务句柄,正常完成时取消 */
private volatile ScheduledFuture<?> safetyCleanupFuture = null;
public JsParserExecutor(ShareLinkInfo shareLinkInfo, CustomParserConfig config) {
this.config = config;
@@ -92,6 +59,7 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
this.jsLogger = new JsLogger("JsParser-" + config.getType());
this.shareLinkInfoWrapper = new JsShareLinkInfoWrapper(shareLinkInfo);
this.fetchBridge = new JsFetchBridge(httpClient);
this.engine = initEngine();
}
/**
@@ -143,7 +111,6 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
if (engine == null) {
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
}
this.engine = engine;
// 注入Java对象到JavaScript环境
engine.put("http", httpClient);
@@ -178,207 +145,28 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
throw new RuntimeException("JavaScript引擎初始化失败: " + e.getMessage(), e);
}
}
private ScriptEngine engine() {
ScriptEngine current = engine;
if (current != null) {
return current;
}
synchronized (engineLock) {
if (closed.get()) {
throw new IllegalStateException("JavaScript解析器已关闭");
}
if (engine == null) {
engine = initEngine();
}
return engine;
}
}
private void beginExecution() {
synchronized (lifecycleLock) {
if (closed.get() || closeRequested) {
throw new IllegalStateException("JavaScript解析器已关闭");
}
if (running) {
throw new IllegalStateException("JavaScript解析器已在运行");
}
running = true;
}
}
private void finishExecution() {
synchronized (lifecycleLock) {
running = false;
if (closeRequested) {
doClose();
}
}
}
/**
* 释放资源ScriptEngine HttpClient避免内存泄漏
* 幂等可安全多次调用
*/
@Override
public void close() {
synchronized (lifecycleLock) {
closeRequested = true;
cancelSafetyCleanup();
if (running || closed.get()) {
closeExternalResources();
return;
}
doClose();
}
}
private void doClose() {
if (!closed.compareAndSet(false, true)) return;
closeRequested = false;
closeExternalResources();
cleanupEngine();
}
private void closeExternalResources() {
if (httpClient != null) {
httpClient.close();
}
}
private void cleanupEngine() {
// 清除 ScriptEngine 持有的所有引用和内部状态帮助 GC 回收
if (engine != null) {
try {
engine.put("http", null);
engine.put("logger", null);
engine.put("shareLinkInfo", null);
engine.put("JavaFetch", null);
// 彻底清除 ENGINE_SCOPE bindings释放 JS AST编译函数闭包等运行时状态
var bindings = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
if (bindings != null) {
bindings.clear();
}
} catch (Exception e) {
log.warn("清理 ScriptEngine bindings 失败: {}", e.getMessage());
}
}
}
private void cancelSafetyCleanup() {
// 取消安全网定时任务如果正常完成则无需再触发
if (safetyCleanupFuture != null) {
safetyCleanupFuture.cancel(false);
safetyCleanupFuture = null;
}
}
/**
* 关闭全局 WorkerExecutor 和清理调度器应在应用关闭时调用
*/
public static void shutdownExecutor() {
synchronized (EXECUTOR_LOCK) {
executorShutdown = true;
if (EXECUTOR != null) {
EXECUTOR.close();
EXECUTOR = null;
log.info("JsParserExecutor WorkerExecutor 已关闭");
}
}
CLEANUP_SCHEDULER.shutdown();
}
/**
* 获取或创建 WorkerExecutor懒加载
*/
private static WorkerExecutor getExecutor() {
synchronized (EXECUTOR_LOCK) {
if (executorShutdown) {
throw new IllegalStateException("JavaScript解析器 WorkerExecutor 已关闭");
}
if (EXECUTOR == null) {
EXECUTOR = WebClientVertxInit.get().createSharedWorkerExecutor("parser-executor", 32);
}
return EXECUTOR;
}
}
private <T> Future<T> executeBlockingWithPermit(String operation, Callable<T> blockingCode) {
if (!EXECUTION_PERMITS.tryAcquire()) {
String message = "JavaScript " + operation + " 执行并发已满,请稍后重试";
jsLogger.error(message);
close();
return Future.failedFuture(message);
}
try {
return getExecutor().executeBlocking(() -> {
boolean executionStarted = false;
try {
beginExecution();
executionStarted = true;
return blockingCode.call();
} finally {
if (executionStarted) {
finishExecution();
}
EXECUTION_PERMITS.release();
}
});
} catch (Throwable e) {
EXECUTION_PERMITS.release();
close();
return Future.failedFuture(e);
}
}
private <T> Future<T> withTimeout(Future<T> executionFuture, String operation) {
Promise<T> promise = Promise.promise();
try {
safetyCleanupFuture = CLEANUP_SCHEDULER.schedule(() -> {
if (promise.tryFail("JavaScript " + operation + " 执行超时(" + EXECUTION_TIMEOUT_SECONDS + "秒)")) {
jsLogger.error("{} 执行超时,已停止外部HTTP资源;ScriptEngine将在执行线程退出后清理", operation);
close();
}
}, EXECUTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (Exception e) {
log.warn("安全网调度失败: {}", e.getMessage());
}
executionFuture.onComplete(ar -> {
cancelSafetyCleanup();
if (ar.succeeded()) {
promise.tryComplete(ar.result());
} else {
promise.tryFail(ar.cause());
}
close();
});
return promise.future();
}
@Override
public Future<String> parse() {
jsLogger.info("开始执行JavaScript解析器: {}", config.getType());
// 使用executeBlocking在工作线程上执行避免阻塞EventLoop线程
Future<String> executionFuture = executeBlockingWithPermit("parse", () -> {
ScriptEngine engine = engine();
return EXECUTOR.executeBlocking(() -> {
// 直接调用全局parse函数
Object parseFunction = engine.get("parse");
if (parseFunction == null) {
throw new RuntimeException("JavaScript代码中未找到parse函数");
}
if (parseFunction instanceof ScriptObjectMirror parseMirror) {
Object result = parseMirror.call(null, shareLinkInfoWrapper, httpClient, jsLogger);
if (result instanceof String) {
String resultText = limitResultString((String) result, "parse");
jsLogger.info("解析成功,结果长度: {}", resultText.length());
return resultText;
jsLogger.info("解析成功: {}", result);
return (String) result;
} else {
jsLogger.error("parse方法返回值类型错误,期望String,实际: {}",
jsLogger.error("parse方法返回值类型错误,期望String,实际: {}",
result != null ? result.getClass().getSimpleName() : "null");
throw new RuntimeException("parse方法返回值类型错误");
}
@@ -386,34 +174,32 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
throw new RuntimeException("parse函数类型错误");
}
});
return withTimeout(executionFuture, "parse");
}
@Override
public Future<List<FileInfo>> parseFileList() {
jsLogger.info("开始执行JavaScript文件列表解析: {}", config.getType());
// 使用executeBlocking在工作线程上执行避免阻塞EventLoop线程
Future<List<FileInfo>> executionFuture = executeBlockingWithPermit("parseFileList", () -> {
ScriptEngine engine = engine();
return EXECUTOR.executeBlocking(() -> {
// 直接调用全局parseFileList函数
Object parseFileListFunction = engine.get("parseFileList");
if (parseFileListFunction == null) {
throw new RuntimeException("JavaScript代码中未找到parseFileList函数");
}
// 调用parseFileList方法
if (parseFileListFunction instanceof ScriptObjectMirror parseFileListMirror) {
Object result = parseFileListMirror.call(null, shareLinkInfoWrapper, httpClient, jsLogger);
if (result instanceof ScriptObjectMirror resultMirror) {
List<FileInfo> fileList = convertToFileInfoList(resultMirror);
jsLogger.info("文件列表解析成功,共 {} 个文件", fileList.size());
return fileList;
} else {
jsLogger.error("parseFileList方法返回值类型错误,期望数组,实际: {}",
jsLogger.error("parseFileList方法返回值类型错误,期望数组,实际: {}",
result != null ? result.getClass().getSimpleName() : "null");
throw new RuntimeException("parseFileList方法返回值类型错误");
}
@@ -421,33 +207,30 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
throw new RuntimeException("parseFileList函数类型错误");
}
});
return withTimeout(executionFuture, "parseFileList");
}
@Override
public Future<String> parseById() {
jsLogger.info("开始执行JavaScript按ID解析: {}", config.getType());
// 使用executeBlocking在工作线程上执行避免阻塞EventLoop线程
Future<String> executionFuture = executeBlockingWithPermit("parseById", () -> {
ScriptEngine engine = engine();
return EXECUTOR.executeBlocking(() -> {
// 直接调用全局parseById函数
Object parseByIdFunction = engine.get("parseById");
if (parseByIdFunction == null) {
throw new RuntimeException("JavaScript代码中未找到parseById函数");
}
// 调用parseById方法
if (parseByIdFunction instanceof ScriptObjectMirror parseByIdMirror) {
Object result = parseByIdMirror.call(null, shareLinkInfoWrapper, httpClient, jsLogger);
if (result instanceof String) {
String resultText = limitResultString((String) result, "parseById");
jsLogger.info("按ID解析成功,结果长度: {}", resultText.length());
return resultText;
jsLogger.info("按ID解析成功: {}", result);
return (String) result;
} else {
jsLogger.error("parseById方法返回值类型错误,期望String,实际: {}",
jsLogger.error("parseById方法返回值类型错误,期望String,实际: {}",
result != null ? result.getClass().getSimpleName() : "null");
throw new RuntimeException("parseById方法返回值类型错误");
}
@@ -455,7 +238,6 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
throw new RuntimeException("parseById函数类型错误");
}
});
return withTimeout(executionFuture, "parseById");
}
/**
@@ -465,9 +247,6 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
List<FileInfo> fileList = new ArrayList<>();
if (resultMirror.isArray()) {
if (resultMirror.size() > MAX_FILE_LIST_SIZE) {
throw new RuntimeException("文件列表数量超过限制: " + resultMirror.size());
}
for (int i = 0; i < resultMirror.size(); i++) {
Object item = resultMirror.get(String.valueOf(i));
if (item instanceof ScriptObjectMirror) {
@@ -491,13 +270,13 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
// 设置基本字段
if (itemMirror.hasMember("fileName")) {
fileInfo.setFileName(limitField(itemMirror.getMember("fileName")));
fileInfo.setFileName(itemMirror.getMember("fileName").toString());
}
if (itemMirror.hasMember("fileId")) {
fileInfo.setFileId(limitField(itemMirror.getMember("fileId")));
fileInfo.setFileId(itemMirror.getMember("fileId").toString());
}
if (itemMirror.hasMember("fileType")) {
fileInfo.setFileType(limitField(itemMirror.getMember("fileType")));
fileInfo.setFileType(itemMirror.getMember("fileType").toString());
}
if (itemMirror.hasMember("size")) {
Object size = itemMirror.getMember("size");
@@ -506,16 +285,16 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
}
}
if (itemMirror.hasMember("sizeStr")) {
fileInfo.setSizeStr(limitField(itemMirror.getMember("sizeStr")));
fileInfo.setSizeStr(itemMirror.getMember("sizeStr").toString());
}
if (itemMirror.hasMember("createTime")) {
fileInfo.setCreateTime(limitField(itemMirror.getMember("createTime")));
fileInfo.setCreateTime(itemMirror.getMember("createTime").toString());
}
if (itemMirror.hasMember("updateTime")) {
fileInfo.setUpdateTime(limitField(itemMirror.getMember("updateTime")));
fileInfo.setUpdateTime(itemMirror.getMember("updateTime").toString());
}
if (itemMirror.hasMember("createBy")) {
fileInfo.setCreateBy(limitField(itemMirror.getMember("createBy")));
fileInfo.setCreateBy(itemMirror.getMember("createBy").toString());
}
if (itemMirror.hasMember("downloadCount")) {
Object downloadCount = itemMirror.getMember("downloadCount");
@@ -524,16 +303,16 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
}
}
if (itemMirror.hasMember("fileIcon")) {
fileInfo.setFileIcon(limitField(itemMirror.getMember("fileIcon")));
fileInfo.setFileIcon(itemMirror.getMember("fileIcon").toString());
}
if (itemMirror.hasMember("panType")) {
fileInfo.setPanType(limitField(itemMirror.getMember("panType")));
fileInfo.setPanType(itemMirror.getMember("panType").toString());
}
if (itemMirror.hasMember("parserUrl")) {
fileInfo.setParserUrl(limitField(itemMirror.getMember("parserUrl")));
fileInfo.setParserUrl(itemMirror.getMember("parserUrl").toString());
}
if (itemMirror.hasMember("previewUrl")) {
fileInfo.setPreviewUrl(limitField(itemMirror.getMember("previewUrl")));
fileInfo.setPreviewUrl(itemMirror.getMember("previewUrl").toString());
}
return fileInfo;
@@ -543,22 +322,4 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
return null;
}
}
private static String limitResultString(String value, String operation) {
if (value.length() > MAX_RESULT_STRING_LENGTH) {
throw new RuntimeException(operation + " 返回结果过大: " + value.length() + " 字符");
}
return value;
}
private static String limitField(Object value) {
if (value == null) {
return null;
}
String text = value.toString();
if (text.length() > MAX_FILE_FIELD_LENGTH) {
throw new RuntimeException("文件字段过长: " + text.length() + " 字符");
}
return text;
}
}
@@ -21,37 +21,20 @@ import java.util.concurrent.*;
*
* @author <a href="https://qaiu.top">QAIU</a>
*/
public class JsPlaygroundExecutor implements AutoCloseable {
public class JsPlaygroundExecutor {
private static final Logger log = LoggerFactory.getLogger(JsPlaygroundExecutor.class);
// JavaScript执行超时时间
private static final long EXECUTION_TIMEOUT_SECONDS = 30;
private static final int MAX_RESULT_STRING_LENGTH = 1024 * 1024;
private static final int MAX_FILE_LIST_SIZE = 1000;
private static final int MAX_FILE_FIELD_LENGTH = 4096;
private static final int TIMEOUT_LOG_RETAIN = 50;
// 使用有界线程池防止线程无限增长导致内存溢出
private static final int POOL_MAX_THREADS = 16;
private static final int POOL_QUEUE_CAPACITY = 256;
private static final ExecutorService INDEPENDENT_EXECUTOR = new ThreadPoolExecutor(
4, POOL_MAX_THREADS, 60L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(POOL_QUEUE_CAPACITY),
r -> {
Thread thread = new Thread(r);
thread.setName("playground-independent-" + thread.getId());
thread.setDaemon(true);
return thread;
},
(r, executor) -> {
// 拒绝策略记录日志并抛出异常避免阻塞 Vert.x EventLoop
log.warn("演练场线程池已满,拒绝任务。活跃线程: {}, 队列大小: {}",
((ThreadPoolExecutor) executor).getActiveCount(),
((ThreadPoolExecutor) executor).getQueue().size());
throw new java.util.concurrent.RejectedExecutionException("演练场线程池已满,请稍后重试");
}
);
// 使用独立的线程池不受Vert.x的BlockedThreadChecker监控
private static final ExecutorService INDEPENDENT_EXECUTOR = Executors.newCachedThreadPool(r -> {
Thread thread = new Thread(r);
thread.setName("playground-independent-" + System.currentTimeMillis());
thread.setDaemon(true); // 设置为守护线程服务关闭时自动清理
return thread;
});
// 超时调度线程池用于处理超时中断
private static final ScheduledExecutorService TIMEOUT_SCHEDULER = Executors.newScheduledThreadPool(2, r -> {
@@ -60,29 +43,14 @@ public class JsPlaygroundExecutor implements AutoCloseable {
thread.setDaemon(true);
return thread;
});
/**
* 关闭静态线程池应在应用关闭时调用
*/
public static void shutdownPools() {
INDEPENDENT_EXECUTOR.shutdown();
TIMEOUT_SCHEDULER.shutdown();
log.info("JsPlaygroundExecutor 线程池已关闭");
}
private final ShareLinkInfo shareLinkInfo;
private final String jsCode;
private volatile ScriptEngine engine;
private final Object engineLock = new Object();
private final ScriptEngine engine;
private final JsHttpClient httpClient;
private final JsPlaygroundLogger playgroundLogger;
private final JsShareLinkInfoWrapper shareLinkInfoWrapper;
private final JsFetchBridge fetchBridge;
/** 标记是否已释放,防止重复关闭 */
private volatile boolean closed = false;
private final Object lifecycleLock = new Object();
private volatile boolean running = false;
private volatile boolean closeRequested = false;
/**
* 创建演练场执行器
@@ -104,6 +72,7 @@ public class JsPlaygroundExecutor implements AutoCloseable {
this.playgroundLogger = new JsPlaygroundLogger();
this.shareLinkInfoWrapper = new JsShareLinkInfoWrapper(shareLinkInfo);
this.fetchBridge = new JsFetchBridge(httpClient);
this.engine = initEngine();
}
/**
@@ -120,7 +89,6 @@ public class JsPlaygroundExecutor implements AutoCloseable {
if (engine == null) {
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
}
this.engine = engine;
// 注入Java对象到JavaScript环境
engine.put("http", httpClient);
@@ -165,14 +133,9 @@ public class JsPlaygroundExecutor implements AutoCloseable {
*/
public Future<String> executeParseAsync() {
Promise<String> promise = Promise.promise();
final CompletableFuture<String> executionFuture;
try {
// 使用独立的ExecutorService执行避免Vert.x的BlockedThreadChecker输出警告
executionFuture = CompletableFuture.supplyAsync(() -> {
beginExecution();
try {
ScriptEngine engine = engine();
// 使用独立的ExecutorService执行避免Vert.x的BlockedThreadChecker输出警告
CompletableFuture<String> executionFuture = CompletableFuture.supplyAsync(() -> {
playgroundLogger.infoJava("开始执行parse方法");
try {
Object parseFunction = engine.get("parse");
@@ -188,9 +151,8 @@ public class JsPlaygroundExecutor implements AutoCloseable {
log.debug("[JsPlaygroundExecutor] parse函数执行完成,当前日志数量: {}", playgroundLogger.size());
if (result instanceof String) {
String resultText = limitResultString((String) result, "parse");
playgroundLogger.infoJava("解析成功,返回结果长度: " + resultText.length());
return resultText;
playgroundLogger.infoJava("解析成功,返回结果: " + result);
return (String) result;
} else {
String errorMsg = "parse方法返回值类型错误,期望String,实际: " +
(result != null ? result.getClass().getSimpleName() : "null");
@@ -205,27 +167,25 @@ public class JsPlaygroundExecutor implements AutoCloseable {
playgroundLogger.errorJava("执行parse方法失败: " + e.getMessage(), e);
throw new RuntimeException(e);
}
} finally {
finishExecution();
}
}, INDEPENDENT_EXECUTOR);
} catch (java.util.concurrent.RejectedExecutionException e) {
log.warn("演练场线程池已满,任务被拒绝");
close(); // 释放已创建的 ScriptEngine HttpClient 资源
promise.fail(new RuntimeException("演练场线程池已满,请稍后重试", e));
return promise.future();
}
ScheduledFuture<?> timeoutTask = scheduleTimeout(executionFuture, "parse");
// 创建超时任务强制取消执行
ScheduledFuture<?> timeoutTask = TIMEOUT_SCHEDULER.schedule(() -> {
if (!executionFuture.isDone()) {
executionFuture.cancel(true); // 强制中断执行线程
playgroundLogger.errorJava("执行超时,已强制中断");
log.warn("JavaScript执行超时,已强制取消");
}
}, EXECUTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
// 处理执行结果
executionFuture.whenComplete((result, error) -> {
// 取消超时任务
timeoutTask.cancel(false);
if (error != null) {
if (error instanceof CancellationException) {
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已返回超时并停止外部HTTP资源;ScriptEngine将在执行线程退出后清理";
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已强制中断";
playgroundLogger.errorJava(timeoutMsg);
log.error(timeoutMsg);
promise.fail(new RuntimeException(timeoutMsg));
@@ -237,10 +197,10 @@ public class JsPlaygroundExecutor implements AutoCloseable {
promise.complete(result);
}
});
return promise.future();
}
/**
* 执行parseFileList方法异步带超时控制
* 使用独立线程池不受Vert.x BlockedThreadChecker监控
@@ -249,14 +209,9 @@ public class JsPlaygroundExecutor implements AutoCloseable {
*/
public Future<List<FileInfo>> executeParseFileListAsync() {
Promise<List<FileInfo>> promise = Promise.promise();
final CompletableFuture<List<FileInfo>> executionFuture;
try {
// 使用独立的ExecutorService执行避免Vert.x的BlockedThreadChecker输出警告
executionFuture = CompletableFuture.supplyAsync(() -> {
beginExecution();
try {
ScriptEngine engine = engine();
// 使用独立的ExecutorService执行避免Vert.x的BlockedThreadChecker输出警告
CompletableFuture<List<FileInfo>> executionFuture = CompletableFuture.supplyAsync(() -> {
playgroundLogger.infoJava("开始执行parseFileList方法");
try {
Object parseFileListFunction = engine.get("parseFileList");
@@ -287,27 +242,25 @@ public class JsPlaygroundExecutor implements AutoCloseable {
playgroundLogger.errorJava("执行parseFileList方法失败: " + e.getMessage(), e);
throw new RuntimeException(e);
}
} finally {
finishExecution();
}
}, INDEPENDENT_EXECUTOR);
} catch (java.util.concurrent.RejectedExecutionException e) {
log.warn("演练场线程池已满,任务被拒绝");
close(); // 释放已创建的 ScriptEngine HttpClient 资源
promise.fail(new RuntimeException("演练场线程池已满,请稍后重试", e));
return promise.future();
}
ScheduledFuture<?> timeoutTask = scheduleTimeout(executionFuture, "parseFileList");
// 创建超时任务强制取消执行
ScheduledFuture<?> timeoutTask = TIMEOUT_SCHEDULER.schedule(() -> {
if (!executionFuture.isDone()) {
executionFuture.cancel(true); // 强制中断执行线程
playgroundLogger.errorJava("执行超时,已强制中断");
log.warn("JavaScript执行超时,已强制取消");
}
}, EXECUTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
// 处理执行结果
executionFuture.whenComplete((result, error) -> {
// 取消超时任务
timeoutTask.cancel(false);
if (error != null) {
if (error instanceof CancellationException) {
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已返回超时并停止外部HTTP资源;ScriptEngine将在执行线程退出后清理";
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已强制中断";
playgroundLogger.errorJava(timeoutMsg);
log.error(timeoutMsg);
promise.fail(new RuntimeException(timeoutMsg));
@@ -319,10 +272,10 @@ public class JsPlaygroundExecutor implements AutoCloseable {
promise.complete(result);
}
});
return promise.future();
}
/**
* 执行parseById方法异步带超时控制
* 使用独立线程池不受Vert.x BlockedThreadChecker监控
@@ -331,14 +284,9 @@ public class JsPlaygroundExecutor implements AutoCloseable {
*/
public Future<String> executeParseByIdAsync() {
Promise<String> promise = Promise.promise();
final CompletableFuture<String> executionFuture;
try {
// 使用独立的ExecutorService执行避免Vert.x的BlockedThreadChecker输出警告
executionFuture = CompletableFuture.supplyAsync(() -> {
beginExecution();
try {
ScriptEngine engine = engine();
// 使用独立的ExecutorService执行避免Vert.x的BlockedThreadChecker输出警告
CompletableFuture<String> executionFuture = CompletableFuture.supplyAsync(() -> {
playgroundLogger.infoJava("开始执行parseById方法");
try {
Object parseByIdFunction = engine.get("parseById");
@@ -352,9 +300,8 @@ public class JsPlaygroundExecutor implements AutoCloseable {
Object result = parseByIdMirror.call(null, shareLinkInfoWrapper, httpClient, playgroundLogger);
if (result instanceof String) {
String resultText = limitResultString((String) result, "parseById");
playgroundLogger.infoJava("按ID解析成功,返回结果长度: " + resultText.length());
return resultText;
playgroundLogger.infoJava("按ID解析成功: " + result);
return (String) result;
} else {
String errorMsg = "parseById方法返回值类型错误,期望String,实际: " +
(result != null ? result.getClass().getSimpleName() : "null");
@@ -369,27 +316,25 @@ public class JsPlaygroundExecutor implements AutoCloseable {
playgroundLogger.errorJava("执行parseById方法失败: " + e.getMessage(), e);
throw new RuntimeException(e);
}
} finally {
finishExecution();
}
}, INDEPENDENT_EXECUTOR);
} catch (java.util.concurrent.RejectedExecutionException e) {
log.warn("演练场线程池已满,任务被拒绝");
close(); // 释放已创建的 ScriptEngine HttpClient 资源
promise.fail(new RuntimeException("演练场线程池已满,请稍后重试", e));
return promise.future();
}
ScheduledFuture<?> timeoutTask = scheduleTimeout(executionFuture, "parseById");
// 创建超时任务强制取消执行
ScheduledFuture<?> timeoutTask = TIMEOUT_SCHEDULER.schedule(() -> {
if (!executionFuture.isDone()) {
executionFuture.cancel(true); // 强制中断执行线程
playgroundLogger.errorJava("执行超时,已强制中断");
log.warn("JavaScript执行超时,已强制取消");
}
}, EXECUTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
// 处理执行结果
executionFuture.whenComplete((result, error) -> {
// 取消超时任务
timeoutTask.cancel(false);
if (error != null) {
if (error instanceof CancellationException) {
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已返回超时并停止外部HTTP资源;ScriptEngine将在执行线程退出后清理";
String timeoutMsg = "JavaScript执行超时(超过" + EXECUTION_TIMEOUT_SECONDS + "秒),已强制中断";
playgroundLogger.errorJava(timeoutMsg);
log.error(timeoutMsg);
promise.fail(new RuntimeException(timeoutMsg));
@@ -401,7 +346,7 @@ public class JsPlaygroundExecutor implements AutoCloseable {
promise.complete(result);
}
});
return promise.future();
}
@@ -410,7 +355,7 @@ public class JsPlaygroundExecutor implements AutoCloseable {
*/
public List<JsPlaygroundLogger.LogEntry> getLogs() {
List<JsPlaygroundLogger.LogEntry> logs = playgroundLogger.getLogs();
log.debug("获取日志,数量: {}", logs.size());
System.out.println("[JsPlaygroundExecutor] 获取日志,数量: " + logs.size());
return logs;
}
@@ -428,9 +373,6 @@ public class JsPlaygroundExecutor implements AutoCloseable {
List<FileInfo> fileList = new ArrayList<>();
if (resultMirror.isArray()) {
if (resultMirror.size() > MAX_FILE_LIST_SIZE) {
throw new RuntimeException("文件列表数量超过限制: " + resultMirror.size());
}
for (int i = 0; i < resultMirror.size(); i++) {
Object item = resultMirror.get(String.valueOf(i));
if (item instanceof ScriptObjectMirror) {
@@ -454,13 +396,13 @@ public class JsPlaygroundExecutor implements AutoCloseable {
// 设置基本字段
if (itemMirror.hasMember("fileName")) {
fileInfo.setFileName(limitField(itemMirror.getMember("fileName")));
fileInfo.setFileName(itemMirror.getMember("fileName").toString());
}
if (itemMirror.hasMember("fileId")) {
fileInfo.setFileId(limitField(itemMirror.getMember("fileId")));
fileInfo.setFileId(itemMirror.getMember("fileId").toString());
}
if (itemMirror.hasMember("fileType")) {
fileInfo.setFileType(limitField(itemMirror.getMember("fileType")));
fileInfo.setFileType(itemMirror.getMember("fileType").toString());
}
if (itemMirror.hasMember("size")) {
Object size = itemMirror.getMember("size");
@@ -469,16 +411,16 @@ public class JsPlaygroundExecutor implements AutoCloseable {
}
}
if (itemMirror.hasMember("sizeStr")) {
fileInfo.setSizeStr(limitField(itemMirror.getMember("sizeStr")));
fileInfo.setSizeStr(itemMirror.getMember("sizeStr").toString());
}
if (itemMirror.hasMember("createTime")) {
fileInfo.setCreateTime(limitField(itemMirror.getMember("createTime")));
fileInfo.setCreateTime(itemMirror.getMember("createTime").toString());
}
if (itemMirror.hasMember("updateTime")) {
fileInfo.setUpdateTime(limitField(itemMirror.getMember("updateTime")));
fileInfo.setUpdateTime(itemMirror.getMember("updateTime").toString());
}
if (itemMirror.hasMember("createBy")) {
fileInfo.setCreateBy(limitField(itemMirror.getMember("createBy")));
fileInfo.setCreateBy(itemMirror.getMember("createBy").toString());
}
if (itemMirror.hasMember("downloadCount")) {
Object downloadCount = itemMirror.getMember("downloadCount");
@@ -487,154 +429,24 @@ public class JsPlaygroundExecutor implements AutoCloseable {
}
}
if (itemMirror.hasMember("fileIcon")) {
fileInfo.setFileIcon(limitField(itemMirror.getMember("fileIcon")));
fileInfo.setFileIcon(itemMirror.getMember("fileIcon").toString());
}
if (itemMirror.hasMember("panType")) {
fileInfo.setPanType(limitField(itemMirror.getMember("panType")));
fileInfo.setPanType(itemMirror.getMember("panType").toString());
}
if (itemMirror.hasMember("parserUrl")) {
fileInfo.setParserUrl(limitField(itemMirror.getMember("parserUrl")));
fileInfo.setParserUrl(itemMirror.getMember("parserUrl").toString());
}
if (itemMirror.hasMember("previewUrl")) {
fileInfo.setPreviewUrl(limitField(itemMirror.getMember("previewUrl")));
fileInfo.setPreviewUrl(itemMirror.getMember("previewUrl").toString());
}
return fileInfo;
} catch (Exception e) {
playgroundLogger.errorJava("转换FileInfo对象失败", e);
return null;
}
}
private static String limitResultString(String value, String operation) {
if (value.length() > MAX_RESULT_STRING_LENGTH) {
throw new RuntimeException(operation + " 返回结果过大: " + value.length() + " 字符");
}
return value;
}
private static String limitField(Object value) {
if (value == null) {
return null;
}
String text = value.toString();
if (text.length() > MAX_FILE_FIELD_LENGTH) {
throw new RuntimeException("文件字段过长: " + text.length() + " 字符");
}
return text;
}
private void beginExecution() {
synchronized (lifecycleLock) {
if (closed) {
throw new CancellationException("演练场执行器已关闭");
}
if (running) {
throw new IllegalStateException("演练场执行器已在运行");
}
running = true;
}
}
private ScriptEngine engine() {
ScriptEngine current = engine;
if (current != null) {
return current;
}
synchronized (engineLock) {
if (closed) {
throw new CancellationException("演练场执行器已关闭");
}
if (engine == null) {
engine = initEngine();
}
return engine;
}
}
private void finishExecution() {
synchronized (lifecycleLock) {
running = false;
if (closeRequested) {
doClose();
}
}
}
private ScheduledFuture<?> scheduleTimeout(CompletableFuture<?> executionFuture, String operation) {
// cancel(true) 只能请求中断Nashorn 死循环不保证立即停止
return TIMEOUT_SCHEDULER.schedule(() -> {
if (!executionFuture.isDone()) {
executionFuture.cancel(true);
playgroundLogger.errorJava(operation + " 执行超时,已请求取消并停止外部HTTP资源");
forceCloseAfterTimeout();
log.warn("JavaScript {} 执行超时,已请求取消;Nashorn长循环可能继续占用线程,ScriptEngine将在执行线程退出后清理", operation);
}
}, EXECUTION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
private void forceCloseAfterTimeout() {
synchronized (lifecycleLock) {
closeRequested = true;
if (running || closed) {
closeExternalResources();
} else {
doClose();
}
}
playgroundLogger.trimToLast(TIMEOUT_LOG_RETAIN);
}
/**
* 释放资源HttpClient ScriptEngine避免内存泄漏
* 幂等可安全多次调用
*/
@Override
public void close() {
synchronized (lifecycleLock) {
closeRequested = true;
if (running || closed) {
closeExternalResources();
return;
}
doClose();
}
}
private void doClose() {
if (closed) return;
closed = true;
closeRequested = false;
closeExternalResources();
cleanupEngine();
log.debug("JsPlaygroundExecutor 资源已释放");
}
private void closeExternalResources() {
if (httpClient != null) {
httpClient.close();
}
}
private void cleanupEngine() {
// 清除 ScriptEngine 的所有 bindings释放 JS 运行时引用
if (engine != null) {
try {
// 清除注入的 Java 对象引用
engine.put("http", null);
engine.put("logger", null);
engine.put("shareLinkInfo", null);
engine.put("JavaFetch", null);
// 清除所有 ENGINE_SCOPE bindings包括 eval 加载的 JS 函数
var bindings = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
if (bindings != null) {
bindings.clear();
}
} catch (Exception e) {
log.warn("清理 ScriptEngine bindings 失败: {}", e.getMessage());
}
}
}
}
@@ -4,9 +4,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 演练场日志收集器
* 收集JavaScript执行过程中的日志信息
@@ -15,12 +12,8 @@ import org.slf4j.LoggerFactory;
* @author <a href="https://qaiu.top">QAIU</a>
*/
public class JsPlaygroundLogger {
private static final Logger log = LoggerFactory.getLogger(JsPlaygroundLogger.class);
// 使用线程安全的列表
private static final int MAX_LOG_SIZE = 1000;
private static final int MAX_LOG_MESSAGE_LENGTH = 4096;
private final List<LogEntry> logs = Collections.synchronizedList(new ArrayList<>());
/**
@@ -63,25 +56,9 @@ public class JsPlaygroundLogger {
if (obj == null) {
return "null";
}
String msg = obj.toString();
if (msg.length() <= MAX_LOG_MESSAGE_LENGTH) {
return msg;
}
return msg.substring(0, MAX_LOG_MESSAGE_LENGTH) + "...[truncated]";
return obj.toString();
}
/**
* 添加日志条目超过最大容量时移除最早的条目
*/
private void addLog(LogEntry entry) {
synchronized (logs) {
if (logs.size() >= MAX_LOG_SIZE) {
logs.remove(0);
}
logs.add(entry);
}
}
/**
* 记录日志内部方法
* @param level 日志级别
@@ -90,8 +67,8 @@ public class JsPlaygroundLogger {
*/
private void log(String level, Object message, String source) {
String msg = toString(message);
addLog(new LogEntry(level, msg, source));
log.debug("[{}PlaygroundLogger] {}: {}", source, level, msg);
logs.add(new LogEntry(level, msg, source));
System.out.println("[" + source + "PlaygroundLogger] " + level + ": " + msg);
}
/**
@@ -132,10 +109,10 @@ public class JsPlaygroundLogger {
public void error(Object message, Throwable throwable) {
String msg = toString(message);
if (throwable != null) {
msg = toString(msg + ": " + throwable.getMessage());
msg = msg + ": " + throwable.getMessage();
}
addLog(new LogEntry("ERROR", msg, "JS"));
log.debug("[JSPlaygroundLogger] ERROR: {}", msg);
logs.add(new LogEntry("ERROR", msg, "JS"));
System.out.println("[JSPlaygroundLogger] ERROR: " + msg);
}
// ===== 以下是供Java层调用的内部方法 =====
@@ -172,12 +149,12 @@ public class JsPlaygroundLogger {
* 错误日志带异常供Java层调用
*/
public void errorJava(String message, Throwable throwable) {
String msg = toString(message);
String msg = message;
if (throwable != null) {
msg = toString(msg + ": " + throwable.getMessage());
msg = msg + ": " + throwable.getMessage();
}
addLog(new LogEntry("ERROR", msg, "JAVA"));
log.debug("[JAVAPlaygroundLogger] ERROR: {}", msg);
logs.add(new LogEntry("ERROR", msg, "JAVA"));
System.out.println("[JAVAPlaygroundLogger] ERROR: " + msg);
}
/**
@@ -202,17 +179,4 @@ public class JsPlaygroundLogger {
public void clear() {
logs.clear();
}
public void trimToLast(int maxEntries) {
if (maxEntries < 0) {
throw new IllegalArgumentException("maxEntries不能小于0");
}
synchronized (logs) {
int removeCount = logs.size() - maxEntries;
if (removeCount <= 0) {
return;
}
logs.subList(0, removeCount).clear();
}
}
}
@@ -31,8 +31,6 @@ public class JsScriptLoader {
private static final String RESOURCE_PATH = "custom-parsers";
private static final String EXTERNAL_PATH = "./custom-parsers";
private static final long MAX_SCRIPT_SIZE_BYTES = 128 * 1024;
private static final int MAX_EXTERNAL_SCRIPT_COUNT = 100;
// 系统属性配置的外部目录路径
private static final String EXTERNAL_PATH_PROPERTY = "parser.custom-parsers.path";
@@ -83,16 +81,14 @@ public class JsScriptLoader {
try {
InputStream inputStream = JsScriptLoader.class.getClassLoader()
.getResourceAsStream(resourceFile);
if (inputStream != null) {
try (inputStream) {
String jsCode = readResourceScript(inputStream, resourceFile);
CustomParserConfig config = JsScriptMetadataParser.parseScript(jsCode);
configs.add(config);
String fileName = resourceFile.substring(resourceFile.lastIndexOf('/') + 1);
log.debug("从资源目录加载脚本: {}", fileName);
}
String jsCode = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
CustomParserConfig config = JsScriptMetadataParser.parseScript(jsCode);
configs.add(config);
String fileName = resourceFile.substring(resourceFile.lastIndexOf('/') + 1);
log.debug("从资源目录加载脚本: {}", fileName);
}
} catch (Exception e) {
log.warn("加载资源脚本失败: {}", resourceFile, e);
@@ -143,20 +139,21 @@ public class JsScriptLoader {
try {
String jarPath = jarUrl.getPath().substring(5, jarUrl.getPath().indexOf("!"));
try (JarFile jarFile = new JarFile(jarPath)) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.startsWith(RESOURCE_PATH + "/") &&
entryName.endsWith(".js") &&
!isExcludedFile(entryName.substring(entryName.lastIndexOf('/') + 1))) {
resourceFiles.add(entryName);
}
JarFile jarFile = new JarFile(jarPath);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.startsWith(RESOURCE_PATH + "/") &&
entryName.endsWith(".js") &&
!isExcludedFile(entryName.substring(entryName.lastIndexOf('/') + 1))) {
resourceFiles.add(entryName);
}
}
jarFile.close();
} catch (Exception e) {
log.debug("解析JAR包资源文件失败", e);
}
@@ -211,10 +208,8 @@ public class JsScriptLoader {
paths.filter(Files::isRegularFile)
.filter(path -> path.toString().endsWith(".js"))
.filter(path -> !isExcludedFile(path.getFileName().toString()))
.limit(MAX_EXTERNAL_SCRIPT_COUNT)
.forEach(path -> {
try {
ensureScriptSize(path);
String jsCode = Files.readString(path, StandardCharsets.UTF_8);
CustomParserConfig config = JsScriptMetadataParser.parseScript(jsCode);
configs.add(config);
@@ -268,7 +263,6 @@ public class JsScriptLoader {
throw new IllegalArgumentException("文件不存在: " + filePath);
}
ensureScriptSize(path);
String jsCode = Files.readString(path, StandardCharsets.UTF_8);
return JsScriptMetadataParser.parseScript(jsCode);
@@ -286,16 +280,14 @@ public class JsScriptLoader {
try {
InputStream inputStream = JsScriptLoader.class.getClassLoader()
.getResourceAsStream(resourcePath);
if (inputStream == null) {
throw new IllegalArgumentException("资源文件不存在: " + resourcePath);
}
try (inputStream) {
String jsCode = readResourceScript(inputStream, resourcePath);
return JsScriptMetadataParser.parseScript(jsCode);
}
String jsCode = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
return JsScriptMetadataParser.parseScript(jsCode);
} catch (IOException e) {
throw new RuntimeException("读取资源文件失败: " + resourcePath, e);
}
@@ -355,19 +347,4 @@ public class JsScriptLoader {
fileName.contains(".test.") ||
fileName.contains(".spec.");
}
private static void ensureScriptSize(Path path) throws IOException {
long size = Files.size(path);
if (size > MAX_SCRIPT_SIZE_BYTES) {
throw new IllegalArgumentException("JavaScript脚本超过128KB限制: " + path.getFileName());
}
}
private static String readResourceScript(InputStream inputStream, String name) throws IOException {
byte[] bytes = inputStream.readNBytes((int) MAX_SCRIPT_SIZE_BYTES + 1);
if (bytes.length > MAX_SCRIPT_SIZE_BYTES) {
throw new IllegalArgumentException("JavaScript资源脚本超过128KB限制: " + name);
}
return new String(bytes, StandardCharsets.UTF_8);
}
}
@@ -2,7 +2,6 @@ package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.IPanTool;
import cn.qaiu.parser.PanBase;
import io.vertx.core.Future;
import io.vertx.core.buffer.Buffer;
@@ -161,7 +160,6 @@ public class CeTool extends PanBase {
} catch (Exception e) {
log.debug("v3 share API解析失败: {}", e.getMessage());
}
tryV4ShareApi(baseUrl, key, pwd);
}).onFailure(t -> {
log.debug("v3 share API请求失败: {}", t.getMessage());
// 请求失败尝试 v4 或下一个解析器
@@ -208,8 +206,7 @@ public class CeTool extends PanBase {
*/
private void delegateToCe4Tool() {
log.debug("检测到Cloudreve 4.x,转发到Ce4Tool处理");
Ce4Tool ce4Tool = new Ce4Tool(shareLinkInfo);
IPanTool.closeAfter(ce4Tool, ce4Tool::parse).onComplete(promise);
new Ce4Tool(shareLinkInfo).parse().onComplete(promise);
}
@@ -1,73 +1,36 @@
package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.PanBase;
import cn.qaiu.util.CommonUtils;
import cn.qaiu.util.FileSizeConverter;
import cn.qaiu.util.RandomStringGenerator;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.uritemplate.UriTemplate;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <a href="https://www.ctfile.com">诚通网盘</a>
*/
public class CtTool extends PanBase {
private static final String API_URL_PREFIX = "https://webapi.ctfile.com";
private static final String SHARE_FILE_URL_PREFIX = "https://ctfile.com/file/";
private static final String AJAX_ACCEPT = "application/json, text/javascript, */*; q=0.01";
private static final String BROWSER_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
private static final int FILE_LIST_PAGE_SIZE = 200;
private static final int MAX_FILE_LIST_PAGES = 50;
// https://webapi.ctfile.com/getfile.php?path=f&f=64115194-17569800420720-06c697&
// passcode=7609&r=0.6611183001986635&ref=&url=https%3A%2F%2Furl94.ctfile.com%2Ff%2F64115194-17569800420720-06c697%3Fp%3D7609
// https://webapi.ctfile.com/getfile.php?path=f&f=55050874-1246660795-6464f6&
// passcode=7548&token=30wiijxs1fzhb6brw0p9m6&r=0.5885881231735761&
// ref=&url=https%3A%2F%2F474b.com%2Ff%2F55050874-1246660795-6464f6%3Fp%3D7548
private static final String API1 = API_URL_PREFIX + "/getfile.php?path={path}" +
"&f={shareKey}&passcode={pwd}&r={rand}&ref=&url={url}";
"&f={shareKey}&passcode={pwd}&token={token}&r={rand}&ref=";
// https://webapi.ctfile.com/get_down_url.php?uid=64115194&fid=17569800420720&
// file_chk=af5c8757a49cbc69a557eb3da59b246c&start_time=1780471868&wait_seconds=0&rd=0.36...
private static final String API2 = API_URL_PREFIX + "/get_down_url.php?" +
"uid={uid}&fid={fid}&file_chk={file_chk}" +
"&start_time={start_time}&wait_seconds={wait_seconds}&rd={rand}";
//https://webapi.ctfile.com/get_file_url.php?uid=55050874&fid=1246660795&folder_id=0&
// file_chk=054bc20461f5c63ff82015b9e69fb7fc&mb=1&token=30wiijxs1fzhb6brw0p9m6&app=0&
// acheck=1&verifycode=&rd=0.965929071503574
private static final String API2 = API_URL_PREFIX + "/get_file_url.php?" +
"uid={uid}&fid={fid}&folder_id=0&file_chk={file_chk}&mb=0&token={token}&app=0&acheck=0&verifycode=" +
"&rd={rand}";
// https://webapi.ctfile.com/getdir.php?path=d&d=64115194-164803691-48508c&
// folder_id=164803691&fk=decb36&passcode=7609&r=0.23...&ref=&url=https://url94.ctfile.com/d/...
private static final String API_GETDIR = API_URL_PREFIX + "/getdir.php?path={path}" +
"&d={shareKey}&folder_id={folder_id}&fk={fk}&passcode={pwd}&r={rand}&ref=&url={url}";
// DataTables参数用于获取目录文件列表
private static final String FILE_LIST_PARAMS_TEMPLATE = "&sEcho=1&iColumns=4&sColumns=%2C%2C%2C" +
"&iDisplayStart={start}&iDisplayLength={length}" +
"&mDataProp_0=0&sSearch_0=&bRegex_0=false&bSearchable_0=true&bSortable_0=false" +
"&mDataProp_1=1&sSearch_1=&bRegex_1=false&bSearchable_1=true&bSortable_1=true" +
"&mDataProp_2=2&sSearch_2=&bRegex_2=false&bSearchable_2=true&bSortable_2=true" +
"&mDataProp_3=3&sSearch_3=&bRegex_3=false&bSearchable_3=true&bSortable_3=true" +
"&sSearch=&bRegex=false" +
"&iSortCol_0=3&sSortDir_0=desc&iSortingCols=1";
// 文件列表HTML解析正则
private static final Pattern FILE_ID_PATTERN = Pattern.compile("value=[\"']f(\\d+)[\"']");
private static final Pattern FOLDER_ID_PATTERN = Pattern.compile("value=[\"']d(\\d+)[\"']");
private static final Pattern FILE_HREF_PATTERN = Pattern.compile("href=[\"']#/f/([^\"']+)[\"']");
private static final Pattern FILE_NAME_PATTERN = Pattern.compile("<a\\b[^>]*>([^<]+)</a>", Pattern.CASE_INSENSITIVE);
private static final Pattern FILE_ICON_PATTERN = Pattern.compile("alt=[\"']([^\"']+)[\"']");
private static final Pattern SUBDIR_PATTERN = Pattern.compile("load_subdir\\s*\\((\\d+)\\s*,\\s*['\"]([^'\"]+)['\"]\\)");
/**
* 子类重写此构造方法不需要添加额外逻辑
@@ -88,586 +51,62 @@ public class CtTool extends PanBase {
@Override
public Future<String> parse() {
final String shareKey = shareLinkInfo.getShareKey();
if (shareKey == null || shareKey.indexOf('-') == -1) {
if (shareKey.indexOf('-') == -1) {
fail("shareKey格式不正确找不到'-': {}", shareKey);
return promise.future();
}
String[] split = shareKey.split("-");
if (split.length < 2 || split[0].isBlank() || split[1].isBlank()) {
fail("shareKey格式不正确: {}", shareKey);
return promise.future();
}
String fallbackUid = split[0], fallbackFid = split[1];
String path = extractPath(shareLinkInfo.getShareUrl());
String uid = split[0], fid = split[1];
String token = RandomStringGenerator.generateRandomString();
// 获取url path
int i1 = shareLinkInfo.getShareUrl().indexOf("com/");
int i2 = shareLinkInfo.getShareUrl().lastIndexOf("/");
String path = shareLinkInfo.getShareUrl().substring(i1 + 4, i2);
HttpRequest<Buffer> bufferHttpRequest1 = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API1))
HttpRequest<Buffer> bufferHttpRequest1 = clientSession.getAbs(UriTemplate.of(API1))
.setTemplateParam("path", path)
.setTemplateParam("shareKey", shareKey)
.setTemplateParam("pwd", shareLinkInfo.getSharePassword())
.setTemplateParam("rand", String.valueOf(Math.random()))
.setTemplateParam("url", shareLinkInfo.getShareUrl()), shareLinkInfo.getShareUrl());
.setTemplateParam("token", token)
.setTemplateParam("r", Math.random() + "");
bufferHttpRequest1
.send().onSuccess(res -> {
try {
var resJson = asJson(res);
if (resJson == null || resJson.isEmpty()) {
fail("解析失败, 上游返回空响应或非JSON响应");
return;
var resJson = asJson(res);
if (resJson.containsKey("file")) {
var fileJson = resJson.getJsonObject("file");
if (fileJson.containsKey("file_chk")) {
var file_chk = fileJson.getString("file_chk");
HttpRequest<Buffer> bufferHttpRequest2 = clientSession.getAbs(UriTemplate.of(API2))
.setTemplateParam("uid", uid)
.setTemplateParam("fid", fid)
.setTemplateParam("file_chk", file_chk)
.setTemplateParam("token", token)
.setTemplateParam("rd", Math.random() + "");
bufferHttpRequest2
.send().onSuccess(res2 -> {
JsonObject resJson2 = asJson(res2);
if (resJson2.containsKey("downurl")) {
String downloadUrl = resJson2.getString("downurl");
// 存储下载元数据包括必要的请求头
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
headers.put("Referer", shareLinkInfo.getShareUrl());
// 使用新的 completeWithMeta 方法
completeWithMeta(downloadUrl, headers);
} else {
fail("解析失败, 可能分享已失效: json: {} 字段 {} 不存在", resJson2, "downurl");
}
}).onFailure(handleFail(bufferHttpRequest1.queryParams().toString()));
} else {
fail("解析失败, file_chk找不到, 可能分享已失效或者分享密码不对: {}", fileJson);
}
Object fileValue = resJson.getValue("file");
if (!(fileValue instanceof JsonObject)) {
fail("解析失败, 文件信息为空或格式错误, 可能分享已失效: {}", resJson);
return;
}
var fileJson = (JsonObject) fileValue;
String uid = resolveDownloadUid(fileJson, fallbackUid);
String fid = resolveDownloadFid(fileJson, fallbackFid);
String fileChk = fileJson.getString("file_chk");
String startTime = valueToString(fileJson.getValue("start_time"));
String waitSeconds = valueToString(fileJson.getValue("wait_seconds"));
if (uid.isBlank() || fid.isBlank() || fileChk == null || fileChk.isBlank()
|| startTime.isBlank() || waitSeconds.isBlank()) {
fail("解析失败, 下载参数不完整, 可能分享已失效或者分享密码不对: {}", fileJson);
return;
}
// 提取文件信息并存储
FileInfo fileInfo = new FileInfo()
.setFileName(fileJson.getString("file_name"))
.setFileId(fid)
.setSizeStr(fileJson.getString("file_size"))
.setCreateTime(fileJson.getString("file_time"))
.setCreateBy(fileJson.getString("username"))
.setFileType("file")
.setPanType(shareLinkInfo.getType());
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
HttpRequest<Buffer> bufferHttpRequest2 = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API2))
.setTemplateParam("uid", uid)
.setTemplateParam("fid", fid)
.setTemplateParam("file_chk", fileChk)
.setTemplateParam("start_time", startTime)
.setTemplateParam("wait_seconds", waitSeconds)
.setTemplateParam("rand", String.valueOf(Math.random())), shareLinkInfo.getShareUrl());
bufferHttpRequest2
.send().onSuccess(res2 -> handleDownloadUrlResponse(res2))
.onFailure(t -> fail("下载链接请求失败: {}", t.getMessage()));
} catch (Exception e) {
fail("解析失败: {}", e.getMessage());
} else {
fail("解析失败, 文件信息为空, 可能分享已失效");
}
}).onFailure(t -> fail("文件信息请求失败: {}", t.getMessage()));
}).onFailure(handleFail(bufferHttpRequest1.queryParams().toString()));
return promise.future();
}
private void handleDownloadUrlResponse(io.vertx.ext.web.client.HttpResponse<Buffer> res) {
try {
JsonObject resJson = asJson(res);
if (resJson == null || resJson.isEmpty()) {
fail("解析失败, 下载接口返回空响应或非JSON响应");
return;
}
String downloadUrl = resJson.getString("downurl");
if (downloadUrl == null || downloadUrl.isBlank()) {
fail("解析失败, 可能分享已失效: json: {} 字段 {} 不存在", resJson, "downurl");
return;
}
// 存储下载元数据包括必要的请求头
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", BROWSER_UA);
if (shareLinkInfo.getShareUrl() != null && !shareLinkInfo.getShareUrl().isBlank()) {
headers.put("Referer", shareLinkInfo.getShareUrl());
}
// 使用新的 completeWithMeta 方法
completeWithMeta(downloadUrl, headers);
} catch (Exception e) {
fail("解析失败, 下载接口响应处理异常: {}", e.getMessage());
}
}
@Override
public Future<List<FileInfo>> parseFileList() {
Promise<List<FileInfo>> listPromise = Promise.promise();
final String shareKey = shareLinkInfo.getShareKey();
final String shareUrl = shareLinkInfo.getShareUrl();
final String pwd = shareLinkInfo.getSharePassword();
// shareKey格式: uid-folder_id-hash (例如 64115194-164803691-48508c)
if (shareKey == null) {
listPromise.fail(baseMsg() + " shareKey为空");
return listPromise.future();
}
String[] split = shareKey.split("-");
if (split.length < 2) {
listPromise.fail(baseMsg() + " shareKey格式不正确: " + shareKey);
return listPromise.future();
}
String path = extractPath(shareUrl);
Object dirId = shareLinkInfo.getOtherParam() == null ? null : shareLinkInfo.getOtherParam().get("dirId");
DirectoryContext directoryContext = resolveDirectoryContext(shareUrl, dirId);
HttpRequest<Buffer> getDirRequest = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API_GETDIR))
.setTemplateParam("path", path)
.setTemplateParam("shareKey", shareKey)
.setTemplateParam("folder_id", directoryContext.folderId)
.setTemplateParam("fk", directoryContext.folderKey)
.setTemplateParam("pwd", pwd != null ? pwd : "")
.setTemplateParam("rand", String.valueOf(Math.random()))
.setTemplateParam("url", shareUrl), shareUrl);
getDirRequest.send().onSuccess(res -> {
try {
var resJson = asJson(res);
if (resJson == null || resJson.isEmpty()) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: 上游返回空响应或非JSON响应");
return;
}
if (!resJson.containsKey("file")) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: " + resJson.encode());
return;
}
Object dirInfoValue = resJson.getValue("file");
if (!(dirInfoValue instanceof JsonObject)) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: file字段格式错误: " + resJson.encode());
return;
}
JsonObject dirInfo = (JsonObject) dirInfoValue;
Object fileListUrlValue = dirInfo.getValue("url");
String fileListRelUrl = fileListUrlValue instanceof String ? ((String) fileListUrlValue).trim() : "";
if (fileListRelUrl.isBlank()) {
failListPromise(listPromise, baseMsg() + " " + buildDirectoryFailureMessage(resJson, dirInfo));
return;
}
fetchFileListPage(toCtApiUrl(fileListRelUrl), 0, 0, new ArrayList<>(), listPromise,
shareLinkInfo.getType(), getDomainName(), shareUrl, pwd);
} catch (Exception e) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: " + e.getMessage());
}
}).onFailure(t -> failListPromise(listPromise, t));
return listPromise.future();
}
private void fetchFileListPage(String fileListBaseUrl, int start, int pageIndex, List<FileInfo> fileList,
Promise<List<FileInfo>> listPromise, String panType, String domainName,
String shareUrl, String pwd) {
try {
if (pageIndex >= MAX_FILE_LIST_PAGES) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 分页超过最大限制 " + MAX_FILE_LIST_PAGES
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
return;
}
String fileListUrl = appendQueryParams(fileListBaseUrl,
buildFileListParams(start, FILE_LIST_PAGE_SIZE) + "&_=" + System.currentTimeMillis());
withCtAjaxHeaders(clientSession.getAbs(fileListUrl), shareUrl)
.send()
.onSuccess(res -> handleFileListPageResponse(fileListBaseUrl, start, pageIndex, fileList,
listPromise, panType, domainName, shareUrl, pwd, res))
.onFailure(t -> failListPromise(listPromise, t));
} catch (Exception e) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: " + e.getMessage()
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
}
}
private void handleFileListPageResponse(String fileListBaseUrl, int start, int pageIndex, List<FileInfo> fileList,
Promise<List<FileInfo>> listPromise, String panType, String domainName,
String shareUrl, String pwd, io.vertx.ext.web.client.HttpResponse<Buffer> res) {
try {
var listJson = asJson(res);
if (listJson == null || listJson.isEmpty()) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 上游返回空响应或非JSON响应"
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
return;
}
Object aaDataValue = listJson.getValue("aaData");
if (!(aaDataValue instanceof JsonArray)) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: aaData为空: " + listJson.encode());
return;
}
JsonArray aaData = (JsonArray) aaDataValue;
for (int i = 0; i < aaData.size(); i++) {
try {
Object rowValue = aaData.getValue(i);
if (!(rowValue instanceof JsonArray)) {
log.warn("城通文件列表行格式错误: {}", rowValue);
continue;
}
FileInfo fileInfo = parseFileListRow((JsonArray) rowValue, panType,
domainName, shareUrl, pwd);
if (fileInfo != null) {
fileList.add(fileInfo);
}
} catch (Exception e) {
log.warn("解析文件行失败: {}", e.getMessage());
}
}
int nextStart = start + aaData.size();
int total = parseFileListTotal(listJson);
if (isUnexpectedEmptyFileListPage(start, aaData.size(), total)) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 上游返回空分页"
+ " (start=" + start + ", total=" + total + ")");
return;
}
if (shouldFetchNextFileListPage(start, aaData.size(), total)) {
fetchFileListPage(fileListBaseUrl, nextStart, pageIndex + 1, fileList,
listPromise, panType, domainName, shareUrl, pwd);
} else {
completeListPromise(listPromise, fileList);
}
} catch (Exception e) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: " + e.getMessage()
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
}
}
@Override
public Future<String> parseById() {
Object paramValue = shareLinkInfo.getOtherParam().get("paramJson");
if (!(paramValue instanceof JsonObject)) {
Promise<String> parsePromise = Promise.promise();
parsePromise.fail(baseMsg() + " 缺少下载参数paramJson");
return parsePromise.future();
}
JsonObject paramJson = (JsonObject) paramValue;
if (!applyFileParam(shareLinkInfo, paramJson)) {
Promise<String> parsePromise = Promise.promise();
parsePromise.fail(baseMsg() + " 下载参数id为空");
return parsePromise.future();
}
return parse();
}
static boolean applyFileParam(ShareLinkInfo shareLinkInfo, JsonObject paramJson) {
String fileShareKey = paramJson.getString("id");
if (fileShareKey == null || fileShareKey.isBlank()) {
return false;
}
shareLinkInfo.setSharePassword(paramJson.getString("pwd", ""));
shareLinkInfo.setShareKey(fileShareKey);
shareLinkInfo.setShareUrl(SHARE_FILE_URL_PREFIX + fileShareKey);
shareLinkInfo.setStandardUrl(SHARE_FILE_URL_PREFIX + fileShareKey);
return true;
}
static String resolveDownloadUid(JsonObject fileJson, String fallbackUid) {
return firstNonBlank(valueToString(fileJson.getValue("userid")), fallbackUid);
}
static String resolveDownloadFid(JsonObject fileJson, String fallbackFid) {
return firstNonBlank(valueToString(fileJson.getValue("file_id")), fallbackFid);
}
private HttpRequest<Buffer> withCtAjaxHeaders(HttpRequest<Buffer> request, String shareUrl) {
request.putHeader("User-Agent", BROWSER_UA)
.putHeader("Accept", AJAX_ACCEPT)
.putHeader("X-Requested-With", "XMLHttpRequest");
if (shareUrl != null && !shareUrl.isBlank()) {
request.putHeader("Referer", shareUrl);
}
String origin = extractOrigin(shareUrl);
if (!origin.isBlank()) {
request.putHeader("Origin", origin);
}
return request;
}
static FileInfo parseFileListRow(JsonArray row, String panType, String domainName, String shareUrl, String pwd) {
if (row == null || row.size() < 2) {
return null;
}
String checkboxHtml = rowString(row, 0);
String nameCellHtml = rowString(row, 1);
String sizeStr = rowString(row, 2).trim();
String dateStr = rowString(row, 3).trim();
if (nameCellHtml.isBlank()) {
return null;
}
String fileName = matchFirst(FILE_NAME_PATTERN, nameCellHtml);
String fileIcon = matchFirst(FILE_ICON_PATTERN, nameCellHtml);
if (fileName == null || fileName.isBlank()) {
return null;
}
Matcher subdirMatcher = SUBDIR_PATTERN.matcher(nameCellHtml);
boolean hasSubdirCall = subdirMatcher.find();
if (hasSubdirCall || "folder".equalsIgnoreCase(fileIcon)) {
String folderId = hasSubdirCall ? subdirMatcher.group(1) : null;
String folderKey = hasSubdirCall ? subdirMatcher.group(2) : "";
if (folderId == null) {
folderId = matchFirst(FOLDER_ID_PATTERN, checkboxHtml);
}
if (folderId == null || folderId.isBlank()) {
return null;
}
String dirId = folderId + ":" + folderKey;
FileInfo fileInfo = new FileInfo()
.setFileName(fileName.trim())
.setFileId(folderId)
.setSize(0L)
.setSizeStr(sizeStr.isBlank() ? "0B" : sizeStr)
.setFileType("folder")
.setFileIcon(fileIcon)
.setPanType(panType)
.setParserUrl(buildFolderParserUrl(domainName, shareUrl, dirId, pwd));
if (!dateStr.isBlank()) {
fileInfo.setCreateTime(dateStr).setUpdateTime(dateStr);
}
return fileInfo;
}
String fileShareKey = matchFirst(FILE_HREF_PATTERN, nameCellHtml);
if (fileShareKey == null || fileShareKey.isBlank()) {
return null;
}
String fileId = matchFirst(FILE_ID_PATTERN, checkboxHtml);
JsonObject paramJson = new JsonObject()
.put("id", fileShareKey)
.put("fileName", fileName.trim())
.put("pwd", pwd == null ? "" : pwd);
String param = CommonUtils.urlBase64Encode(paramJson.encode());
long sizeBytes = 0;
try {
sizeBytes = sizeStr.isBlank() ? 0 : FileSizeConverter.convertToBytes(sizeStr);
} catch (Exception ignored) {
}
FileInfo fileInfo = new FileInfo()
.setFileName(fileName.trim())
.setFileId(fileId)
.setSizeStr(sizeStr)
.setSize(sizeBytes)
.setFileType(fileIcon != null ? fileIcon : "file")
.setFileIcon(fileIcon)
.setPanType(panType)
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
domainName, panType, param));
if (!dateStr.isBlank()) {
fileInfo.setCreateTime(dateStr).setUpdateTime(dateStr);
}
return fileInfo;
}
private static String buildFolderParserUrl(String domainName, String shareUrl, String dirId, String pwd) {
String url = String.format("%s/v2/getFileList?url=%s&dirId=%s",
domainName, urlEncode(shareUrl), urlEncode(dirId));
if (pwd != null && !pwd.isBlank()) {
url += "&pwd=" + urlEncode(pwd);
}
return url;
}
static String extractQueryParam(String url, String paramName) {
if (url == null || paramName == null) return null;
int qIdx = url.indexOf('?');
if (qIdx < 0) return null;
String query = url.substring(qIdx + 1);
int fragmentIdx = query.indexOf('#');
if (fragmentIdx >= 0) {
query = query.substring(0, fragmentIdx);
}
for (String param : query.split("&")) {
int eqIdx = param.indexOf('=');
if (eqIdx > 0 && urlDecode(param.substring(0, eqIdx)).equals(paramName)) {
return urlDecode(param.substring(eqIdx + 1));
}
}
return null;
}
static String extractPath(String shareUrl) {
if (shareUrl == null) {
return "";
}
int comIdx = shareUrl.indexOf("com/");
if (comIdx < 0) {
return "";
}
int pathStart = comIdx + 4;
int pathEnd = shareUrl.indexOf('/', pathStart);
if (pathEnd < 0) {
pathEnd = shareUrl.indexOf('?', pathStart);
}
if (pathEnd < 0) {
pathEnd = shareUrl.length();
}
return shareUrl.substring(pathStart, pathEnd);
}
static String extractFolderKey(String shareUrl) {
return trimToEmpty(extractQueryParam(shareUrl, "fk"));
}
static DirectoryContext resolveDirectoryContext(String shareUrl, Object dirIdObj) {
String dirId = dirIdObj == null ? "" : urlDecode(String.valueOf(dirIdObj).trim());
if (!dirId.isBlank()) {
String[] split = dirId.split(":", 2);
return new DirectoryContext(trimToDefault(split[0], "undefined"),
split.length > 1 ? trimToEmpty(split[1]) : "");
}
String queryFolderId = firstNonBlank(extractQueryParam(shareUrl, "folder_id"), extractQueryParam(shareUrl, "d"));
String queryFk = extractFolderKey(shareUrl);
if (!queryFolderId.isBlank() || !queryFk.isBlank()) {
return new DirectoryContext(trimToDefault(queryFolderId, "undefined"), queryFk);
}
return new DirectoryContext("undefined", "");
}
static String buildDirectoryFailureMessage(JsonObject resJson, JsonObject dirInfo) {
String code = valueToString(resJson.getValue("code"));
String message = valueToString(dirInfo.getValue("message"));
if (message != null && !message.isBlank()) {
return "目录解析失败: " + message + " (code=" + code + ")";
}
if ("423".equals(code)) {
return "目录解析失败: 需要访问密码或该分享受限 (code=423)";
}
return "目录解析失败: 文件列表URL为空, 上游响应: " + resJson.encode();
}
static String buildFileListParams(int start, int length) {
return FILE_LIST_PARAMS_TEMPLATE
.replace("{start}", String.valueOf(Math.max(0, start)))
.replace("{length}", String.valueOf(Math.max(1, length)));
}
static int parseFileListTotal(JsonObject listJson) {
int displayTotal = parseInteger(listJson.getValue("iTotalDisplayRecords"), -1);
return displayTotal >= 0 ? displayTotal : parseInteger(listJson.getValue("iTotalRecords"), -1);
}
static boolean shouldFetchNextFileListPage(int start, int rowCount, int total) {
if (rowCount <= 0) {
return false;
}
int fetchedThrough = start + rowCount;
return total < 0 ? rowCount >= FILE_LIST_PAGE_SIZE : fetchedThrough < total;
}
static boolean isUnexpectedEmptyFileListPage(int start, int rowCount, int total) {
return total >= 0 && start < total && rowCount <= 0;
}
private static int parseInteger(Object value, int defaultValue) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value == null) {
return defaultValue;
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return defaultValue;
}
}
private static void failListPromise(Promise<List<FileInfo>> listPromise, String message) {
if (!listPromise.future().isComplete()) {
listPromise.fail(message);
}
}
private static void failListPromise(Promise<List<FileInfo>> listPromise, Throwable throwable) {
if (!listPromise.future().isComplete()) {
listPromise.fail(throwable);
}
}
private static void completeListPromise(Promise<List<FileInfo>> listPromise, List<FileInfo> fileList) {
if (!listPromise.future().isComplete()) {
listPromise.complete(fileList);
}
}
private static String toCtApiUrl(String url) {
if (url.startsWith("http://") || url.startsWith("https://")) {
return url;
}
return API_URL_PREFIX + url;
}
private static String appendQueryParams(String url, String params) {
String normalizedParams = params != null && params.startsWith("&") ? params.substring(1) : params;
return url + (url.contains("?") ? "&" : "?") + normalizedParams;
}
private static String rowString(JsonArray row, int index) {
if (row == null || index >= row.size()) {
return "";
}
return valueToString(row.getValue(index));
}
private static String valueToString(Object value) {
return value == null ? "" : value.toString();
}
private static String matchFirst(Pattern pattern, String text) {
if (text == null) {
return null;
}
Matcher matcher = pattern.matcher(text);
return matcher.find() ? matcher.group(1) : null;
}
private static String firstNonBlank(String first, String second) {
return !trimToEmpty(first).isBlank() ? trimToEmpty(first) : trimToEmpty(second);
}
private static String trimToDefault(String value, String defaultValue) {
String result = trimToEmpty(value);
return result.isBlank() ? defaultValue : result;
}
private static String trimToEmpty(String value) {
return value == null ? "" : value.trim();
}
private static String urlEncode(String value) {
return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8);
}
private static String urlDecode(String value) {
if (value == null) {
return "";
}
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8);
} catch (Exception e) {
return value;
}
}
private static String extractOrigin(String shareUrl) {
try {
URI uri = URI.create(shareUrl);
if (uri.getScheme() == null || uri.getHost() == null) {
return "";
}
String origin = uri.getScheme() + "://" + uri.getHost();
return uri.getPort() > 0 ? origin + ":" + uri.getPort() : origin;
} catch (Exception e) {
return "";
}
}
static final class DirectoryContext {
final String folderId;
final String folderKey;
DirectoryContext(String folderId, String folderKey) {
this.folderId = folderId;
this.folderKey = folderKey;
}
}
}
@@ -25,10 +25,6 @@ public class FcTool extends PanBase {
private static final String DOWN_REQUEST_URL = "https://v2.fangcloud.cn/apps/files/download?file_id={fid}" +
"&scenario=share&unique_name={uname}";
// 静态编译的正则表达式避免每次调用都重新编译
private static final Pattern REQUEST_TOKEN_PATTERN = Pattern.compile("name=\"requesttoken\"\\s+value=\"([a-zA-Z0-9_+=]+)\"");
private static final Pattern TYPED_ID_PATTERN = Pattern.compile("id=\"typed_id\"\\s+value=\"file_(\\d+)\"");
public FcTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
}
@@ -45,7 +41,8 @@ public class FcTool extends PanBase {
if (StringUtils.isNotEmpty(pwd)) {
// 获取requesttoken
String html = res.bodyAsString();
Matcher matcher = REQUEST_TOKEN_PATTERN.matcher(html);
Pattern compile = Pattern.compile("name=\"requesttoken\"\\s+value=\"([a-zA-Z0-9_+=]+)\"");
Matcher matcher = compile.matcher(html);
if (!matcher.find()) {
fail(SHARE_URL_PREFIX + " 未匹配到加密分享的密码输入页面的requesttoken");
return;
@@ -74,7 +71,8 @@ public class FcTool extends PanBase {
WebClientSession sClient) {
// 从HTML中找到文件id
String html = res.bodyAsString();
Matcher matcher = TYPED_ID_PATTERN.matcher(html);
Pattern compile = Pattern.compile("id=\"typed_id\"\\s+value=\"file_(\\d+)\"");
Matcher matcher = compile.matcher(html);
if (!matcher.find()) {
fail(SHARE_URL_PREFIX + " 未匹配到文件id(typed_id)");
return;
@@ -109,9 +109,9 @@ public class FjTool extends PanBase {
// String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
static volatile String token = null;
static volatile String userId = null;
public static volatile boolean authFlag = true;
static String token = null;
static String userId = null;
public static boolean authFlag = true;
public FjTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
@@ -169,13 +169,8 @@ public class FjTool extends PanBase {
// 文件Id
JsonObject fileInfo = resJson.getJsonArray("list").getJsonObject(0);
JsonArray fileListArray = fileInfo.getJsonArray("fileList");
if (fileListArray == null || fileListArray.isEmpty()) {
fail(FIRST_REQUEST_URL + " 文件列表为空: " + fileInfo);
return;
}
// 如果是目录返回目录ID
JsonObject fileList = fileListArray.getJsonObject(0);
JsonObject fileList = fileInfo.getJsonArray("fileList").getJsonObject(0);
if (fileList.getInteger("fileType") == 2) {
promise.complete(fileList.getInteger("folderId").toString());
return;
@@ -294,14 +289,12 @@ public class FjTool extends PanBase {
JsonObject json = asJson(res2);
if (json.getInteger("code") == 200) {
token = json.getJsonObject("data").getString("appToken");
MultiMap h0 = MultiMap.caseInsensitiveMultiMap();
h0.addAll(header0);
h0.set("appToken", token);
log.info("登录成功 token: {}...", token != null ? token.substring(0, Math.min(8, token.length())) : "null");
header0.set("appToken", token);
log.info("登录成功 token: {}", token);
client.postAbs(UriTemplate.of(TOKEN_VERIFY_URL))
.setTemplateParam("uuid", uuid)
.setTemplateParam("ts", tsEncode2)
.putHeaders(h0).send().onSuccess(res -> {
.putHeaders(header0).send().onSuccess(res -> {
if (asJson(res).getInteger("code") == 200) {
if (FjTool.userId == null) {
FjTool.userId = asJson(res).getJsonObject("map").getString("userId");
@@ -461,10 +454,7 @@ public class FjTool extends PanBase {
// 如果参数里的目录ID不为空则直接解析目录
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
if (dirId != null && !dirId.isEmpty()) {
Object uuidObj = shareLinkInfo.getOtherParam().get("uuid");
if (uuidObj != null) {
uuid = uuidObj.toString();
}
uuid = shareLinkInfo.getOtherParam().get("uuid").toString();
parserDir(dirId, shareId, promise0);
return promise0.future();
}
@@ -505,7 +495,7 @@ public class FjTool extends PanBase {
JsonArray list;
try {
JsonObject jsonObject = asJson(res);
log.debug("目录列表: {}", jsonObject.encodePrettily());
System.out.println(jsonObject.encodePrettily());
list = jsonObject.getJsonArray("list");
} catch (Exception e) {
log.error("解析目录失败: {}", res.bodyAsString());
@@ -586,10 +576,6 @@ public class FjTool extends PanBase {
// 第二次请求
JsonObject paramJson = (JsonObject)shareLinkInfo.getOtherParam().get("paramJson");
if (paramJson == null) {
promise.fail("缺少 paramJson 参数");
return promise.future();
}
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
.setTemplateParam("fidEncode", paramJson.getString("fidEncode"))
.setTemplateParam("uuid", paramJson.getString("uuid"))
@@ -389,10 +389,6 @@ public class FsTool extends PanBase {
try {
JsonObject paramJson = (JsonObject) shareLinkInfo.getOtherParam().get("paramJson");
if (paramJson == null) {
parsePromise.fail("缺少 paramJson 参数");
return parsePromise.future();
}
String shareUrl = paramJson.getString("shareUrl");
String objToken = paramJson.getString("objToken");
String tenant = extractTenant(shareUrl);
@@ -448,7 +444,7 @@ public class FsTool extends PanBase {
if (m1.find()) {
try {
return URLDecoder.decode(m1.group(1).trim(), StandardCharsets.UTF_8);
} catch (IllegalArgumentException ignored) {
} catch (Exception ignored) {
}
}
@@ -457,7 +453,7 @@ public class FsTool extends PanBase {
if (m2.find()) {
try {
return URLDecoder.decode(m2.group(1).trim(), StandardCharsets.UTF_8);
} catch (IllegalArgumentException ignored) {
} catch (Exception ignored) {
}
}
@@ -31,12 +31,10 @@ public class GenShortUrl extends PanBase {
private static final String WRAPPER_URL = "https://www.so.com/link?m=ewgUSYiFWXIoTybC3fJH8YoJy8y10iRquo6cazgINwWjTn3HvVJ92TrCJu0PmMUR0RMDfOAucP3wa4G8j64SrhNH9Z0Cr0PEyn9ASuvpkUGmAjjUEGJkO5%2BIDGWVrEkPHsL7UsoKO6%2BlT%2BD6r&ccc=";
private static final String MID = "5095144728824883"; // 微博的mid
private static final Pattern SHORT_URL_PATTERN = Pattern.compile("(https?)://t.cn/\\w+");
private static final Pattern COMMENT_ID_PATTERN = Pattern.compile("comment_id=\"(\\d+)\"");
private static final MultiMap HEADER = HeadersMultiMap.headers()
.add("Content-Type", "application/x-www-form-urlencoded")
.add("Referer", "https://www.weibo.com")
.add("Content-Type", "application/x-www-form-urlencoded")
.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
Cookie cookie = new DefaultCookie("SUB", "_2A25KJE5vDeRhGeRJ6lsR9SjJzDuIHXVpWM-nrDV8PUJbkNAbLVPlkW1NUmJm3GjYtRHBsHdMUKafkdTL_YheMEmu");
@@ -66,12 +64,11 @@ public class GenShortUrl extends PanBase {
String shortUrl = extractShortUrl(comment);
if (shortUrl != null) {
log.info("生成的短链:{}", shortUrl);
// 先完成 promise返回短链
promise.complete(shortUrl);
// 异步清理评论best-effort不影响结果
String commentId = extractCommentId(comment);
if (commentId != null) {
deleteComment(commentId);
} else {
promise.fail("未能提取评论ID");
}
} else {
promise.fail("未能生成短链");
@@ -106,7 +103,8 @@ public class GenShortUrl extends PanBase {
}
private String extractShortUrl(String comment) {
Matcher matcher = SHORT_URL_PATTERN.matcher(comment);
Pattern pattern = Pattern.compile("(https?)://t.cn/\\w+");
Matcher matcher = pattern.matcher(comment);
if (matcher.find()) {
return matcher.group(0);
}
@@ -114,7 +112,8 @@ public class GenShortUrl extends PanBase {
}
private String extractCommentId(String comment) {
Matcher matcher = COMMENT_ID_PATTERN.matcher(comment);
Pattern pattern = Pattern.compile("comment_id=\"(\\d+)\"");
Matcher matcher = pattern.matcher(comment);
if (matcher.find()) {
return matcher.group(1);
}
@@ -52,14 +52,4 @@ public class IzSelectorTool implements IPanTool {
public Future<String> parseById() {
return selectedTool.parseById();
}
@Override
public ShareLinkInfo getShareLinkInfo() {
return selectedTool.getShareLinkInfo();
}
@Override
public void close() {
IPanTool.closeQuietly(selectedTool);
}
}
@@ -89,8 +89,8 @@ public class IzTool extends PanBase {
String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
public static volatile String token = null;
public static volatile boolean authFlag = true;
public static String token = null;
public static boolean authFlag = true;
public Future<String> parse() {
@@ -101,8 +101,8 @@ public class IzTool extends PanBase {
// 检查并输出认证状态
if (shareLinkInfo.getOtherParam().containsKey("auths")) {
boolean isTempAuth = shareLinkInfo.getOtherParam().containsKey("__TEMP_AUTH_ADDED");
log.info("文件解析检测到认证信息: isTempAuth={}, authFlag={}, token={}",
isTempAuth, authFlag, token != null ? "已登录(" + token.substring(0, Math.min(8, token.length())) + "...)" : "未登录");
log.info("文件解析检测到认证信息: isTempAuth={}, authFlag={}, token={}",
isTempAuth, authFlag, token != null ? "已登录(" + token.substring(0, Math.min(10, token.length())) + "...)" : "未登录");
// 如果需要认证但还没有token先执行登录
if ((isTempAuth || authFlag) && token == null) {
@@ -118,7 +118,7 @@ public class IzTool extends PanBase {
// 登录失败继续使用免登录模式
});
} else if (token != null) {
log.info("文件解析使用已有token: {}...", token.substring(0, Math.min(8, token.length())));
log.info("文件解析使用已有token: {}...", token.substring(0, Math.min(10, token.length())));
}
} else {
log.debug("文件解析无认证信息,使用免登录模式");
@@ -247,7 +247,7 @@ public class IzTool extends PanBase {
log.warn("登录失败: {}", failRes.getMessage());
fail(failRes.getMessage());
}).onSuccess(r-> {
httpRequest.setTemplateParam("appToken", token)
httpRequest.setTemplateParam("appToken", header.get("appToken"))
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
});
@@ -263,12 +263,12 @@ public class IzTool extends PanBase {
log.warn("重新登录失败: {}", failRes.getMessage());
fail(failRes.getMessage());
}).onSuccess(r-> {
httpRequest.setTemplateParam("appToken", token)
httpRequest.setTemplateParam("appToken", header.get("appToken"))
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
});
} else {
httpRequest.setTemplateParam("appToken", token)
httpRequest.setTemplateParam("appToken", header.get("appToken"))
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
}
@@ -311,7 +311,8 @@ public class IzTool extends PanBase {
JsonObject json = asJson(res2);
if (json.getInteger("code") == 200) {
token = json.getJsonObject("data").getString("appToken");
log.info("登录成功 token: {}...", token != null ? token.substring(0, Math.min(8, token.length())) : "null");
header.set("appToken", token);
log.info("登录成功 token: {}", token);
promise1.complete();
} else {
// 检查是否为临时认证
@@ -443,75 +444,16 @@ public class IzTool extends PanBase {
}
}
private void down(HttpResponse<Buffer> res2) {
MultiMap headers = res2.headers();
String location = headers.get("Location");
if (StringUtils.isBlank(location)) {
fail("{}", buildMissingLocationMessage(res2));
return;
}
promise.complete(location);
}
private String buildMissingLocationMessage(HttpResponse<Buffer> response) {
StringBuilder message = new StringBuilder("未获取到下载重定向地址");
message.append(", HTTP ").append(response.statusCode());
String body = null;
try {
body = asText(response);
} catch (Exception e) {
body = "<响应体读取失败: " + e.getMessage() + ">";
}
if (StringUtils.isNotBlank(body)) {
try {
JsonObject json = new JsonObject(body);
String upstreamMsg = json.getString("msg");
Object code = json.getValue("code");
if (StringUtils.isNotBlank(upstreamMsg)) {
message.append(", 上游返回: ").append(upstreamMsg);
if (code != null) {
message.append(" (code=").append(code).append(")");
}
} else {
message.append(", 响应体: ").append(previewBody(body));
}
} catch (Exception ignored) {
message.append(", 响应体: ").append(previewBody(body));
}
} else {
message.append(", 响应体为空");
}
Object fileName = shareLinkInfo.getOtherParam().get("fileName");
Object fileSize = shareLinkInfo.getOtherParam().get("fileSizeFormat");
if (fileName != null) {
message.append(", 文件: ").append(fileName);
}
if (fileSize != null) {
message.append(", 大小: ").append(fileSize);
}
if (!hasConfiguredAuth()) {
message.append(", 当前为免登录解析,上游可能要求登录、会员或人工处理");
}
return message.toString();
}
private boolean hasConfiguredAuth() {
Object authObj = shareLinkInfo.getOtherParam().get("auths");
if (!(authObj instanceof MultiMap auths)) {
return false;
}
return StringUtils.isNotBlank(auths.get("username")) && StringUtils.isNotBlank(auths.get("password"));
}
private String previewBody(String body) {
int maxLength = 500;
return body.length() <= maxLength ? body : body.substring(0, maxLength) + "...";
}
// 目录解析
private void down(HttpResponse<Buffer> res2) {
MultiMap headers = res2.headers();
if (!headers.contains("Location") || StringUtils.isBlank(headers.get("Location"))) {
fail("找不到下载链接可能服务器已被禁止或者配置的认证信息有误");
return;
}
promise.complete(headers.get("Location"));
}
// 目录解析
@Override
public Future<List<FileInfo>> parseFileList() {
Promise<List<FileInfo>> promise = Promise.promise();
@@ -521,10 +463,7 @@ public class IzTool extends PanBase {
// 如果参数里的目录ID不为空则直接解析目录
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
if (dirId != null && !dirId.isEmpty()) {
Object uuidObj = shareLinkInfo.getOtherParam().get("uuid");
if (uuidObj != null) {
uuid = uuidObj.toString();
}
uuid = shareLinkInfo.getOtherParam().get("uuid").toString();
parserDir(dirId, shareId, promise);
return promise.future();
}
@@ -88,8 +88,8 @@ public class IzToolWithAuth extends PanBase {
String uuid = UUID.randomUUID().toString().toLowerCase(); // 也可以使用 UUID.randomUUID().toString()
public static volatile String token = null;
public static volatile boolean authFlag = true;
public static String token = null;
public static boolean authFlag = true;
public Future<String> parse() {
@@ -216,7 +216,7 @@ public class IzToolWithAuth extends PanBase {
log.warn("登录失败: {}", failRes.getMessage());
fail(failRes.getMessage());
}).onSuccess(r-> {
httpRequest.setTemplateParam("appToken", token)
httpRequest.setTemplateParam("appToken", header.get("appToken"))
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
});
@@ -232,12 +232,12 @@ public class IzToolWithAuth extends PanBase {
log.warn("重新登录失败: {}", failRes.getMessage());
fail(failRes.getMessage());
}).onSuccess(r-> {
httpRequest.setTemplateParam("appToken", token)
httpRequest.setTemplateParam("appToken", header.get("appToken"))
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
});
} else {
httpRequest.setTemplateParam("appToken", token)
httpRequest.setTemplateParam("appToken", header.get("appToken"))
.putHeaders(header);
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
}
@@ -280,7 +280,8 @@ public class IzToolWithAuth extends PanBase {
JsonObject json = asJson(res2);
if (json.getInteger("code") == 200) {
token = json.getJsonObject("data").getString("appToken");
log.info("登录成功 token: {}...", token != null ? token.substring(0, Math.min(8, token.length())) : "null");
header.set("appToken", token);
log.info("登录成功 token: {}", token);
promise1.complete();
} else {
// 检查是否为临时认证
@@ -414,70 +415,11 @@ public class IzToolWithAuth extends PanBase {
private void down(HttpResponse<Buffer> res2) {
MultiMap headers = res2.headers();
String location = headers.get("Location");
if (StringUtils.isBlank(location)) {
fail("{}", buildMissingLocationMessage(res2));
if (!headers.contains("Location") || StringUtils.isBlank(headers.get("Location"))) {
fail("找不到下载链接可能服务器已被禁止或者配置的认证信息有误");
return;
}
promise.complete(location);
}
private String buildMissingLocationMessage(HttpResponse<Buffer> response) {
StringBuilder message = new StringBuilder("未获取到下载重定向地址");
message.append(", HTTP ").append(response.statusCode());
String body = null;
try {
body = asText(response);
} catch (Exception e) {
body = "<响应体读取失败: " + e.getMessage() + ">";
}
if (StringUtils.isNotBlank(body)) {
try {
JsonObject json = new JsonObject(body);
String upstreamMsg = json.getString("msg");
Object code = json.getValue("code");
if (StringUtils.isNotBlank(upstreamMsg)) {
message.append(", 上游返回: ").append(upstreamMsg);
if (code != null) {
message.append(" (code=").append(code).append(")");
}
} else {
message.append(", 响应体: ").append(previewBody(body));
}
} catch (Exception ignored) {
message.append(", 响应体: ").append(previewBody(body));
}
} else {
message.append(", 响应体为空");
}
Object fileName = shareLinkInfo.getOtherParam().get("fileName");
Object fileSize = shareLinkInfo.getOtherParam().get("fileSizeFormat");
if (fileName != null) {
message.append(", 文件: ").append(fileName);
}
if (fileSize != null) {
message.append(", 大小: ").append(fileSize);
}
if (!hasConfiguredAuth()) {
message.append(", 当前为免登录解析,上游可能要求登录、会员或人工处理");
}
return message.toString();
}
private boolean hasConfiguredAuth() {
Object authObj = shareLinkInfo.getOtherParam().get("auths");
if (!(authObj instanceof MultiMap auths)) {
return false;
}
return StringUtils.isNotBlank(auths.get("username")) && StringUtils.isNotBlank(auths.get("password"));
}
private String previewBody(String body) {
int maxLength = 500;
return body.length() <= maxLength ? body : body.substring(0, maxLength) + "...";
promise.complete(headers.get("Location"));
}
// 目录解析
@@ -490,8 +432,7 @@ public class IzToolWithAuth extends PanBase {
// 如果参数里的目录ID不为空则直接解析目录
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
if (dirId != null && !dirId.isEmpty()) {
Object uuidObj = shareLinkInfo.getOtherParam().get("uuid");
uuid = uuidObj != null ? uuidObj.toString() : null;
uuid = shareLinkInfo.getOtherParam().get("uuid").toString();
parserDir(dirId, shareId, promise);
return promise.future();
}
@@ -539,7 +480,7 @@ public class IzToolWithAuth extends PanBase {
requestDirList(id, shareId, tsEncode, promise);
})
.onSuccess(r -> {
log.info("目录解析登录成功,token={}, 使用 VIP 模式", token != null ? token.substring(0, Math.min(8, token.length())) + "..." : "null");
log.info("目录解析登录成功,token={}, 使用 VIP 模式", token != null ? token.substring(0, 10) + "..." : "null");
requestDirList(id, shareId, tsEncode, promise);
});
return;
@@ -686,7 +627,7 @@ public class IzToolWithAuth extends PanBase {
// 如果有 token使用 VIP 接口
if (StringUtils.isNotBlank(appToken)) {
log.debug("parseById 使用 VIP 接口, appToken={}", appToken.substring(0, Math.min(8, appToken.length())) + "...");
log.debug("parseById 使用 VIP 接口, appToken={}", appToken.substring(0, Math.min(10, appToken.length())) + "...");
webClientSession.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
.putHeaders(header)
.setTemplateParam("fidEncode", paramJson.getString("fidEncode"))
@@ -15,7 +15,6 @@ import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Random;
import java.util.UUID;
/**
@@ -25,7 +24,6 @@ public class LeTool extends PanBase {
private static final String API_URL_PREFIX = "https://lecloud.lenovo.com/mshare/api/clouddiskapi/share/public/v1/";
private static final String DEFAULT_FILE_TYPE = "file";
private static final int FILE_TYPE_DIRECTORY = 0; // 目录类型
private static final Random RANDOM = new Random();
private static final MultiMap HEADERS;
@@ -102,8 +100,8 @@ public class LeTool extends PanBase {
}
String fileId = fileInfoJson.getString("fileId");
// 根据文件ID获取跳转链接随机选择方式失败自动fallback
getDownURLWithFallback(dataKey, fileId);
// 根据文件ID获取跳转链接
getDownURL(dataKey, fileId);
}
} else {
fail("{}: {}", resJson.getString("errcode"), resJson.getString("errmsg"));
@@ -262,8 +260,8 @@ public class LeTool extends PanBase {
String shareId = paramJson.getString("shareId");
String fileId = paramJson.getString("fileId");
// 调用获取下载链接随机选择方式失败自动fallback
getDownURLWithFallbackForById(shareId, fileId, parsePromise);
// 调用获取下载链接
getDownURLForById(shareId, fileId, parsePromise);
} catch (Exception e) {
parsePromise.fail("解析参数失败: " + e.getMessage());
@@ -306,22 +304,14 @@ public class LeTool extends PanBase {
}).onFailure(err -> promise.fail(err));
}
/**
* 通过 packageDownloadWithFileIds 接口获取下载链接
* 需要两步先获取 downloadUrl再请求 302 跳转
*
* @param shareId 分享ID
* @param fileId 文件ID
* @param promise 完成时会写入此 promise
*/
private void getDownURL(String shareId, String fileId, Promise<String> promise) {
private void getDownURL(String key, String fileId) {
String uuid = UUID.randomUUID().toString();
JsonArray fileIds = JsonArray.of(fileId);
String apiUrl = API_URL_PREFIX + "packageDownloadWithFileIds";
String apiUrl2 = API_URL_PREFIX + "packageDownloadWithFileIds";
// {"fileIds":[123],"shareId":"xxx","browserId":"uuid"}
client.postAbs(apiUrl)
client.postAbs(apiUrl2)
.putHeaders(HEADERS)
.sendJsonObject(JsonObject.of("fileIds", fileIds, "shareId", shareId, "browserId", uuid))
.sendJsonObject(JsonObject.of("fileIds", fileIds, "shareId", key, "browserId", uuid))
.onSuccess(res -> {
JsonObject resJson = asJson(res);
if (resJson.containsKey("result")) {
@@ -330,107 +320,20 @@ public class LeTool extends PanBase {
// 获取重定向链接跳转链接
String downloadUrl = dataJson.getString("downloadUrl");
if (downloadUrl == null) {
promise.fail("Result JSON数据异常: downloadUrl不存在");
fail("Result JSON数据异常: downloadUrl不存在");
return;
}
// 获取重定向链接跳转链接
clientNoRedirects.getAbs(downloadUrl).send()
.onSuccess(res2 -> promise.complete(res2.headers().get("Location")))
.onFailure(err -> promise.fail(err));
.onFailure(handleFail(downloadUrl));
} else {
promise.fail(resJson.getString("errcode") + ": " + resJson.getString("errmsg"));
fail("{}: {}", resJson.getString("errcode"), resJson.getString("errmsg"));
}
} else {
promise.fail("Result JSON数据异常: result字段不存在");
fail("Result JSON数据异常: result字段不存在");
}
}).onFailure(err -> promise.fail(err));
}
/**
* 通过 directDownload 接口获取下载链接
* 相比 packageDownloadWithFileIds 少一次请求直接返回302
*
* @param shareId 分享ID
* @param fileId 文件ID
* @param promise 完成时会写入此 promise
*/
private void getDownURLDirect(String shareId, String fileId, Promise<String> promise) {
String uuid = UUID.randomUUID().toString();
String apiUrl = API_URL_PREFIX + "directDownload"
+ "?shareId=" + shareId
+ "&fileId=" + fileId
+ "&browserId=" + uuid;
clientNoRedirects.getAbs(apiUrl)
.putHeaders(HEADERS)
.send()
.onSuccess(res -> {
String location = res.headers().get("Location");
if (location != null && !location.isEmpty()) {
promise.complete(location);
} else {
log.warn("directDownload 返回非302响应: shareId={}, fileId={}, statusCode={}", shareId, fileId, res.statusCode());
promise.fail("directDownload 未返回有效的 Location, statusCode=" + res.statusCode());
}
})
.onFailure(err -> {
log.warn("directDownload 请求失败: shareId={}, fileId={}, error={}", shareId, fileId, err.getMessage());
promise.fail(err);
});
}
/**
* 随机选择下载方式并带 fallback用于 parse
* 先随机选择 directDownload packageDownloadWithFileIds失败则尝试另一个
*/
private void getDownURLWithFallback(String shareId, String fileId) {
boolean useDirect = RANDOM.nextBoolean();
log.info("乐云下载方式选择: shareId={}, fileId={}, method={}", shareId, fileId, useDirect ? "directDownload" : "packageDownloadWithFileIds");
Promise<String> fallbackPromise = Promise.promise();
fallbackPromise.future().onSuccess(url -> {
promise.complete(url);
}).onFailure(err -> {
log.warn("乐云第一种下载方式失败,尝试另一种: {}", err.getMessage());
if (useDirect) {
getDownURL(shareId, fileId, promise);
} else {
getDownURLDirect(shareId, fileId, promise);
}
});
if (useDirect) {
getDownURLDirect(shareId, fileId, fallbackPromise);
} else {
getDownURL(shareId, fileId, fallbackPromise);
}
}
/**
* 随机选择下载方式并带 fallback用于 parseById
* 先随机选择 directDownload packageDownloadWithFileIds失败则尝试另一个
*/
private void getDownURLWithFallbackForById(String shareId, String fileId, Promise<String> promise) {
boolean useDirect = RANDOM.nextBoolean();
log.info("乐云下载方式选择(parseById): shareId={}, fileId={}, method={}", shareId, fileId, useDirect ? "directDownload" : "packageDownloadWithFileIds");
Promise<String> fallbackPromise = Promise.promise();
fallbackPromise.future().onSuccess(url -> {
promise.complete(url);
}).onFailure(err -> {
log.warn("乐云第一种下载方式失败,尝试另一种: {}", err.getMessage());
if (useDirect) {
getDownURLForById(shareId, fileId, promise);
} else {
getDownURLDirect(shareId, fileId, promise);
}
});
if (useDirect) {
getDownURLDirect(shareId, fileId, fallbackPromise);
} else {
getDownURLForById(shareId, fileId, fallbackPromise);
}
}).onFailure(handleFail(apiUrl2));
}
/**
@@ -14,9 +14,6 @@ import io.vertx.ext.web.client.WebClientSession;
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
import javax.script.ScriptException;
import java.net.MalformedURLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -33,20 +30,6 @@ public class LzTool extends PanBase {
WebClientSession webClientSession = WebClientSession.create(clientNoRedirects);
public static final String SHARE_URL_PREFIX = "https://w1.lanzn.com/";
// 静态编译的正则表达式避免每次调用都重新编译
private static final Pattern FILE_NAME_PATTERN = Pattern.compile("padding: 56px 0px 20px 0px;\">(.*?)<|filenajax\">(.*?)<");
private static final Pattern FILE_SIZE_PATTERN = Pattern.compile(">文件大小:</span>(.*?)<br>|\"n_filesize\">大小:(.*?)</div>");
private static final Pattern SHARE_USER_PATTERN = Pattern.compile(">分享用户:</span><font>(.*?)</font>|获取<span>(.*?)</span>的文件|\"user-name\">(.*?)</");
private static final Pattern DESCRIPTION_PATTERN = Pattern.compile("(?s)文件描述:</span><br>(.*?)</td>|class=\"n_box_des\">(.*?)</div>");
private static final Pattern FILE_ID_PATTERN = Pattern.compile("\\?f=(.*?)&|fid = (.*?);");
private static final Pattern CREATE_TIME_PATTERN = Pattern.compile(">上传时间:</span>(.*?)<");
private static final Pattern URL_DATE_PATTERN = Pattern.compile("(\\d{4}/\\d{1,2}/\\d{1,2})");
private static final Pattern ARG1_PATTERN = Pattern.compile("var arg1='([^']+)'");
private static final Pattern IFRAME_SRC_PATTERN = Pattern.compile("src=\"(/fn\\?[a-zA-Z\\d_+/=]{16,})\"");
private static final Pattern RELATIVE_TIME_PATTERN = Pattern.compile("^(\\d+|几)\\s*(分钟|小时)前$");
private static final Pattern DATE_PATTERN = Pattern.compile("^(\\d{4})\\s*[-/年]\\s*(\\d{1,2})\\s*[-/月]\\s*(\\d{1,2})\\s*日?$");
private static final Pattern MONTH_DAY_PATTERN = Pattern.compile("^(\\d{1,2})\\s*月\\s*(\\d{1,2})\\s*日?$");
MultiMap headers0 = HeaderUtils.parseHeaders("""
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Encoding: gzip, deflate
@@ -78,30 +61,19 @@ public class LzTool extends PanBase {
client.getAbs(sUrl)
.putHeaders(headers0)
.send().onSuccess(res -> {
try {
String html = asText(res);
if (hasAcwArg1(html)) {
webClientSession = WebClientSession.create(clientNoRedirects);
if (!setCookie(html, sUrl)) {
fail("蓝奏云反爬 arg1 Cookie 解析失败,页面内容异常");
return;
}
webClientSession.getAbs(sUrl)
.putHeaders(headers0)
.send().onSuccess(res2 -> {
try {
String html2 = asText(res2);
doParser(html2, pwd, sUrl);
} catch (Exception e) {
fail("蓝奏云页面响应处理异常: {}", e.getMessage());
}
}).onFailure(handleFail(sUrl));
String html = asText(res);
if (html.contains("var arg1='")) {
webClientSession = WebClientSession.create(clientNoRedirects);
setCookie(html, sUrl);
webClientSession.getAbs(sUrl)
.putHeaders(headers0)
.send().onSuccess(res2 -> {
String html2 = asText(res2);
doParser(html2, pwd, sUrl);
});
} else {
doParser(html, pwd, sUrl);
}
} catch (Exception e) {
fail("蓝奏云页面响应处理异常: {}", e.getMessage());
} else {
doParser(html, pwd, sUrl);
}
}).onFailure(handleFail(sUrl));
@@ -109,41 +81,22 @@ public class LzTool extends PanBase {
}
private void doParser(String html, String pwd, String sUrl) {
if (html == null || html.isBlank()) {
fail("蓝奏云页面响应为空");
return;
}
if (isShareCancelledPage(html)) {
fail("分享已失效或文件已取消分享");
return;
}
// 检测是否为目录分享链接 ( /s//b/ 路径段或 b 开头的路径段)
if (sUrl.matches(".*/(s|b)/[^/]+.*") || sUrl.matches(".*/b[^/]+.*")) {
// 检测是否为目录分享链接 ( /s//b/ 路径段或 b0 开头的路径段)
if (sUrl.matches(".*/(s|b)/[^/]+.*") || sUrl.matches(".*/b0[^/]+.*")) {
fail("该链接为蓝奏云目录分享,请使用目录解析接口");
return;
}
// 若仍是校验页 (parse()中cookie域名与实际URL不匹配时会出现), 重试一次
if (hasAcwArg1(html)) {
if (html.contains("var arg1='")) {
webClientSession = WebClientSession.create(clientNoRedirects);
if (!setCookie(html, sUrl)) {
fail("蓝奏云反爬 arg1 Cookie 解析失败,页面内容异常");
return;
}
setCookie(html, sUrl);
webClientSession.getAbs(sUrl).putHeaders(headers0).send().onSuccess(res -> {
try {
String html2 = asText(res);
if (isShareCancelledPage(html2)) {
fail("分享已失效或文件已取消分享");
return;
}
if (hasAcwArg1(html2)) {
fail("蓝奏云反爬校验失败,请稍后重试");
return;
}
doParserInternal(html2, pwd, sUrl);
} catch (Exception e) {
fail("蓝奏云页面响应处理异常: {}", e.getMessage());
String html2 = asText(res);
if (html2.contains("var arg1='")) {
fail("蓝奏云反爬校验失败,请稍后重试");
return;
}
doParserInternal(html2, pwd, sUrl);
}).onFailure(handleFail(sUrl));
return;
}
@@ -151,21 +104,14 @@ public class LzTool extends PanBase {
}
private void doParserInternal(String html, String pwd, String sUrl) {
if (html == null || html.isBlank()) {
fail("蓝奏云页面响应为空");
return;
}
if (isShareCancelledPage(html)) {
fail("分享已失效或文件已取消分享");
return;
}
try {
setFileInfo(html, shareLinkInfo);
} catch (Exception e) {
log.error("文件信息解析异常", e);
e.printStackTrace();
}
// 匹配iframe
Matcher matcher = IFRAME_SRC_PATTERN.matcher(html);
Pattern compile = Pattern.compile("src=\"(/fn\\?[a-zA-Z\\d_+/=]{16,})\"");
Matcher matcher = compile.matcher(html);
// 没有Iframe说明是加密分享, 匹配sign通过密码请求下载页面
if (!matcher.find()) {
try {
@@ -179,64 +125,46 @@ public class LzTool extends PanBase {
// 没有密码
String iframePath = matcher.group(1);
String absoluteURI = SHARE_URL_PREFIX + iframePath;
// 创建局部副本避免修改实例字段导致累积
MultiMap headersCopy = MultiMap.caseInsensitiveMultiMap().addAll(headers0);
headersCopy.add("Referer", absoluteURI);
webClientSession.getAbs(absoluteURI).putHeaders(headersCopy).send().onSuccess(res2 -> {
try {
String html2 = asText(res2);
if (isShareCancelledPage(html2)) {
fail("分享已失效或文件已取消分享");
return;
}
String jsText = getJsText(html2);
if (jsText == null) {
if (!setCookie(html2, absoluteURI)) {
fail("蓝奏云反爬 arg1 Cookie 解析失败,页面内容异常");
return;
}
webClientSession.getAbs(absoluteURI).send().onSuccess(res3 -> {
webClientSession.getAbs(absoluteURI).putHeaders(headers0).send().onSuccess(res2 -> {
String html2 = asText(res2);
String jsText = getJsText(html2);
if (jsText == null) {
headers0.add("Referer", absoluteURI);
setCookie(html2, absoluteURI);
webClientSession.getAbs(absoluteURI).send().onSuccess(res3 -> {
String html3 = asText(res3);
String jsText3 = getJsText(html3);
if (jsText3 != null) {
try {
String html3 = asText(res3);
if (isShareCancelledPage(html3)) {
fail("分享已失效或文件已取消分享");
return;
}
String jsText3 = getJsText(html3);
if (jsText3 != null) {
try {
ScriptObjectMirror scriptObjectMirror = JsExecUtils.executeDynamicJs(jsText3, null);
getDownURL(sUrl, scriptObjectMirror);
} catch (ScriptException | NoSuchMethodException e) {
fail(e, "引擎执行失败");
}
} else {
fail(SHARE_URL_PREFIX + iframePath + " -> " + sUrl + ": 获取失败0, 可能分享已失效");
}
} catch (Exception e) {
fail("蓝奏云 iframe 响应处理异常: {}", e.getMessage());
ScriptObjectMirror scriptObjectMirror = JsExecUtils.executeDynamicJs(jsText3, null);
getDownURL(sUrl, scriptObjectMirror);
} catch (ScriptException | NoSuchMethodException e) {
fail(e, "引擎执行失败");
}
}).onFailure(handleFail(absoluteURI));
} else {
try {
ScriptObjectMirror scriptObjectMirror = JsExecUtils.executeDynamicJs(jsText, null);
getDownURL(sUrl, scriptObjectMirror);
} catch (ScriptException | NoSuchMethodException e) {
fail(e, "js引擎执行失败");
} else {
fail(SHARE_URL_PREFIX + iframePath + " -> " + sUrl + ": 获取失败0, 可能分享已失效");
}
});
} else {
try {
ScriptObjectMirror scriptObjectMirror = JsExecUtils.executeDynamicJs(jsText, null);
getDownURL(sUrl, scriptObjectMirror);
} catch (ScriptException | NoSuchMethodException e) {
fail(e, "js引擎执行失败");
}
} catch (Exception e) {
fail("蓝奏云 iframe 响应处理异常: {}", e.getMessage());
}
}).onFailure(handleFail(SHARE_URL_PREFIX));
}
}
private boolean setCookie(String html, String url) {
String arg1 = extractAcwArg1(html);
if (arg1 == null) {
return false;
private void setCookie(String html, String url) {
int beginIndex = html.indexOf("arg1='") + 6;
int endIndex = html.indexOf("';", beginIndex);
if (beginIndex < 6 || endIndex == -1 || endIndex <= beginIndex) {
fail("蓝奏云反爬 arg1 Cookie 解析失败,页面内容异常");
return;
}
String arg1 = html.substring(beginIndex, endIndex);
String acw_sc__v2 = AcwScV2Generator.acwScV2Simple(arg1);
// URL 中动态提取域名 lanzoum.com, lanzoux.com
String domain = ".lanzn.com"; // 默认兜底
@@ -247,7 +175,7 @@ public class LzTool extends PanBase {
if (firstDot >= 0) {
domain = host.substring(firstDot); // e.g. ".lanzoum.com"
}
} catch (MalformedURLException ignored) {}
} catch (Exception ignored) {}
// 创建一个 Cookie 并放入 CookieStore
DefaultCookie nettyCookie = new DefaultCookie("acw_sc__v2", acw_sc__v2);
nettyCookie.setDomain(domain);
@@ -255,7 +183,6 @@ public class LzTool extends PanBase {
nettyCookie.setSecure(false);
nettyCookie.setHttpOnly(false);
webClientSession.cookieStore().put(nettyCookie);
return true;
}
private String getJsByPwd(String pwd, String html, String subText) {
@@ -273,9 +200,6 @@ public class LzTool extends PanBase {
}
private String getJsText(String html) {
if (html == null) {
return null;
}
String jsTagStart = "<script type=\"text/javascript\">";
String jsTagEnd = "</script>";
int index = html.lastIndexOf(jsTagStart);
@@ -284,52 +208,23 @@ public class LzTool extends PanBase {
}
int startPos = index + jsTagStart.length();
int endPos = html.indexOf(jsTagEnd, startPos);
if (endPos <= startPos) {
return null;
}
return html.substring(startPos, endPos).replaceAll("<!--.*-->", "");
}
static String extractAcwArg1(String html) {
if (html == null) {
return null;
}
int beginIndex = html.indexOf("arg1='");
if (beginIndex < 0) {
return null;
}
beginIndex += 6;
int endIndex = html.indexOf("';", beginIndex);
if (endIndex <= beginIndex) {
return null;
}
return html.substring(beginIndex, endIndex);
}
static boolean isShareCancelledPage(String html) {
return html != null
&& ((html.contains("来晚啦") && html.contains("取消分享"))
|| (html.contains("class=\"off\"") && html.contains("取消分享")));
}
private static boolean hasAcwArg1(String html) {
return html != null && html.contains("var arg1='");
}
private void getDownURL(String key, Map<String, ?> obj) {
if (obj == null) {
fail("需要访问密码");
return;
}
Map<?, ?> signMap = (Map<?, ?>)obj.get("data");
String url0 = String.valueOf(obj.get("url"));
String url0 = obj.get("url").toString();
MultiMap map = MultiMap.caseInsensitiveMultiMap();
signMap.forEach((k, v) -> {
map.add((String) k, v.toString());
});
MultiMap headers = HeaderUtils.parseHeaders("""
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Encoding: gzip, deflate, br
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
Cache-Control: no-cache
Connection: keep-alive
@@ -365,57 +260,42 @@ public class LzTool extends PanBase {
headers.remove("Referer");
webClientSession.getAbs(downUrl).putHeaders(headers).send()
.onSuccess(res3 -> {
try {
String location = res3.headers().get("Location");
if (location == null) {
String text = asText(res3);
if (isShareCancelledPage(text)) {
fail(downUrl + " -> 分享已失效或文件已取消分享");
return;
}
// 使用cookie 再请求一次
headers.add("Referer", downUrl);
String arg1 = extractAcwArg1(text);
if (arg1 == null) {
fail(downUrl + " -> 蓝奏云反爬 arg1 Cookie 解析失败,可能分享已失效");
return;
}
String acw_sc__v2 = AcwScV2Generator.acwScV2Simple(arg1);
// downUrl 中动态提取域名
String downDomain = ".lanrar.com";
try {
java.net.URL du = new java.net.URL(downUrl);
String h = du.getHost();
int dot = h.indexOf('.');
if (dot >= 0) downDomain = h.substring(dot);
} catch (MalformedURLException ignored) {}
// 创建一个 Cookie 并放入 CookieStore
DefaultCookie nettyCookie = new DefaultCookie("acw_sc__v2", acw_sc__v2);
nettyCookie.setDomain(downDomain);
nettyCookie.setPath("/");
nettyCookie.setSecure(false);
nettyCookie.setHttpOnly(false);
WebClientSession webClientSession2 = WebClientSession.create(clientNoRedirects);
webClientSession2.cookieStore().put(nettyCookie);
webClientSession2.getAbs(downUrl).putHeaders(headers).send()
.onSuccess(res4 -> {
try {
String location0 = res4.headers().get("Location");
if (location0 == null) {
fail(downUrl + " -> 直链获取失败2, 可能分享已失效");
} else {
setDateAndComplete(location0);
}
} catch (Exception e) {
fail("蓝奏云直链二次响应处理异常: {}", e.getMessage());
}
}).onFailure(handleFail(downUrl));
return;
}
setDateAndComplete(location);
} catch (Exception e) {
fail("蓝奏云直链响应处理异常: {}", e.getMessage());
String location = res3.headers().get("Location");
if (location == null) {
String text = asText(res3);
// 使用cookie 再请求一次
headers.add("Referer", downUrl);
int beginIndex = text.indexOf("arg1='") + 6;
String arg1 = text.substring(beginIndex, text.indexOf("';", beginIndex));
String acw_sc__v2 = AcwScV2Generator.acwScV2Simple(arg1);
// downUrl 中动态提取域名
String downDomain = ".lanrar.com";
try {
java.net.URL du = new java.net.URL(downUrl);
String h = du.getHost();
int dot = h.indexOf('.');
if (dot >= 0) downDomain = h.substring(dot);
} catch (Exception ignored) {}
// 创建一个 Cookie 并放入 CookieStore
DefaultCookie nettyCookie = new DefaultCookie("acw_sc__v2", acw_sc__v2);
nettyCookie.setDomain(downDomain);
nettyCookie.setPath("/");
nettyCookie.setSecure(false);
nettyCookie.setHttpOnly(false);
WebClientSession webClientSession2 = WebClientSession.create(clientNoRedirects);
webClientSession2.cookieStore().put(nettyCookie);
webClientSession2.getAbs(downUrl).putHeaders(headers).send()
.onSuccess(res4 -> {
String location0 = res4.headers().get("Location");
if (location0 == null) {
fail(downUrl + " -> 直链获取失败2, 可能分享已失效");
} else {
setDateAndComplate(location0);
}
}).onFailure(handleFail(downUrl));
return;
}
setDateAndComplate(location);
})
.onFailure(handleFail(downUrl));
} catch (Exception e) {
@@ -424,11 +304,12 @@ public class LzTool extends PanBase {
}).onFailure(handleFail(url));
}
private void setDateAndComplete(String location0) {
private void setDateAndComplate(String location0) {
// 分享时间 提取url中的时间戳格式lanzoui.com/abc/abc/yyyy/mm/dd/
Matcher matcher = URL_DATE_PATTERN.matcher(location0);
String regex = "(\\d{4}/\\d{1,2}/\\d{1,2})";
Matcher matcher = Pattern.compile(regex).matcher(location0);
if (matcher.find()) {
String dateStr = parseLanzouFileTime(matcher.group());
String dateStr = matcher.group().replace("/", "-");
((FileInfo)shareLinkInfo.getOtherParam().get("fileInfo")).setCreateTime(dateStr);
}
promise.complete(location0);
@@ -456,45 +337,26 @@ public class LzTool extends PanBase {
String pwd = shareLinkInfo.getSharePassword();
webClientSession.getAbs(sUrl).send().onSuccess(res -> {
try {
String html = asText(res);
// 检查是否需要 cookie 验证
if (hasAcwArg1(html)) {
webClientSession = WebClientSession.create(clientNoRedirects);
if (!setCookie(html, sUrl)) {
promise.tryFail(baseMsg() + "蓝奏云反爬 arg1 Cookie 解析失败,页面内容异常");
return;
}
// 重新请求
webClientSession.getAbs(sUrl).send().onSuccess(res2 -> {
try {
handleFileListParse(asText(res2), pwd, sUrl, promise);
} catch (Exception e) {
promise.tryFail(e);
}
}).onFailure(promise::tryFail);
return;
}
handleFileListParse(html, pwd, sUrl, promise);
} catch (Exception e) {
promise.tryFail(e);
String html = asText(res);
// 检查是否需要 cookie 验证
if (html.contains("var arg1='")) {
webClientSession = WebClientSession.create(clientNoRedirects);
setCookie(html, sUrl);
// 重新请求
webClientSession.getAbs(sUrl).send().onSuccess(res2 -> {
handleFileListParse(asText(res2), pwd, sUrl, promise);
}).onFailure(err -> promise.fail(err));
return;
}
}).onFailure(promise::tryFail);
handleFileListParse(html, pwd, sUrl, promise);
}).onFailure(err -> promise.fail(err));
return promise.future();
}
private void handleFileListParse(String html, String pwd, String sUrl, Promise<List<FileInfo>> promise) {
if (html == null || html.isBlank()) {
promise.tryFail(baseMsg() + "蓝奏云页面响应为空");
return;
}
if (isShareCancelledPage(html)) {
promise.tryFail(baseMsg() + "分享已失效或文件已取消分享");
return;
}
// 检测是否为文件分享链接 (不含 /s//b/ 路径段且不含 b 开头的路径段)
if (!sUrl.matches(".*/(s|b)/[^/]+.*") && !sUrl.matches(".*/b[^/]+.*")) {
promise.tryFail(baseMsg() + "该链接为蓝奏云文件分享,请使用文件解析接口");
// 检测是否为文件分享链接 (不含 /s//b/ 路径段且不含 b0 开头的路径段)
if (!sUrl.matches(".*/(s|b)/[^/]+.*") && !sUrl.matches(".*/b0[^/]+.*")) {
promise.fail(baseMsg() + "该链接为蓝奏云文件分享,请使用文件解析接口");
return;
}
try {
@@ -508,43 +370,28 @@ public class LzTool extends PanBase {
String url = SHARE_URL_PREFIX + "filemoreajax.php?file=" + data.get("fid");
webClientSession.postAbs(url).putHeaders(headers).sendForm(map).onSuccess(res2 -> {
try {
String resBody = asText(res2);
// 再次检查是否需要 cookie 验证
if (hasAcwArg1(resBody)) {
if (!setCookie(resBody, url)) {
promise.tryFail(baseMsg() + "蓝奏云反爬 arg1 Cookie 解析失败,页面内容异常");
return;
}
// 重新请求
webClientSession.postAbs(url).putHeaders(headers).sendForm(map).onSuccess(res3 -> {
try {
handleFileListResponse(asText(res3), promise);
} catch (Exception e) {
promise.tryFail(e);
}
}).onFailure(promise::tryFail);
return;
}
handleFileListResponse(resBody, promise);
} catch (Exception e) {
promise.tryFail(e);
String resBody = asText(res2);
// 再次检查是否需要 cookie 验证
if (resBody.contains("var arg1='")) {
setCookie(resBody, url);
// 重新请求
webClientSession.postAbs(url).putHeaders(headers).sendForm(map).onSuccess(res3 -> {
handleFileListResponse(asText(res3), promise);
}).onFailure(err -> promise.fail(err));
return;
}
}).onFailure(promise::tryFail);
handleFileListResponse(resBody, promise);
}).onFailure(err -> promise.fail(err));
} catch (ScriptException | NoSuchMethodException | RuntimeException e) {
promise.tryFail(e);
promise.fail(e);
}
}
private void handleFileListResponse(String responseBody, Promise<List<FileInfo>> promise) {
try {
if (responseBody == null || responseBody.isBlank()) {
promise.tryFail(baseMsg() + "蓝奏云文件列表响应为空");
return;
}
JsonObject fileListJson = new JsonObject(responseBody);
if (fileListJson.getInteger("zt") != 1) {
promise.tryFail(baseMsg() + fileListJson.getString("info"));
promise.fail(baseMsg() + fileListJson.getString("info"));
return;
}
List<FileInfo> list = new ArrayList<>();
@@ -575,7 +422,7 @@ public class LzTool extends PanBase {
String param = CommonUtils.urlBase64Encode(paramJson.encode());
fileInfo.setFileName(fileName)
.setFileId(id)
.setCreateTime(parseLanzouFileTime(fileJson.getString("time")))
.setCreateTime(fileJson.getString("time"))
.setFileType(fileJson.getString("icon"))
.setSizeStr(fileJson.getString("size"))
.setSize(sizeNum)
@@ -588,46 +435,10 @@ public class LzTool extends PanBase {
});
promise.complete(list);
} catch (Exception e) {
promise.tryFail(e);
promise.fail(e);
}
}
private static String parseLanzouFileTime(String timeText) {
if (timeText == null || timeText.isBlank()) {
return timeText;
}
String normalized = timeText.trim().replaceAll("\\s+", " ");
Matcher matcher = RELATIVE_TIME_PATTERN.matcher(normalized);
if (matcher.matches()) {
int amount = "".equals(matcher.group(1)) ? 1 : Integer.parseInt(matcher.group(1));
String unit = matcher.group(2);
LocalDateTime time = LocalDateTime.now();
if ("小时".equals(unit)) {
time = time.minusHours(amount);
} else {
time = time.minusMinutes(amount);
}
return time.toLocalDate().toString();
}
matcher = DATE_PATTERN.matcher(normalized);
if (matcher.matches()) {
return LocalDate.of(
Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
Integer.parseInt(matcher.group(3))
).toString();
}
matcher = MONTH_DAY_PATTERN.matcher(normalized);
if (matcher.matches()) {
return LocalDate.of(
LocalDate.now().getYear(),
Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2))
).toString();
}
return normalized;
}
@Override
public Future<String> parseById() {
JsonObject paramJson = (JsonObject) shareLinkInfo.getOtherParam().get("paramJson");
@@ -643,13 +454,13 @@ public class LzTool extends PanBase {
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
try {
// 提取文件名
String fileName = CommonUtils.extract(html, FILE_NAME_PATTERN);
String sizeStr = CommonUtils.extract(html, FILE_SIZE_PATTERN);
String createBy = CommonUtils.extract(html, SHARE_USER_PATTERN);
String description = CommonUtils.extract(html, DESCRIPTION_PATTERN);
String fileName = CommonUtils.extract(html, Pattern.compile("padding: 56px 0px 20px 0px;\">(.*?)<|filenajax\">(.*?)<"));
String sizeStr = CommonUtils.extract(html, Pattern.compile(">文件大小:</span>(.*?)<br>|\"n_filesize\">大小:(.*?)</div>"));
String createBy = CommonUtils.extract(html, Pattern.compile(">分享用户:</span><font>(.*?)</font>|获取<span>(.*?)</span>的文件|\"user-name\">(.*?)</"));
String description = CommonUtils.extract(html, Pattern.compile("(?s)文件描述:</span><br>(.*?)</td>|class=\"n_box_des\">(.*?)</div>"));
// String icon = CommonUtils.extract(html, Pattern.compile("class=\"n_file_icon\" src=\"(.*?)\""));
String fileId = CommonUtils.extract(html, FILE_ID_PATTERN);
String createTime = CommonUtils.extract(html, CREATE_TIME_PATTERN);
String fileId = CommonUtils.extract(html, Pattern.compile("\\?f=(.*?)&|fid = (.*?);"));
String createTime = CommonUtils.extract(html, Pattern.compile(">上传时间:</span>(.*?)<"));
try {
fileInfo.setFileName(fileName)
.setCreateBy(createBy)
@@ -657,7 +468,7 @@ public class LzTool extends PanBase {
.setDescription(description)
.setFileType("file")
.setFileId(fileId)
.setCreateTime(parseLanzouFileTime(createTime));
.setCreateTime(createTime);
if (sizeStr != null && !sizeStr.isBlank()) {
long bytes = FileSizeConverter.convertToBytes(sizeStr);
fileInfo.setSize(bytes).setSizeStr(FileSizeConverter.convertToReadableSize(bytes));
@@ -21,8 +21,6 @@ public class MkgsTool extends PanBase {
public static final String API_URL = "https://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash={hash}";
private static final Pattern HASH_PATTERN = Pattern.compile("\"hash\"\\s*:\\s*\"([A-F0-9]+)\"");
private static final MultiMap headers = MultiMap.caseInsensitiveMultiMap();
static {
// 设置 User-Agent
@@ -80,15 +78,18 @@ public class MkgsTool extends PanBase {
protected void downUrl(String locationURL) {
client.getAbs(locationURL).putHeaders(headers).send().onSuccess(res2->{
String body = res2.bodyAsString();
Matcher matcher = HASH_PATTERN.matcher(body);
// 正则表达式匹配 hash 字段
String regex = "\"hash\"\s*:\s*\"([A-F0-9]+)\"";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(body);
// 查找并输出 hash 字段的值
if (matcher.find()) {
String hashValue = matcher.group(1); // 获取第一个捕获组
log.debug("hash: {}", hashValue);
System.out.println(hashValue);
client.getAbs(UriTemplate.of(API_URL)).setTemplateParam("hash", hashValue).send().onSuccess(res3 -> {
JsonObject jsonObject = asJson(res3);
log.debug("API response: {}", jsonObject.encodePrettily());
System.out.println(jsonObject.encodePrettily());
if (jsonObject.containsKey("url")) {
promise.complete(jsonObject.getString("url"));
} else {
@@ -19,8 +19,6 @@ public class MkwTool extends PanBase {
public static final String API_URL = "https://www.kuwo.cn/api/v1/www/music/playUrl?mid={mid}&type=music&httpsStatus=1&reqId=&plat=web_www&from=";
private static final Pattern COOKIE_PATTERN = Pattern.compile("([A-Za-z0-9_]+)=([A-Za-z0-9]+)");
public MkwTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
@@ -31,41 +29,39 @@ public class MkwTool extends PanBase {
clientSession.getAbs(shareUrl).send().onSuccess(result -> {
String cookie = result.headers().get("set-cookie");
if (cookie == null || cookie.isEmpty()) {
fail("未获取到 cookie,无法继续解析");
return;
if (!cookie.isEmpty()) {
String regex = "([A-Za-z0-9_]+)=([A-Za-z0-9]+)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(cookie);
if (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
var key = matcher.group(1);
var token = matcher.group(2);
String sign = JsExecUtils.getKwSign(token, key);
System.out.println(sign);
clientSession.getAbs(UriTemplate.of(API_URL)).setTemplateParam("mid", shareLinkInfo.getShareKey())
.putHeader("Secret", sign).send().onSuccess(res -> {
JsonObject json = asJson(res);
log.debug(json.encodePrettily());
try {
if (json.getInteger("code") == 200) {
complete(json.getJsonObject("data").getString("url"));
} else {
fail("链接已失效/需要VIP");
}
} catch (Exception e) {
e.printStackTrace();
fail("解析失败");
}
});
}
}
Matcher matcher = COOKIE_PATTERN.matcher(cookie);
if (!matcher.find()) {
fail("cookie 格式不匹配");
return;
}
log.debug("cookie key: {}", matcher.group(1));
log.debug("cookie value: {}", matcher.group(2));
var key = matcher.group(1);
var token = matcher.group(2);
String sign = JsExecUtils.getKwSign(token, key);
log.debug("sign: {}", sign);
clientSession.getAbs(UriTemplate.of(API_URL)).setTemplateParam("mid", shareLinkInfo.getShareKey())
.putHeader("Secret", sign).send().onSuccess(res -> {
JsonObject json = asJson(res);
log.debug(json.encodePrettily());
try {
if (json.getInteger("code") == 200) {
complete(json.getJsonObject("data").getString("url"));
} else {
fail("链接已失效/需要VIP");
}
} catch (Exception e) {
log.error("解析失败", e);
fail("解析失败");
}
}).onFailure(handleFail("获取下载链接失败"));
}).onFailure(handleFail("请求分享页面失败"));
});
return promise.future();
}
@@ -21,8 +21,6 @@ public class P115Tool extends PanBase {
private static final String SECOND_REQUEST_URL = API_URL_PREFIX + "share/skip_login_downurl";
private static final String DEFAULT_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
private static final MultiMap header;
static {
@@ -51,11 +49,9 @@ public class P115Tool extends PanBase {
public Future<String> parse() {
// 第一次请求 获取文件信息
Object uaObj = shareLinkInfo.getOtherParam().get("UA");
String ua = uaObj != null ? uaObj.toString() : DEFAULT_UA;
client.getAbs(UriTemplate.of(FIRST_REQUEST_URL))
.putHeaders(header)
.putHeader("User-Agent", ua)
.putHeader("User-Agent", shareLinkInfo.getOtherParam().get("UA").toString())
.setTemplateParam("dataKey", shareLinkInfo.getShareKey())
.setTemplateParam("dataPwd", shareLinkInfo.getSharePassword())
.send().onSuccess(res -> {
@@ -72,7 +68,7 @@ public class P115Tool extends PanBase {
// share_code={dataKey}&receive_code={dataPwd}&file_id={file_id}
client.postAbs(SECOND_REQUEST_URL)
.putHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
.putHeader("User-Agent", ua)
.putHeader("User-Agent", shareLinkInfo.getOtherParam().get("UA").toString())
.sendForm(MultiMap.caseInsensitiveMultiMap()
.set("share_code", shareLinkInfo.getShareKey())
.set("receive_code", shareLinkInfo.getSharePassword())
@@ -16,9 +16,6 @@ import java.util.regex.Pattern;
* 下载链接需要Referer: https://link.yunpan.com/
*/
public class P360Tool extends PanBase {
private static final Pattern NID_PATTERN = Pattern.compile("\"nid\": \"([^\"]+)\"");
public P360Tool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
}
@@ -46,7 +43,9 @@ public class P360Tool extends PanBase {
clientSession.getAbs(url)
.send()
.onSuccess(res -> {
Matcher matcher = NID_PATTERN.matcher(res.bodyAsString());
// find "nid": "17402043311959599"
Pattern compile = Pattern.compile("\"nid\": \"([^\"]+)\"");
Matcher matcher = compile.matcher(res.bodyAsString());
AtomicReference<String> nid = new AtomicReference<>();
if (matcher.find()) {
nid.set(matcher.group(1));
@@ -70,7 +69,7 @@ public class P360Tool extends PanBase {
clientSession.getAbs(url)
.send()
.onSuccess(res3 -> {
Matcher matcher1 = NID_PATTERN.matcher(res3.bodyAsString());
Matcher matcher1 = compile.matcher(res3.bodyAsString());
if (matcher1.find()) {
nid.set(matcher1.group(1));
} else {
@@ -14,25 +14,6 @@ import java.util.regex.Pattern;
*/
public class PcxTool extends PanBase {
private static final Pattern TITLE_PATTERN =
Pattern.compile("<title>([^<]+)</title>");
private static final Pattern FILENAME_INPUT_PATTERN =
Pattern.compile("<input id=\"filename\" type=\"hidden\" value=\"([^\"]+)\"");
private static final Pattern FILESIZE_PATTERN =
Pattern.compile("['\"]filesize['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
private static final Pattern SUFFIX_PATTERN =
Pattern.compile("['\"]suffix['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
private static final Pattern OBJECT_ID_PATTERN =
Pattern.compile("['\"]objectId['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
private static final Pattern CREATOR_PATTERN =
Pattern.compile("['\"]creator['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
private static final Pattern UPLOAD_DATE_PATTERN =
Pattern.compile("['\"]uploadDate['\"]\\s*:\\s*(\\d+)");
private static final Pattern THUMBNAIL_PATTERN =
Pattern.compile("['\"]thumbnail['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
private static final Pattern DOWNLOAD_PATTERN =
Pattern.compile("['\"]download['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
public PcxTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
}
@@ -63,7 +44,9 @@ public class PcxTool extends PanBase {
* 从HTML中提取download链接
*/
private String extractDownloadUrl(String html) {
Matcher matcher = DOWNLOAD_PATTERN.matcher(html);
// 匹配 'download': 'https://xxx' "download": "https://xxx"
Pattern pattern = Pattern.compile("['\"]download['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
Matcher matcher = pattern.matcher(html);
if (matcher.find()) {
return matcher.group(1);
}
@@ -78,13 +61,13 @@ public class PcxTool extends PanBase {
FileInfo fileInfo = new FileInfo();
// 提取文件名<title>标签或文件名input
String fileName = extractByRegex(html, TITLE_PATTERN);
String fileName = extractByRegex(html, "<title>([^<]+)</title>");
if (fileName == null) {
fileName = extractByRegex(html, FILENAME_INPUT_PATTERN);
fileName = extractByRegex(html, "<input id=\"filename\" type=\"hidden\" value=\"([^\"]+)\"");
}
// 提取文件大小'filesize': 'xxx' "filesize": "xxx"
String fileSizeStr = extractByRegex(html, FILESIZE_PATTERN);
String fileSizeStr = extractByRegex(html, "['\"]filesize['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
Long fileSize = null;
if (fileSizeStr != null) {
try {
@@ -93,19 +76,19 @@ public class PcxTool extends PanBase {
}
// 提取文件类型/后缀'suffix': 'xxx' "suffix": "xxx"
String suffix = extractByRegex(html, SUFFIX_PATTERN);
String suffix = extractByRegex(html, "['\"]suffix['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
// 提取objectId文件ID'objectId': 'xxx' "objectId": "xxx"
String objectId = extractByRegex(html, OBJECT_ID_PATTERN);
String objectId = extractByRegex(html, "['\"]objectId['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
// 提取创建者'creator': 'xxx' "creator": "xxx"
String creator = extractByRegex(html, CREATOR_PATTERN);
String creator = extractByRegex(html, "['\"]creator['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
// 提取上传时间'uploadDate': timestamp
String uploadDate = extractByRegex(html, UPLOAD_DATE_PATTERN);
String uploadDate = extractByRegex(html, "['\"]uploadDate['\"]\\s*:\\s*(\\d+)");
// 提取缩略图'thumbnail': 'xxx' "thumbnail": "xxx"
String thumbnail = extractByRegex(html, THUMBNAIL_PATTERN);
String thumbnail = extractByRegex(html, "['\"]thumbnail['\"]\\s*:\\s*['\"]([^'\"]+)['\"]");
// 设置文件信息
if (fileName != null) {
@@ -158,7 +141,8 @@ public class PcxTool extends PanBase {
/**
* 使用正则表达式提取内容
*/
private String extractByRegex(String text, Pattern pattern) {
private String extractByRegex(String text, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
return matcher.group(1);
@@ -28,7 +28,6 @@ public class PdbTool extends PanBase implements IPanTool {
private static final String API_URL =
"https://www.dropbox.com/sharing/fetch_user_content_link";
static final String COOKIE_KEY = "__Host-js_csrf=";
private static final Pattern CSRF_TOKEN_PATTERN = Pattern.compile(COOKIE_KEY + "([\\w-]+);");
public PdbTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
@@ -48,7 +47,7 @@ public class PdbTool extends PanBase implements IPanTool {
fail("cookie未找到");
return;
}
Matcher matcher = CSRF_TOKEN_PATTERN.matcher(collect.get(0));
Matcher matcher = Pattern.compile(COOKIE_KEY + "([\\w-]+);").matcher(collect.get(0));
String _t;
if (matcher.find()) {
_t = matcher.group(1);
@@ -86,7 +85,7 @@ public class PdbTool extends PanBase implements IPanTool {
})
.onFailure(handleFail());
} catch (Exception e) {
log.error("URL编码异常", e);
e.printStackTrace();
}
})
@@ -23,16 +23,6 @@ import java.util.regex.Pattern;
*/
public class PodTool extends PanBase {
private static final int MAX_RESPONSE_BODY_BYTES = 8 * 1024 * 1024;
private static final java.time.Duration REQUEST_TIMEOUT = java.time.Duration.ofSeconds(30);
// 静态共享的 JDK HttpClient 实例避免每次调用创建新实例
private static final HttpClient SHARED_HTTP_CLIENT = HttpClient.newBuilder()
.connectTimeout(java.time.Duration.ofSeconds(10))
.build();
private static volatile WorkerExecutor SHARED_WORKER_EXECUTOR;
private static volatile boolean workerExecutorShutdown = false;
/*
* https://1drv.ms/w/s!Alg0feQmCv2rnRFd60DQOmMa-Oh_?e=buaRtp --302->
* https://api.onedrive.com/v1.0/drives/abfd0a26e47d3458/items/ABFD0A26E47D3458!3729?authkey=!AF3rQNA6Yxr46H8
@@ -55,13 +45,6 @@ public class PodTool extends PanBase {
private static final Pattern redirectUrlRegex =
Pattern.compile("resid=(?<cid1>[^!]+)!(?<cid2>[^&]+).+&redeem=(?<redeem>.+).*");
private static final Pattern DOWNLOAD_URL_IN_RESPONSE_PATTERN =
Pattern.compile("\"downloadUrl\":\"(?<url>https?://[^\\s\"]+)");
private static final Pattern ACTION_URL_PATTERN =
Pattern.compile("'action'.+(?<url>https://.+)'\\)");
private static final Pattern TOKEN_PATTERN =
Pattern.compile("inputElem\\.value\\s*=\\s*'([^']+)'");
public PodTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
}
@@ -114,7 +97,7 @@ public class PodTool extends PanBase {
sendHttpRequest(url, token).onSuccess(body -> {
Matcher matcher1 =
DOWNLOAD_URL_IN_RESPONSE_PATTERN.matcher(body);
Pattern.compile("\"downloadUrl\":\"(?<url>https?://[^\s\"]+)").matcher(body);
if (matcher1.find()) {
// 响应体是 JSON 文本URL 中的 '&' 被转义为 \u0026需要反转义
complete(unescapeJsonUnicode(matcher1.group("url")));
@@ -138,11 +121,15 @@ public class PodTool extends PanBase {
}
private String matcherUrl(String html) {
Matcher urlMatcher = ACTION_URL_PATTERN.matcher(html);
// 正则表达式来匹配 URL
String urlRegex = "'action'.+(?<url>https://.+)'\\)";
Pattern urlPattern = Pattern.compile(urlRegex);
Matcher urlMatcher = urlPattern.matcher(html);
if (urlMatcher.find()) {
String url = urlMatcher.group("url");
log.debug("URL: {}", url);
System.out.println("URL: " + url);
return url;
}
throw new RuntimeException("URL匹配失败");
@@ -178,11 +165,14 @@ public class PodTool extends PanBase {
private String matcherToken(String html) {
Matcher tokenMatcher = TOKEN_PATTERN.matcher(html);
// 正则表达式来匹配 inputElem.value 中的 Token
String tokenRegex = "inputElem\\.value\\s*=\\s*'([^']+)'";
Pattern tokenPattern = Pattern.compile(tokenRegex);
Matcher tokenMatcher = tokenPattern.matcher(html);
if (tokenMatcher.find()) {
String token = tokenMatcher.group(1);
log.debug("Token: {}***", token.length() > 4 ? token.substring(0, 4) : "***");
System.out.println("Token: " + token);
return token;
}
throw new RuntimeException("token匹配失败");
@@ -190,8 +180,11 @@ public class PodTool extends PanBase {
public Future<String> sendHttpRequest2(String token, String redeem) {
Promise<String> promise = Promise.promise();
// 构造 HttpClient
HttpClient client = HttpClient.newHttpClient();
// 构造请求的 URI 和头部信息
// https://onedrive.live.com/redir?cid=abfd0a26e47d3458&resid=ABFD0A26E47D3458!4465&ithint=file%2cxlsx&e=Ao2uSU&migratedtospo=true&redeem=aHR0cHM6Ly8xZHJ2Lm1zL3gvYy9hYmZkMGEyNmU0N2QzNDU4L0VWZzBmZVFtQ3YwZ2dLdHhFUUFBQUFBQlRQRWVDMTZfZk1EYk5FTjhEdTRta1E_ZT1BbzJ1U1U
String url = ("https://my.microsoftpersonalcontent.com/_api/v2.0/shares/u!%s/driveItem?$select=content" +
".downloadUrl").formatted(redeem);
String authorizationHeader = "Badger " + token;
@@ -199,20 +192,15 @@ public class PodTool extends PanBase {
// 构建请求
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(REQUEST_TIMEOUT)
.header("Authorization", authorizationHeader)
.build();
// 发送请求并处理响应使用共享的 HttpClient
SHARED_HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofByteArray())
// 发送请求并处理响应
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
log.debug("Response Status Code: {}", response.statusCode());
promise.complete(toLimitedString(response.body()));
return null;
})
.exceptionally(e -> {
log.error("sendHttpRequest2 请求失败: {}", e.getMessage());
promise.fail(e);
System.out.println("Response Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
promise.complete(response.body());
return null;
});
@@ -220,13 +208,18 @@ public class PodTool extends PanBase {
}
public Future<String> sendHttpRequest(String url, String token) {
// 创建一个 WorkerExecutor 用于异步执行阻塞的 HTTP 请求
WorkerExecutor executor = WebClientVertxInit.get().createSharedWorkerExecutor("http-client-worker");
Promise<String> promise = Promise.promise();
getWorkerExecutor().executeBlocking(() -> {
executor.executeBlocking(() -> {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = null;
try {
// 构造请求
HttpRequest request = HttpRequest.newBuilder()
request = HttpRequest.newBuilder()
.uri(new URI(url))
.timeout(REQUEST_TIMEOUT)
.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9," +
"image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;" +
"v=b3;q=0.7")
@@ -251,49 +244,17 @@ public class PodTool extends PanBase {
.POST(HttpRequest.BodyPublishers.ofString("badger_token=" + token))
.build();
// 发起请求并获取响应使用共享的 HttpClient
HttpResponse<byte[]> response = SHARED_HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofByteArray());
// 发起请求并获取响应
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// 返回响应体
promise.complete(toLimitedString(response.body()));
promise.complete(response.body());
return null;
} catch (URISyntaxException | IOException | InterruptedException e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw new RuntimeException(e);
}
}).onFailure(promise::fail);
});
return promise.future();
}
private static String toLimitedString(byte[] body) {
if (body.length > MAX_RESPONSE_BODY_BYTES) {
throw new IllegalArgumentException("OneDrive响应体过大: " + body.length + " bytes");
}
return new String(body, java.nio.charset.StandardCharsets.UTF_8);
}
private static WorkerExecutor getWorkerExecutor() {
synchronized (PodTool.class) {
if (workerExecutorShutdown) {
throw new IllegalStateException("OneDrive WorkerExecutor 已关闭");
}
if (SHARED_WORKER_EXECUTOR == null) {
SHARED_WORKER_EXECUTOR = WebClientVertxInit.get().createSharedWorkerExecutor("http-client-worker", 8);
}
return SHARED_WORKER_EXECUTOR;
}
}
public static void shutdownWorkerExecutor() {
synchronized (PodTool.class) {
workerExecutorShutdown = true;
if (SHARED_WORKER_EXECUTOR != null) {
SHARED_WORKER_EXECUTOR.close();
SHARED_WORKER_EXECUTOR = null;
}
}
}
}
}
@@ -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;
@@ -10,6 +11,7 @@ import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.core.json.pointer.JsonPointer;
import io.vertx.ext.web.client.WebClient;
import io.vertx.uritemplate.UriTemplate;
import java.util.List;
@@ -51,8 +53,9 @@ public class PvyyTool extends PanBase {
@Override
public Future<String> parse() {
// 请求downcode - 使用父类的共享 WebClient 而非创建新实例
client.getAbs(api + shareLinkInfo.getShareKey())
// 请求downcode
WebClient.create(WebClientVertxInit.get())
.getAbs(api + shareLinkInfo.getShareKey())
.send()
.onSuccess(res -> {
if (res.statusCode() == 200) {
@@ -74,9 +74,9 @@ public class QQTool extends PanBase {
});
// 调试匹配的情况
log.debug("文件名称: {}", filename);
log.debug("文件大小: {}", filesize);
log.debug("文件直链: {}", fileurl);
System.out.println("文件名称: " + filename);
System.out.println("文件大小: " + filesize);
System.out.println("文件直链: " + fileurl);
// 提交
promise.complete(fileurl.replace("\\x26", "&"));
@@ -3,11 +3,9 @@ package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.PanBase;
import cn.qaiu.util.CommonUtils;
import cn.qaiu.util.HeaderUtils;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
@@ -15,33 +13,27 @@ import org.slf4j.LoggerFactory;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* QQ闪传 <br>
* 支持多文件多级目录解析通过 GetFileList API 获取文件列表BatchDownload API 获取下载直链<br>
* 有效期默认7天
* 只能客户端上传 支持Android QQ 9.2.5, MACOS QQ 6.9.78可生成分享链接通过浏览器下载支持超大文件有效期默认7天暂时没找到续期方法<br>
*/
public class QQscTool extends PanBase {
Logger LOG = LoggerFactory.getLogger(QQscTool.class);
private static final String BATCH_DOWNLOAD_API =
"https://qfile.qq.com/http2rpc/gotrpc/noauth/trpc.qqntv2.richmedia.InnerProxy/BatchDownload";
private static final String API_URL = "https://qfile.qq.com/http2rpc/gotrpc/noauth/trpc.qqntv2.richmedia.InnerProxy/BatchDownload";
private static final String GET_FILE_LIST_API =
"https://qfile.qq.com/http2rpc/gotrpc/noauth/trpc.file.FileFlashTrans/GetFileList";
private static final MultiMap BATCH_DOWNLOAD_HEADERS = HeaderUtils.parseHeaders("""
private static final MultiMap HEADERS = HeaderUtils.parseHeaders("""
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Connection: keep-alive
Cookie: uin=9000002; p_uin=9000002
DNT: 1
Origin: https://qfile.qq.com
Referer: https://qfile.qq.com/q/Xolxtv5b4O
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
@@ -54,262 +46,86 @@ public class QQscTool extends PanBase {
x-oidb: {"uint32_command":"0x9248", "uint32_service_type":"4"}
""");
private static final MultiMap GET_FILE_LIST_HEADERS = HeaderUtils.parseHeaders("""
Accept-Encoding: gzip, deflate
Cookie: uin=9000002; p_uin=9000002
Origin: https://qfile.qq.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0
content-type: application/json
x-oidb: {"uint32_command":"0x93d4", "uint32_service_type":"1"}
""");
private static final Pattern FILESET_ID_PATTERN = Pattern.compile(
"fileset_id[^a-f0-9]*([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})");
private static final Pattern TITLE_PATTERN = Pattern.compile("<title>(.*?)</title>");
public QQscTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
}
@Override
public Future<String> parse() {
String jsonTemplate = """
{"req_head":{"agent":8},"download_info":[{"batch_id":"%s","scene":{"business_type":4,"app_type":22,"scene_type":5},"index_node":{"file_uuid":"%s"},"url_type":2,"download_scene":0}],"scene_type":103}
""";
client.getAbs(shareLinkInfo.getShareUrl()).send(result -> {
if (result.failed()) {
if (result.succeeded()) {
String htmlJs = result.result().bodyAsString();
LOG.debug("获取到的HTML内容: {}", htmlJs);
String fileUUID = getFileUUID(htmlJs);
String fileName = extractFileNameFromTitle(htmlJs);
if (fileName != null) {
LOG.info("提取到的文件名: {}", fileName);
FileInfo fileInfo = new FileInfo();
fileInfo.setFileName(fileName);
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
} else {
LOG.warn("未能提取到文件名");
}
if (fileUUID != null) {
LOG.info("提取到的文件UUID: {}", fileUUID);
String formatted = jsonTemplate.formatted(fileUUID, fileUUID);
JsonObject entries = new JsonObject(formatted);
client.postAbs(API_URL)
.putHeaders(HEADERS)
.sendJsonObject(entries)
.onSuccess(result2 -> {
if (result2.statusCode() == 200) {
JsonObject body = asJson(result2);
LOG.debug("API响应内容: {}", body.encodePrettily());
// {
// "retcode": 0,
// "cost": 132,
// "message": "",
// "error": {
// "message": "",
// "code": 0
// },
// "data": {
// "download_rsp": [{
// download_rsp
if (!body.containsKey("retcode") || body.getInteger("retcode") != 0) {
promise.fail("API请求失败,错误信息: " + body.encodePrettily());
return;
}
JsonArray downloadRsp = body.getJsonObject("data").getJsonArray("download_rsp");
if (downloadRsp != null && !downloadRsp.isEmpty()) {
String url = downloadRsp.getJsonObject(0).getString("url");
if (fileName != null) {
url = url + "&filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8);
}
promise.complete(url);
} else {
promise.fail("API响应中缺少 download_rsp");
}
} else {
promise.fail("API请求失败,状态码: " + result2.statusCode());
}
}).onFailure(e -> {
LOG.error("API请求异常", e);
promise.fail(e);
});
} else {
LOG.error("未能提取到文件UUID");
promise.fail("未能提取到文件UUID");
}
} else {
LOG.error("请求失败: {}", result.cause().getMessage());
promise.fail(result.cause());
return;
}
String html = result.result().bodyAsString();
String fileName = extractFileNameFromTitle(html);
if (fileName != null) {
FileInfo fileInfo = new FileInfo();
fileInfo.setFileName(fileName);
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
}
// 尝试用 GetFileList API 获取第一个文件的下载链接
String filesetId = extractFilesetId(html);
if (filesetId != null) {
fetchFileList(filesetId, "").onSuccess(fileList -> {
for (int i = 0; i < fileList.size(); i++) {
JsonObject file = fileList.getJsonObject(i);
if (!file.getBoolean("is_dir", false)) {
String physicalId = file.getJsonObject("physical").getString("id");
String name = file.getString("name");
downloadFile(physicalId, name);
return;
}
}
promise.fail("未找到可下载的文件");
}).onFailure(e -> {
LOG.warn("GetFileList 失败,回退到旧解析方式: {}", e.getMessage());
parseLegacy(html, fileName);
});
} else {
parseLegacy(html, fileName);
}
});
return promise.future();
}
@Override
public Future<List<FileInfo>> parseFileList() {
Promise<List<FileInfo>> resultPromise = Promise.promise();
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
client.getAbs(shareLinkInfo.getShareUrl()).send(result -> {
if (result.failed()) {
resultPromise.fail(result.cause());
return;
}
String html = result.result().bodyAsString();
String filesetId = extractFilesetId(html);
if (filesetId == null) {
resultPromise.fail("无法从页面提取 filesetId");
return;
}
String parentId = dirId != null ? dirId : "";
fetchFileList(filesetId, parentId).onSuccess(fileList -> {
try {
List<FileInfo> list = new ArrayList<>();
String panType = shareLinkInfo.getType();
for (int i = 0; i < fileList.size(); i++) {
JsonObject file = fileList.getJsonObject(i);
FileInfo fileInfo = new FileInfo();
String name = file.getString("name");
String cliFileid = file.getString("cli_fileid");
boolean isDir = file.getBoolean("is_dir", false);
String sizeStr = file.getString("file_size");
fileInfo.setFileName(name)
.setFileId(cliFileid)
.setPanType(panType)
.setSizeStr(sizeStr);
if (isDir) {
fileInfo.setFileType("folder")
.setParserUrl(String.format("%s/v2/getFileList?url=%s&dirId=%s",
getDomainName(),
URLEncoder.encode(shareLinkInfo.getShareUrl(), StandardCharsets.UTF_8),
cliFileid));
} else {
String physicalId = file.getJsonObject("physical").getString("id");
JsonObject paramJson = new JsonObject()
.put("fileId", physicalId)
.put("fileName", name)
.put("cliFileid", cliFileid);
String param = CommonUtils.urlBase64Encode(paramJson.encode());
fileInfo.setFileType("file")
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
getDomainName(), panType, param));
}
list.add(fileInfo);
}
resultPromise.complete(list);
} catch (Exception e) {
resultPromise.fail(e);
}
}).onFailure(resultPromise::fail);
});
return resultPromise.future();
}
@Override
public Future<String> parseById() {
JsonObject paramJson = (JsonObject) shareLinkInfo.getOtherParam().get("paramJson");
String fileId = paramJson.getString("fileId");
String fileName = paramJson.getString("fileName");
Promise<String> p = Promise.promise();
callBatchDownload(fileId, fileName, p);
return p.future();
}
// ========== 内部方法 ==========
/**
* 调用 BatchDownload API 获取单个文件的下载直链
*/
private void downloadFile(String physicalId, String fileName) {
callBatchDownload(physicalId, fileName, promise);
}
private void callBatchDownload(String physicalId, String fileName, Promise<String> p) {
String body = """
{"req_head":{"agent":8},"download_info":[{"batch_id":"%s","scene":{"business_type":4,"app_type":22,"scene_type":5},"index_node":{"file_uuid":"%s"},"url_type":2,"download_scene":0}],"scene_type":103}
""".formatted(physicalId, physicalId);
client.postAbs(BATCH_DOWNLOAD_API)
.putHeaders(BATCH_DOWNLOAD_HEADERS)
.sendJsonObject(new JsonObject(body))
.onSuccess(resp -> {
if (resp.statusCode() != 200) {
p.fail("BatchDownload 请求失败,状态码: " + resp.statusCode());
return;
}
JsonObject respBody = asJson(resp);
if (!respBody.containsKey("retcode") || respBody.getInteger("retcode") != 0) {
p.fail("BatchDownload 请求失败: " + respBody.encodePrettily());
return;
}
JsonArray downloadRsp = respBody.getJsonObject("data").getJsonArray("download_rsp");
if (downloadRsp == null || downloadRsp.isEmpty()) {
p.fail("BatchDownload 响应中缺少 download_rsp");
return;
}
String url = downloadRsp.getJsonObject(0).getString("url");
if (url != null && url.startsWith("&filename=")) {
p.fail("该文件已被和谐");
return;
}
if (fileName != null) {
url = url + "&filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8);
}
p.complete(url);
})
.onFailure(e -> {
LOG.error("BatchDownload 请求异常", e);
p.fail(e);
});
}
/**
* 调用 GetFileList API 获取指定目录下的文件列表
*/
private Future<JsonArray> fetchFileList(String filesetId, String parentId) {
Promise<JsonArray> p = Promise.promise();
JsonObject body = new JsonObject()
.put("fileset_id", filesetId)
.put("req_infos", new JsonArray()
.add(new JsonObject()
.put("parent_id", parentId)
.put("req_depth", 1)
.put("count", 50)
.put("filter_condition", new JsonObject().put("file_category", 0))
.put("sort_conditions", new JsonArray()
.add(new JsonObject()
.put("sort_field", 0)
.put("sort_order", 0)))))
.put("support_folder_status", true);
// 创建局部副本避免修改静态 MultiMap 导致并发污染
MultiMap headers = MultiMap.caseInsensitiveMultiMap().addAll(GET_FILE_LIST_HEADERS)
.set("Referer", shareLinkInfo.getShareUrl());
client.postAbs(GET_FILE_LIST_API)
.putHeaders(headers)
.sendJsonObject(body)
.onSuccess(resp -> {
if (resp.statusCode() != 200) {
p.fail("GetFileList 请求失败,状态码: " + resp.statusCode());
return;
}
JsonObject respBody = asJson(resp);
if (respBody.getInteger("retcode", -1) != 0) {
p.fail("GetFileList 请求失败: " + respBody.getString("message", "未知错误"));
return;
}
JsonArray fileLists = respBody.getJsonObject("data").getJsonArray("file_lists");
if (fileLists == null || fileLists.isEmpty()) {
p.fail("GetFileList 响应中缺少 file_lists");
return;
}
JsonArray fileList = fileLists.getJsonObject(0).getJsonArray("file_list");
p.complete(fileList != null ? fileList : new JsonArray());
})
.onFailure(e -> {
LOG.error("GetFileList 请求异常", e);
p.fail(e);
});
return p.future();
}
/**
* HTML __NUXT_DATA__ 中提取 fileset_id
*/
String extractFilesetId(String html) {
// Nuxt __NUXT_DATA__ fileset_id 出现在缓存 key 的嵌套 JSON
// 直接匹配 fileset_id 后面最近的 UUID跳过转义引号冒号等非hex字符
Matcher matcher = FILESET_ID_PATTERN.matcher(html);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
/**
* 旧版解析方式兼容单文件链接通过 HTML 字符串搜索提取 UUID
*/
private void parseLegacy(String html, String fileName) {
String fileUUID = getFileUUID(html);
if (fileUUID == null) {
promise.fail("未能提取到文件UUID");
return;
}
LOG.info("使用旧版解析,提取到的文件UUID: {}", fileUUID);
downloadFile(fileUUID, fileName);
}
String getFileUUID(String htmlJs) {
String keyword = "\"download_limit_status\"";
String marker = "},\"";
@@ -324,22 +140,32 @@ public class QQscTool extends PanBase {
String extracted = htmlJs.substring(quoteStart, quoteEnd);
LOG.debug("提取结果: {}", extracted);
return extracted;
} else {
LOG.error("未找到结束引号: {}", marker);
}
} else {
LOG.error("未找到标记: {} 在关键字: {} 之后", marker, keyword);
}
} else {
LOG.error("未找到关键字: {}", keyword);
}
return null;
}
public static String extractFileNameFromTitle(String content) {
Matcher matcher = TITLE_PATTERN.matcher(content);
// 匹配<title></title>之间的内容
Pattern pattern = Pattern.compile("<title>(.*?)</title>");
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
String fullTitle = matcher.group(1);
// "" 分割取前半部分
int sepIndex = fullTitle.indexOf("");
if (sepIndex != -1) {
return fullTitle.substring(0, sepIndex);
}
return fullTitle;
return fullTitle; // 如果没有分隔符就返回全部
}
return null;
}
}
@@ -3,11 +3,10 @@ package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import io.vertx.core.Future;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QQwTool extends QQTool {
@@ -17,51 +16,54 @@ public class QQwTool extends QQTool {
@Override
public Future<String> parse() {
String k = shareLinkInfo.getShareKey();
String postBody = "f=json&k=" + URLEncoder.encode(k, StandardCharsets.UTF_8);
client.getAbs(shareLinkInfo.getShareUrl()).send().onSuccess(res -> {
String html = res.bodyAsString();
Map<String, String> stringStringMap = extractVariables(html);
String url = stringStringMap.get("url");
String fn = stringStringMap.get("filename");
String size = stringStringMap.get("filesize");
String createBy = stringStringMap.get("nick");
FileInfo fileInfo = new FileInfo().setFileName(fn).setSize(Long.parseLong(size)).setCreateBy(createBy);
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
if (url != null) {
String url302 = url.replace("\\x26", "&");
promise.complete(url302);
client.postAbs("https://wx.mail.qq.com/s")
.putHeader("Content-Type", "application/x-www-form-urlencoded")
.putHeader("Accept", "application/json, text/plain, */*")
.putHeader("Referer", shareLinkInfo.getShareUrl())
.putHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0")
.sendBuffer(Buffer.buffer(postBody))
.onSuccess(res -> {
try {
JsonObject data = asJson(res);
JsonObject head = data.getJsonObject("head");
if (head == null || head.getInteger("ret", -1) != 0) {
String msg = head != null ? head.getString("msg", "未知错误") : "未知错误";
fail("API错误: " + msg);
return;
}
JsonObject body = data.getJsonObject("body");
if (body == null) {
fail("文件信息为空");
return;
}
String url = body.getString("url");
String fn = body.getString("name", "");
long size = body.getLong("size", 0L);
if (url == null || url.isEmpty()) {
fail("分享链接解析失败, 可能是链接失效");
return;
}
FileInfo fileInfo = new FileInfo().setFileName(fn).setSize(size);
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
String url302 = url.replace("\\x26", "&");
complete(url302);
} catch (Exception e) {
fail(e, "解析响应失败");
/*
clientNoRedirects.getAbs(url302).send().onSuccess(res2 -> {
MultiMap headers = res2.headers();
if (headers.contains("Location")) {
promise.complete(headers.get("Location"));
} else {
fail("找不到重定向URL");
}
}).onFailure(handleFail());
*/
} else {
fail("分享链接解析失败, 可能是链接失效");
}
}).onFailure(handleFail());
return promise.future();
}
private Map<String, String> extractVariables(String jsCode) {
Map<String, String> variables = new HashMap<>();
// 正则表达式匹配 var 变量定义
String regex = "\\s+var\\s+(\\w+)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^;\\r\\n]*))";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(jsCode);
while (m.find()) {
String name = m.group(1);
String value = m.group(2) != null ? m.group(2)
: m.group(3) != null ? m.group(3)
: m.group(4);
variables.put(name, value);
}
return variables;
}
}
@@ -67,7 +67,11 @@ public class WsTool extends PanBase {
String filepid = asJson(res2).getJsonObject("data").getString("ufileid"); // 文件夹pid
String filebid = asJson(res2).getJsonObject("data").getString("boxid"); // 文件夹bid
log.debug("文件夹期限: {}, 大小: {}, pid: {}, bid: {}", filetime, filesize, filepid, filebid);
// 调试输出文件夹信息
System.out.println("文件夹期限: " + filetime);
System.out.println("文件夹大小: " + filesize);
System.out.println("文件夹pid: " + filepid);
System.out.println("文件夹bid: " + filebid);
// 获取文件信息
httpClient.postAbs(SHARE_URL_API + "ufile/list").putHeaders(headers)
@@ -93,7 +97,9 @@ public class WsTool extends PanBase {
String filefid = asJson(res3).getJsonObject("data")
.getJsonArray("fileList").getJsonObject(0).getString("fid"); // 文件fid
log.debug("文件名称: {}, fid: {}", filename, filefid);
// 调试输出文件信息
System.out.println("文件名称: " + filename);
System.out.println("文件fid: " + filefid);
// 检查文件是否失效
httpClient.postAbs(SHARE_URL_API + "dl/sign").putHeaders(headers)
@@ -108,7 +114,8 @@ public class WsTool extends PanBase {
// 获取直链
String fileurl = asJson(res4).getJsonObject("data").getString("url");
log.debug("文件直链: {}", fileurl);
// 调试输出文件直链
System.out.println("文件直链: " + fileurl);
if (!fileurl.equals("")) {
promise.complete(URLDecoder.decode(fileurl, StandardCharsets.UTF_8));
@@ -3,10 +3,8 @@ package cn.qaiu.parser.impl;
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.FileSizeConverter;
import cn.qaiu.util.YeShareHostUtil;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
@@ -21,11 +19,7 @@ import org.apache.commons.lang3.StringUtils;
import java.net.MalformedURLException;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.*;
import java.util.zip.CRC32;
import static cn.qaiu.util.RandomStringGenerator.gen36String;
@@ -38,22 +32,24 @@ import static cn.qaiu.util.RandomStringGenerator.gen36String;
*/
public class Ye2Tool extends PanBase {
private static final String API_BASE = "https://api.123278.com";
private static final String GET_SHARE_INFO_URL = API_BASE + "/b/api/share/get?limit=100&next=1&orderBy=share_id&orderDirection=desc&shareKey={shareKey}&SharePwd={pwd}&ParentFileId={ParentFileId}&Page=1";
private static final String DOWNLOAD_API_URL = API_BASE + "/b/api/file/download_info";
private static final String DOWNLOAD_API_V2_BASE = "https://api.123278.com";
private static final String DOWNLOAD_API_V2_PATH = "/b/api/v2/share/download/info";
private static final String BATCH_DOWNLOAD_API_URL = API_BASE + "/b/api/file/batch_download_share_info";
public static final String SHARE_URL_PREFIX = "https://www.123pan.com/s/";
public static final String FIRST_REQUEST_URL = SHARE_URL_PREFIX + "{key}.html";
private static final String GET_SHARE_INFO_URL = "https://www.123pan.com/b/api/share/get?limit=100&next=1&orderBy=share_id&orderDirection=desc&shareKey={shareKey}&SharePwd={pwd}&ParentFileId={ParentFileId}&Page=1";
private static final String DOWNLOAD_API_URL = "https://www.123pan.com/b/api/file/download_info";
private static final String BATCH_DOWNLOAD_API_URL = "https://www.123pan.com/b/api/file/batch_download_share_info";
private static final String LOGIN_URL = "https://login.123pan.com/api/user/sign_in";
// 字符映射表
private static final String CHAR_MAP = "adefghlmyijnopkqrstubcvwsz";
private final MultiMap header = MultiMap.caseInsensitiveMultiMap();
private final String cacheKey;
// Token管理
private static String ssoToken;
private static long tokenExpireTime = 0L; // 毫秒时间戳
public Ye2Tool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
this.cacheKey = TokenCache.key("ye2", resolveAccountId());
header.set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
header.set("App-Version", "55");
header.set("Cache-Control", "no-cache");
@@ -69,27 +65,16 @@ public class Ye2Tool extends PanBase {
header.set("Content-Type", "application/json");
}
private String resolveAccountId() {
String accountId = "_default";
if (!shareLinkInfo.getOtherParam().containsKey("auths")) {
return accountId;
}
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
if (auths.contains("_configId")) {
accountId = auths.get("_configId");
} else if (auths.contains("username")) {
accountId = auths.get("username");
} else if (auths.contains("token")) {
String token = auths.get("token");
accountId = token.substring(0, Math.min(16, token.length()));
}
return accountId;
}
/**
* 判断 token 是否过期
*/
private boolean isTokenExpired() {
return TokenCache.isExpired(cacheKey);
return System.currentTimeMillis() > tokenExpireTime - 60_000; // 提前1分钟刷新
}
/**
* 计算CRC32并转换为16进制字符串
*/
private String crc32(String data) {
CRC32 crc32 = new CRC32();
crc32.update(data.getBytes());
@@ -97,58 +82,105 @@ public class Ye2Tool extends PanBase {
return String.format("%08x", value);
}
/**
* 16进制转10进制
*/
private long hexToInt(String hexStr) {
return Long.parseLong(hexStr, 16);
}
/**
* 123盘的URL加密算法
* 参考Python代码中的encode123函数
*
* @param url 请求路径
* @param way 平台标识"android"
* @param version 版本号"55"
* @param timestamp 时间戳毫秒
* @return 加密后的URL参数格式?{y}={time_long}-{a}-{final_crc}
*/
private String encode123(String url, String way, String version, String timestamp) {
Random random = new Random();
// 生成随机数 a = int(10000000 * random.randint(1, 10000000) / 10000)
int randomInt = random.nextInt(10000000) + 1;
long a = (10000000L * randomInt) / 10000;
// 将时间戳转换为时间格式
long timeLong = Long.parseLong(timestamp) / 1000;
java.time.LocalDateTime dateTime = java.time.Instant.ofEpochSecond(timeLong)
.atZone(java.time.ZoneId.systemDefault())
.toLocalDateTime();
String timeStr = dateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
// 根据时间字符串生成g
StringBuilder g = new StringBuilder();
for (char c : timeStr.toCharArray()) {
int digit = Character.getNumericValue(c);
if (digit == 0) {
g.append(CHAR_MAP.charAt(0));
} else {
// 数字1对应索引0数字2对应索引1以此类推
g.append(CHAR_MAP.charAt(digit - 1));
}
}
// 计算y值CRC32的十进制
String y = String.valueOf(hexToInt(crc32(g.toString())));
// 计算最终的CRC32
String finalCrcInput = String.format("%d|%d|%s|%s|%s|%s", timeLong, a, url, way, version, y);
String finalCrc = String.valueOf(hexToInt(crc32(finalCrcInput)));
// 返回加密后的URL参数
return String.format("?%s=%d-%d-%s", y, timeLong, a, finalCrc);
}
public Future<String> parse() {
Future<String> tokenFuture = resolveTokenFuture();
Future<String> tokenFuture;
// 检查是否直接提供了token
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
if (auths != null && auths.contains("token")) {
String providedToken = auths.get("token");
if (StringUtils.isNotEmpty(providedToken)) {
ssoToken = providedToken;
tokenFuture = Future.succeededFuture(providedToken);
} else {
// 如果没有提供token尝试登录
if (ssoToken == null || isTokenExpired()) {
tokenFuture = loginAndGetToken();
} else {
tokenFuture = Future.succeededFuture(ssoToken);
}
}
} else {
// 如果没有提供token尝试登录
if (ssoToken == null || isTokenExpired()) {
tokenFuture = loginAndGetToken();
} else {
tokenFuture = Future.succeededFuture(ssoToken);
}
}
// 1. 登录获取 sso-token 或使用提供的token
tokenFuture.onSuccess(token -> {
if (!token.equals("nologin")) {
TokenCache.putToken(cacheKey, token);
// 2. 设置 header
ssoToken = token;
header.set("Authorization", "Bearer " + token);
}
final String dataKey = YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey());
final String dataKey = shareLinkInfo.getShareKey().replace(".html", "");
final String pwd = shareLinkInfo.getSharePassword();
final String shareOrigin = resolveYeShareOrigin(dataKey);
final String shareReferer = buildShareReferer(shareOrigin, dataKey, pwd);
// 3. 获取分享信息
client.getAbs(UriTemplate.of(GET_SHARE_INFO_URL))
.setTemplateParam("shareKey", dataKey)
.setTemplateParam("pwd", StringUtils.isEmpty(pwd) ? "" : pwd)
.setTemplateParam("ParentFileId", "0")
.putHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
.putHeader("Referer", shareReferer)
.putHeader("Origin", shareOrigin)
.putHeader("Referer", "https://www.123pan.com/")
.putHeader("Origin", "https://www.123pan.com")
.send()
.onSuccess(res -> {
JsonObject shareInfoJson = asJson(res);
@@ -168,41 +200,35 @@ public class Ye2Tool extends PanBase {
return;
}
// 获取第一个文件信息
JsonObject fileInfo = data.getJsonArray("InfoList").getJsonObject(0);
// 检查是否需要登录
if (token.equals("nologin")) {
fail("该分享需要登录才能下载,请配置认证信息");
fail("该分享需要登录才能下载,请提供账号密码或token");
return;
}
// 判断是否为文件夹: Type: 1为文件夹, 0为文件
if (fileInfo.getInteger("Type", 0) == 1) {
// 4. 获取文件夹打包下载链接
getZipDownUrl(client, fileInfo);
} else {
// 4. 获取文件下载链接
getDownUrl(client, fileInfo);
}
})
.onFailure(this.handleFail(GET_SHARE_INFO_URL));
}).onFailure(err -> fail("123盘解析异常: {}", err.getMessage()));
}).onFailure(err -> {
fail("登录获取token失败: {}", err.getMessage());
});
return promise.future();
}
private Future<String> resolveTokenFuture() {
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
if (auths != null && auths.contains("token")) {
String providedToken = auths.get("token");
if (StringUtils.isNotEmpty(providedToken)) {
TokenCache.putToken(cacheKey, providedToken);
return Future.succeededFuture(providedToken);
}
}
String cached = TokenCache.getToken(cacheKey);
if (cached == null || isTokenExpired()) {
return loginAndGetToken();
}
return Future.succeededFuture(cached);
}
/**
* 登录并获取token
*/
private Future<String> loginAndGetToken() {
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
if (auths == null) {
@@ -249,17 +275,16 @@ public class Ye2Tool extends PanBase {
promise.fail("未获取到token");
return;
}
String ssoToken = data.getString("token");
ssoToken = data.getString("token");
String expireStr = data.getString("expire");
long expireMs;
// 解析过期时间
if (StringUtils.isNotEmpty(expireStr)) {
expireMs = OffsetDateTime.parse(expireStr)
.toInstant().toEpochMilli() - 60_000;
tokenExpireTime = OffsetDateTime.parse(expireStr)
.toInstant().toEpochMilli();
} else {
expireMs = System.currentTimeMillis() + 3600_000;
// 如果没有过期时间默认1小时后过期
tokenExpireTime = System.currentTimeMillis() + 3600_000;
}
TokenCache.putToken(cacheKey, ssoToken);
TokenCache.putExpire(cacheKey, expireMs);
log.info("登录成功,token: {}", ssoToken);
promise.complete(ssoToken);
})
@@ -267,34 +292,13 @@ public class Ye2Tool extends PanBase {
return promise.future();
}
/**
* 获取下载链接使用Android平台API
*/
private void getDownUrl(WebClient client, JsonObject fileInfo) {
setFileInfo(fileInfo);
String normalizedShareKey = YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey());
if (StringUtils.isNotEmpty(normalizedShareKey)) {
JsonObject v2Body = new JsonObject()
.put("ShareKey", normalizedShareKey)
.put("FileID", fileInfo.getInteger("FileId"))
.put("S3keyFlag", fileInfo.getString("S3KeyFlag"))
.put("Size", fileInfo.getLong("Size"))
.put("Etag", fileInfo.getString("Etag"));
requestShareV2Download(normalizedShareKey, v2Body).onSuccess(v2Url -> {
if (StringUtils.isNotEmpty(v2Url)) {
complete(v2Url);
return;
}
requestLegacyDownUrl(client, fileInfo);
}).onFailure(err -> {
log.warn("Ye2 v2分享下载接口失败,回退旧接口: {}", err.getMessage());
requestLegacyDownUrl(client, fileInfo);
});
return;
}
requestLegacyDownUrl(client, fileInfo);
}
private void requestLegacyDownUrl(WebClient client, JsonObject fileInfo) {
// 构建请求数据
JsonObject jsonObject = new JsonObject();
jsonObject.put("driveId", 0);
jsonObject.put("etag", fileInfo.getString("Etag"));
@@ -304,6 +308,7 @@ public class Ye2Tool extends PanBase {
jsonObject.put("size", fileInfo.getLong("Size"));
jsonObject.put("type", 0);
// 使用encode123加密URL参数
String timestamp = String.valueOf(System.currentTimeMillis());
String encryptedParams = encode123("/b/api/file/download_info", "android", "55", timestamp);
String apiUrl = DOWNLOAD_API_URL + encryptedParams;
@@ -313,71 +318,92 @@ public class Ye2Tool extends PanBase {
HttpRequest<Buffer> bufferHttpRequest = client.postAbs(apiUrl);
bufferHttpRequest.putHeader("platform", "android");
bufferHttpRequest.putHeader("App-Version", "55");
bufferHttpRequest.putHeader("Authorization", "Bearer " + TokenCache.getToken(cacheKey));
bufferHttpRequest.putHeader("Authorization", "Bearer " + ssoToken);
bufferHttpRequest.putHeader("User-Agent", "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36");
bufferHttpRequest.putHeader("Content-Type", "application/json");
bufferHttpRequest
.sendJsonObject(jsonObject)
.onSuccess(res2 -> handleDownloadUrlResponse(client, asJson(res2), "Ye2"))
.onFailure(err -> fail("下载接口失败: " + err.getMessage()));
}
.onSuccess(res2 -> {
JsonObject downURLJson = asJson(res2);
try {
if (downURLJson.getInteger("code") != 0) {
fail("Ye2: downURLJson返回值异常->" + downURLJson);
return;
}
} catch (Exception ignored) {
fail("Ye2: downURLJson格式异常->" + downURLJson);
return;
}
private Future<String> requestShareV2Download(String shareKey, JsonObject body) {
Promise<String> promise = Promise.promise();
String timestamp = String.valueOf(System.currentTimeMillis());
String encryptedParams = encode123(DOWNLOAD_API_V2_PATH, "web", "3", timestamp);
String apiUrl = DOWNLOAD_API_V2_BASE + DOWNLOAD_API_V2_PATH + encryptedParams;
String shareOrigin = resolveYeShareOrigin(shareKey);
String shareReferer = buildShareReferer(shareOrigin, shareKey, shareLinkInfo.getSharePassword());
String downURL = downURLJson.getJsonObject("data").getString("DownloadUrl");
if (StringUtils.isEmpty(downURL)) {
downURL = downURLJson.getJsonObject("data").getString("DownloadURL");
}
HttpRequest<Buffer> request = client.postAbs(apiUrl);
request.putHeader("Accept", "*/*");
request.putHeader("Authorization", "Bearer " + TokenCache.getToken(cacheKey));
request.putHeader("App-Version", "3");
request.putHeader("platform", "web");
request.putHeader("Origin", shareOrigin);
request.putHeader("Referer", shareReferer);
request.putHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36");
request.putHeader("Content-Type", "application/json;charset=UTF-8");
if (StringUtils.isEmpty(downURL)) {
fail("Ye2: 未获取到下载链接");
return;
}
request.sendJsonObject(body).onSuccess(resp -> {
JsonObject json = asJson(resp);
if (json == null || json.getInteger("code", -1) != 0) {
promise.fail("v2接口返回异常: " + (json == null ? "null" : json.encode()));
return;
}
JsonObject data = json.getJsonObject("data", new JsonObject());
JsonArray dispatchList = data.getJsonArray("dispatchList", new JsonArray());
String downloadPath = data.getString("downloadPath");
if (StringUtils.isBlank(downloadPath)) {
promise.complete("");
return;
}
String prefix = "";
if (dispatchList.size() > 0) {
JsonObject firstDispatch = dispatchList.getJsonObject(0);
if (firstDispatch != null) {
prefix = firstDispatch.getString("prefix", "");
}
}
if (StringUtils.isBlank(prefix)) {
promise.complete(downloadPath);
return;
}
String finalUrl = prefix.endsWith("/") ? prefix.substring(0, prefix.length() - 1) : prefix;
finalUrl += downloadPath.startsWith("/") ? downloadPath : "/" + downloadPath;
promise.complete(finalUrl);
}).onFailure(promise::fail);
try {
Map<String, String> urlParams = CommonUtils.getURLParams(downURL);
String params = urlParams.get("params");
if (StringUtils.isEmpty(params)) {
// 如果没有params参数直接使用downURL
complete(downURL);
return;
}
return promise.future();
byte[] decodeByte = Base64.getDecoder().decode(params);
String downUrl2 = new String(decodeByte);
clientNoRedirects.getAbs(downUrl2).putHeaders(header).send().onSuccess(res3 -> {
if (res3.statusCode() == 302 || res3.statusCode() == 301) {
String redirectUrl = res3.getHeader("Location");
if (StringUtils.isBlank(redirectUrl)) {
fail("重定向链接为空");
return;
}
complete(redirectUrl);
return;
}
JsonObject res3Json = asJson(res3);
try {
if (res3Json.getInteger("code") != 0) {
fail("Ye2: downUrl2返回值异常->" + res3Json);
return;
}
} catch (Exception ignored) {
fail("Ye2: downUrl2格式异常->" + downURLJson);
return;
}
String redirectUrl = res3Json.getJsonObject("data").getString("redirect_url");
if (StringUtils.isNotEmpty(redirectUrl)) {
complete(redirectUrl);
} else {
complete(downUrl2);
}
}).onFailure(err -> fail("获取直链失败: " + err.getMessage()));
} catch (MalformedURLException e) {
// 如果解析失败直接使用downURL
complete(downURL);
} catch (Exception e) {
fail("urlParams解析异常: " + e.getMessage());
}
}).onFailure(err -> fail("下载接口失败: " + err.getMessage()));
}
/**
* 获取文件夹打包下载链接使用Android平台API
*/
private void getZipDownUrl(WebClient client, JsonObject fileInfo) {
// 构建请求数据
JsonObject jsonObject = new JsonObject();
jsonObject.put("shareKey", YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey()));
jsonObject.put("shareKey", shareLinkInfo.getShareKey().replace(".html", ""));
jsonObject.put("fileIdList", new JsonArray().add(JsonObject.of("fileId", fileInfo.getInteger("FileId"))));
// 使用encode123加密URL参数
String timestamp = String.valueOf(System.currentTimeMillis());
String encryptedParams = encode123("/b/api/file/batch_download_share_info", "android", "55", timestamp);
String apiUrl = BATCH_DOWNLOAD_API_URL + encryptedParams;
@@ -387,82 +413,85 @@ public class Ye2Tool extends PanBase {
HttpRequest<Buffer> bufferHttpRequest = client.postAbs(apiUrl);
bufferHttpRequest.putHeader("platform", "android");
bufferHttpRequest.putHeader("App-Version", "55");
bufferHttpRequest.putHeader("Authorization", "Bearer " + TokenCache.getToken(cacheKey));
bufferHttpRequest.putHeader("Authorization", "Bearer " + ssoToken);
bufferHttpRequest.putHeader("User-Agent", "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36");
bufferHttpRequest.putHeader("Content-Type", "application/json");
bufferHttpRequest
.sendJsonObject(jsonObject)
.onSuccess(res2 -> handleDownloadUrlResponse(client, asJson(res2), "Ye2: 文件夹打包下载"))
.onFailure(err -> fail("文件夹打包下载接口失败: " + err.getMessage()));
}
private void handleDownloadUrlResponse(WebClient client, JsonObject downURLJson, String failPrefix) {
try {
if (downURLJson.getInteger("code") != 0) {
fail(failPrefix + "返回值异常->" + downURLJson);
return;
}
} catch (Exception ignored) {
fail(failPrefix + "格式异常->" + downURLJson);
return;
}
String downURL = downURLJson.getJsonObject("data").getString("DownloadUrl");
if (StringUtils.isEmpty(downURL)) {
downURL = downURLJson.getJsonObject("data").getString("DownloadURL");
}
if (StringUtils.isEmpty(downURL)) {
fail(failPrefix + "未获取到下载链接");
return;
}
try {
Map<String, String> urlParams = CommonUtils.getURLParams(downURL);
String params = urlParams.get("params");
if (StringUtils.isEmpty(params)) {
complete(downURL);
return;
}
byte[] decodeByte = Base64.getDecoder().decode(params);
String downUrl2 = new String(decodeByte);
clientNoRedirects.getAbs(downUrl2).putHeaders(header).send().onSuccess(res3 -> {
if (res3.statusCode() == 302 || res3.statusCode() == 301) {
String redirectUrl = res3.getHeader("Location");
if (StringUtils.isBlank(redirectUrl)) {
fail("重定向链接为空");
.onSuccess(res2 -> {
JsonObject downURLJson = asJson(res2);
try {
if (downURLJson.getInteger("code") != 0) {
fail("Ye2: 文件夹打包下载接口返回值异常->" + downURLJson);
return;
}
} catch (Exception ignored) {
fail("Ye2: 文件夹打包下载接口格式异常->" + downURLJson);
return;
}
complete(redirectUrl);
return;
}
JsonObject res3Json = asJson(res3);
try {
if (res3Json.getInteger("code") != 0) {
fail(failPrefix + "重定向返回值异常->" + res3Json);
String downURL = downURLJson.getJsonObject("data").getString("DownloadUrl");
if (StringUtils.isEmpty(downURL)) {
downURL = downURLJson.getJsonObject("data").getString("DownloadURL");
}
if (StringUtils.isEmpty(downURL)) {
fail("Ye2: 未获取到文件夹打包下载链接");
return;
}
} catch (Exception ignored) {
fail(failPrefix + "重定向格式异常->" + downURLJson);
return;
}
String redirectUrl = res3Json.getJsonObject("data").getString("redirect_url");
if (StringUtils.isNotEmpty(redirectUrl)) {
complete(redirectUrl);
} else {
complete(downUrl2);
}
}).onFailure(err -> fail("获取直链失败: " + err.getMessage()));
} catch (MalformedURLException e) {
complete(downURL);
} catch (Exception e) {
fail("urlParams解析异常: " + e.getMessage());
}
try {
Map<String, String> urlParams = CommonUtils.getURLParams(downURL);
String params = urlParams.get("params");
if (StringUtils.isEmpty(params)) {
// 如果没有params参数直接使用downURL
complete(downURL);
return;
}
byte[] decodeByte = Base64.getDecoder().decode(params);
String downUrl2 = new String(decodeByte);
clientNoRedirects.getAbs(downUrl2).putHeaders(header).send().onSuccess(res3 -> {
if (res3.statusCode() == 302 || res3.statusCode() == 301) {
String redirectUrl = res3.getHeader("Location");
if (StringUtils.isBlank(redirectUrl)) {
fail("重定向链接为空");
return;
}
complete(redirectUrl);
return;
}
JsonObject res3Json = asJson(res3);
try {
if (res3Json.getInteger("code") != 0) {
fail("Ye2: 文件夹打包下载重定向返回值异常->" + res3Json);
return;
}
} catch (Exception ignored) {
fail("Ye2: 文件夹打包下载重定向格式异常->" + downURLJson);
return;
}
String redirectUrl = res3Json.getJsonObject("data").getString("redirect_url");
if (StringUtils.isNotEmpty(redirectUrl)) {
complete(redirectUrl);
} else {
complete(downUrl2);
}
}).onFailure(err -> fail("获取文件夹打包下载直链失败: " + err.getMessage()));
} catch (MalformedURLException e) {
// 如果解析失败直接使用downURL
complete(downURL);
} catch (Exception e) {
fail("文件夹打包下载urlParams解析异常: " + e.getMessage());
}
}).onFailure(err -> fail("文件夹打包下载接口失败: " + err.getMessage()));
}
/**
* 设置文件信息
*/
void setFileInfo(JsonObject reqBodyJson) {
FileInfo fileInfo = new FileInfo();
fileInfo.setFileId(reqBodyJson.getInteger("FileId").toString());
@@ -485,39 +514,62 @@ public class Ye2Tool extends PanBase {
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
}
/**
* 解析文件夹中的文件列表
*/
@Override
public Future<List<FileInfo>> parseFileList() {
Promise<List<FileInfo>> promise = Promise.promise();
String shareKey = YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey());
String shareKey = shareLinkInfo.getShareKey().replace(".html", "");
String pwd = shareLinkInfo.getSharePassword();
String parentFileId = "0";
String parentFileId = "0"; // 根目录的文件ID
// 如果参数里的目录ID不为空则直接解析目录
String dirId = (String) shareLinkInfo.getOtherParam().get("dirId");
if (StringUtils.isNotBlank(dirId)) {
parentFileId = dirId;
}
Future<String> tokenFuture = resolveTokenFuture();
// 确保已登录
Future<String> tokenFuture;
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
if (auths != null && auths.contains("token")) {
String providedToken = auths.get("token");
if (StringUtils.isNotEmpty(providedToken)) {
ssoToken = providedToken;
tokenFuture = Future.succeededFuture(providedToken);
} else {
if (ssoToken == null || isTokenExpired()) {
tokenFuture = loginAndGetToken();
} else {
tokenFuture = Future.succeededFuture(ssoToken);
}
}
} else {
if (ssoToken == null || isTokenExpired()) {
tokenFuture = loginAndGetToken();
} else {
tokenFuture = Future.succeededFuture(ssoToken);
}
}
String finalParentFileId = parentFileId;
tokenFuture.onSuccess(token -> {
if (token.equals("nologin")) {
promise.fail("该分享需要登录才能访问,请配置认证信息");
promise.fail("该分享需要登录才能访问,请提供账号密码或token");
return;
}
String normalizedShareKey = YeShareHostUtil.normalizeShareKey(shareKey);
String shareOrigin = resolveYeShareOrigin(normalizedShareKey);
String shareReferer = buildShareReferer(shareOrigin, normalizedShareKey, pwd);
// 构造文件列表接口的URL
client.getAbs(UriTemplate.of(GET_SHARE_INFO_URL))
.setTemplateParam("shareKey", shareKey)
.setTemplateParam("pwd", StringUtils.isEmpty(pwd) ? "" : pwd)
.setTemplateParam("ParentFileId", finalParentFileId)
.putHeader("Authorization", "Bearer " + token)
.putHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
.putHeader("Referer", shareReferer)
.putHeader("Origin", shareOrigin)
.putHeader("Referer", "https://www.123pan.com/")
.putHeader("Origin", "https://www.123pan.com")
.send().onSuccess(res -> {
JsonObject response = asJson(res);
if (response.getInteger("code") != 0) {
@@ -533,12 +585,13 @@ public class Ye2Tool extends PanBase {
JsonArray infoList = response.getJsonObject("data").getJsonArray("InfoList");
List<FileInfo> result = new ArrayList<>();
// 遍历返回的文件和目录信息
for (int i = 0; i < infoList.size(); i++) {
JsonObject item = infoList.getJsonObject(i);
FileInfo fileInfo = new FileInfo();
// 构建下载参数
JsonObject postData = JsonObject.of()
.put("shareKey", shareLinkInfo.getShareKey())
.put("driveId", 0)
.put("etag", item.getString("Etag"))
.put("fileId", item.getInteger("FileId"))
@@ -549,7 +602,7 @@ public class Ye2Tool extends PanBase {
String param = CommonUtils.urlBase64Encode(postData.encode());
if (item.getInteger("Type") == 0) {
if (item.getInteger("Type") == 0) { // 文件
fileInfo.setFileName(item.getString("FileName"))
.setFileId(item.getInteger("FileId").toString())
.setFileType("file")
@@ -557,20 +610,40 @@ public class Ye2Tool extends PanBase {
.setHash(item.getString("Etag"))
.setSizeStr(FileSizeConverter.convertToReadableSize(item.getLong("Size")));
setFileTimes(item, fileInfo);
String createAt = item.getString("CreateAt");
if (StringUtils.isNotEmpty(createAt)) {
fileInfo.setCreateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.format(OffsetDateTime.parse(createAt).toLocalDateTime()));
}
String updateAt = item.getString("UpdateAt");
if (StringUtils.isNotEmpty(updateAt)) {
fileInfo.setUpdateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.format(OffsetDateTime.parse(updateAt).toLocalDateTime()));
}
fileInfo.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(),
shareLinkInfo.getType(), param))
.setPreviewUrl(String.format("%s/v2/viewUrl/%s/%s", getDomainName(),
shareLinkInfo.getType(), param));
result.add(fileInfo);
} else if (item.getInteger("Type") == 1) {
} else if (item.getInteger("Type") == 1) { // 目录
fileInfo.setFileName(item.getString("FileName"))
.setFileId(item.getInteger("FileId").toString())
.setFileType("folder")
.setSize(0L);
setFileTimes(item, fileInfo);
String createAt = item.getString("CreateAt");
if (StringUtils.isNotEmpty(createAt)) {
fileInfo.setCreateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.format(OffsetDateTime.parse(createAt).toLocalDateTime()));
}
String updateAt = item.getString("UpdateAt");
if (StringUtils.isNotEmpty(updateAt)) {
fileInfo.setUpdateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.format(OffsetDateTime.parse(updateAt).toLocalDateTime()));
}
fileInfo.setParserUrl(
String.format("%s/v2/getFileList?url=%s&dirId=%s&pwd=%s",
@@ -584,129 +657,134 @@ public class Ye2Tool extends PanBase {
}
promise.complete(result);
}).onFailure(promise::fail);
}).onFailure(err -> promise.fail("123盘解析异常: " + err.getMessage()));
}).onFailure(err -> promise.fail("登录获取token失败: " + err.getMessage()));
return promise.future();
}
/**
* 通过ID解析特定文件
*/
@Override
public Future<String> parseById() {
JsonObject paramJson = (JsonObject) shareLinkInfo.getOtherParam().get("paramJson");
Future<String> tokenFuture = resolveTokenFuture();
// 确保已登录
Future<String> tokenFuture;
MultiMap auths = (MultiMap) shareLinkInfo.getOtherParam().get("auths");
if (auths != null && auths.contains("token")) {
String providedToken = auths.get("token");
if (StringUtils.isNotEmpty(providedToken)) {
ssoToken = providedToken;
tokenFuture = Future.succeededFuture(providedToken);
} else {
if (ssoToken == null || isTokenExpired()) {
tokenFuture = loginAndGetToken();
} else {
tokenFuture = Future.succeededFuture(ssoToken);
}
}
} else {
if (ssoToken == null || isTokenExpired()) {
tokenFuture = loginAndGetToken();
} else {
tokenFuture = Future.succeededFuture(ssoToken);
}
}
tokenFuture.onSuccess(token -> {
if (token.equals("nologin")) {
fail("该分享需要登录才能下载,请配置认证信息");
fail("该分享需要登录才能下载,请提供账号密码或token");
return;
}
String normalizedShareKey = YeShareHostUtil.normalizeShareKey(shareLinkInfo.getShareKey());
if (StringUtils.isNotEmpty(normalizedShareKey)) {
JsonObject v2Body = new JsonObject()
.put("ShareKey", normalizedShareKey)
.put("FileID", paramJson.getInteger("fileId", paramJson.getInteger("FileID", 0)))
.put("S3keyFlag", paramJson.getString("s3keyFlag", paramJson.getString("S3keyFlag", "")))
.put("Size", paramJson.getLong("size", paramJson.getLong("Size", 0L)))
.put("Etag", paramJson.getString("etag", paramJson.getString("Etag", "")));
requestShareV2Download(normalizedShareKey, v2Body).onSuccess(v2Url -> {
if (StringUtils.isNotEmpty(v2Url)) {
complete(v2Url);
return;
}
parseByIdLegacy(token, paramJson);
}).onFailure(err -> {
log.warn("Ye2 parseById v2接口失败,回退旧接口: {}", err.getMessage());
parseByIdLegacy(token, paramJson);
});
return;
}
// 使用encode123加密URL参数
String timestamp = String.valueOf(System.currentTimeMillis());
String encryptedParams = encode123("/b/api/file/download_info", "android", "55", timestamp);
String apiUrl = DOWNLOAD_API_URL + encryptedParams;
parseByIdLegacy(token, paramJson);
}).onFailure(err -> fail("123盘解析异常: " + err.getMessage()));
log.info("Ye2 parseById API URL: {}", apiUrl);
HttpRequest<Buffer> bufferHttpRequest = client.postAbs(apiUrl);
bufferHttpRequest.putHeader("platform", "android");
bufferHttpRequest.putHeader("App-Version", "55");
bufferHttpRequest.putHeader("Authorization", "Bearer " + token);
bufferHttpRequest.putHeader("User-Agent", "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36");
bufferHttpRequest.putHeader("Content-Type", "application/json");
bufferHttpRequest
.sendJsonObject(paramJson)
.onSuccess(res2 -> {
JsonObject downURLJson = asJson(res2);
try {
if (downURLJson.getInteger("code") != 0) {
fail("Ye2: downURLJson返回值异常->" + downURLJson);
return;
}
} catch (Exception ignored) {
fail("Ye2: downURLJson格式异常->" + downURLJson);
return;
}
String downURL = downURLJson.getJsonObject("data").getString("DownloadUrl");
if (StringUtils.isEmpty(downURL)) {
downURL = downURLJson.getJsonObject("data").getString("DownloadURL");
}
if (StringUtils.isEmpty(downURL)) {
fail("Ye2: 未获取到下载链接");
return;
}
try {
Map<String, String> urlParams = CommonUtils.getURLParams(downURL);
String params = urlParams.get("params");
if (StringUtils.isEmpty(params)) {
// 如果没有params参数直接使用downURL
complete(downURL);
return;
}
byte[] decodeByte = Base64.getDecoder().decode(params);
String downUrl2 = new String(decodeByte);
clientNoRedirects.getAbs(downUrl2).putHeaders(header).send().onSuccess(res3 -> {
if (res3.statusCode() == 302 || res3.statusCode() == 301) {
String redirectUrl = res3.getHeader("Location");
if (StringUtils.isBlank(redirectUrl)) {
fail("重定向链接为空");
return;
}
complete(redirectUrl);
return;
}
JsonObject res3Json = asJson(res3);
try {
if (res3Json.getInteger("code") != 0) {
fail("Ye2: downUrl2返回值异常->" + res3Json);
return;
}
} catch (Exception ignored) {
fail("Ye2: downUrl2格式异常->" + downURLJson);
return;
}
String redirectUrl = res3Json.getJsonObject("data").getString("redirect_url");
if (StringUtils.isNotEmpty(redirectUrl)) {
complete(redirectUrl);
} else {
complete(downUrl2);
}
}).onFailure(err -> fail("获取直链失败: " + err.getMessage()));
} catch (MalformedURLException e) {
// 如果解析失败直接使用downURL
complete(downURL);
} catch (Exception e) {
fail("urlParams解析异常: " + e.getMessage());
}
}).onFailure(err -> fail("下载接口失败: " + err.getMessage()));
}).onFailure(err -> fail("登录获取token失败: " + err.getMessage()));
return promise.future();
}
private void parseByIdLegacy(String token, JsonObject paramJson) {
if (paramJson.containsKey("FileID") && !paramJson.containsKey("fileId")) {
paramJson.put("fileId", paramJson.getValue("FileID"));
}
if (paramJson.containsKey("S3keyFlag") && !paramJson.containsKey("s3keyFlag")) {
paramJson.put("s3keyFlag", paramJson.getValue("S3keyFlag"));
}
if (paramJson.containsKey("Size") && !paramJson.containsKey("size")) {
paramJson.put("size", paramJson.getValue("Size"));
}
if (paramJson.containsKey("Etag") && !paramJson.containsKey("etag")) {
paramJson.put("etag", paramJson.getValue("Etag"));
}
String timestamp = String.valueOf(System.currentTimeMillis());
String encryptedParams = encode123("/b/api/file/download_info", "android", "55", timestamp);
String apiUrl = DOWNLOAD_API_URL + encryptedParams;
log.info("Ye2 parseById API URL: {}", apiUrl);
HttpRequest<Buffer> bufferHttpRequest = client.postAbs(apiUrl);
bufferHttpRequest.putHeader("platform", "android");
bufferHttpRequest.putHeader("App-Version", "55");
bufferHttpRequest.putHeader("Authorization", "Bearer " + token);
bufferHttpRequest.putHeader("User-Agent", "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36");
bufferHttpRequest.putHeader("Content-Type", "application/json");
bufferHttpRequest
.sendJsonObject(paramJson)
.onSuccess(res2 -> handleDownloadUrlResponse(client, asJson(res2), "Ye2"))
.onFailure(err -> fail("下载接口失败: " + err.getMessage()));
}
private void setFileTimes(JsonObject item, FileInfo fileInfo) {
String createAt = item.getString("CreateAt");
if (StringUtils.isNotEmpty(createAt)) {
fileInfo.setCreateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.format(OffsetDateTime.parse(createAt).toLocalDateTime()));
}
String updateAt = item.getString("UpdateAt");
if (StringUtils.isNotEmpty(updateAt)) {
fileInfo.setUpdateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.format(OffsetDateTime.parse(updateAt).toLocalDateTime()));
}
}
private String resolveYeShareOrigin(String shareKey) {
String origin = extractYeShareOrigin(shareLinkInfo.getShareUrl());
if (StringUtils.isNotBlank(origin)) {
return origin;
}
origin = extractYeShareOrigin(shareLinkInfo.getStandardUrl());
if (StringUtils.isNotBlank(origin)) {
return origin;
}
String uid = YeShareHostUtil.getNumericSubdomainIdByShareKey(shareKey);
if (StringUtils.isNotBlank(uid)) {
return "https://" + uid + ".share.123pan.cn";
}
return "https://www.123pan.com";
}
private String extractYeShareOrigin(String url) {
if (StringUtils.isBlank(url) || !url.matches("^https?://[a-zA-Z\\d-]+\\.(?:mshare|share)\\.123pan\\.cn(?:[:/].*)?$")) {
return "";
}
int idx = url.indexOf('/', url.indexOf("//") + 2);
return idx > 0 ? url.substring(0, idx) : url;
}
private String buildShareReferer(String shareOrigin, String shareKey, String pwd) {
String key = YeShareHostUtil.normalizeShareKey(shareKey);
if (StringUtils.isBlank(key)) {
return shareOrigin + "/";
}
String referer = shareOrigin + "/123pan/" + key;
if (StringUtils.isNotBlank(pwd)) {
referer += "?pwd=" + pwd;
}
return referer;
}
}
@@ -14,6 +14,7 @@ import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.HexFormat;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -298,7 +299,7 @@ public class AESUtils {
//length用户要求产生字符串的长度
public static String getRandomString(int length){
String str="abcdefghijklmnopqrstuvwxyz0123456789";
SecureRandom random=new SecureRandom();
Random random=new Random();
StringBuilder sb=new StringBuilder();
for(int i=0;i<length;i++){
int number=random.nextInt(36);
@@ -33,9 +33,6 @@ public class CommonUtils {
public static Map<String, String> getURLParams(String url) throws MalformedURLException {
URL fullUrl = new URL(url);
String query = fullUrl.getQuery();
if (query == null || query.isEmpty()) {
return new HashMap<>();
}
String[] params = query.split("&");
Map<String, String> map = new HashMap<>();
for (String param : params) {
@@ -17,35 +17,16 @@ import java.util.zip.InflaterInputStream;
public class HttpResponseHelper {
static Logger LOGGER = LoggerFactory.getLogger(HttpResponseHelper.class);
private static final int MAX_RESPONSE_BODY_BYTES = 8 * 1024 * 1024;
private static final int MAX_DECOMPRESSED_CHARS = 16 * 1024 * 1024;
// -------------------- 公共方法 --------------------
public static String asText(HttpResponse<?> res) {
String encoding = res.getHeader(HttpHeaders.CONTENT_ENCODING.toString());
try {
Buffer body = toBuffer(res);
return asText(body, encoding);
} catch (IllegalArgumentException | UnsupportedOperationException e) {
throw e;
} catch (Exception e) {
LOGGER.error("asText: {}", e.getMessage(), e);
return null;
}
}
public static String asText(Buffer body, String encoding) {
try {
if (body == null) {
return "";
}
ensureBodyLimit(body);
if (encoding == null || "identity".equalsIgnoreCase(encoding)) {
return body.toString(StandardCharsets.UTF_8);
}
return decompress(body, encoding);
} catch (IllegalArgumentException | UnsupportedOperationException e) {
throw e;
} catch (Exception e) {
LOGGER.error("asText: {}", e.getMessage(), e);
return null;
@@ -55,29 +36,6 @@ public class HttpResponseHelper {
public static JsonObject asJson(HttpResponse<?> res) {
try {
String text = asText(res);
return parseJsonText(text);
} catch (IllegalArgumentException | UnsupportedOperationException e) {
throw e;
} catch (Exception e) {
LOGGER.error("asJson: {}", e.getMessage(), e);
return JsonObject.of();
}
}
public static JsonObject asJson(Buffer body, String encoding) {
try {
String text = asText(body, encoding);
return parseJsonText(text);
} catch (IllegalArgumentException | UnsupportedOperationException e) {
throw e;
} catch (Exception e) {
LOGGER.error("asJson: {}", e.getMessage(), e);
return JsonObject.of();
}
}
private static JsonObject parseJsonText(String text) {
try {
if (text != null) {
return new JsonObject(text);
} else {
@@ -95,26 +53,13 @@ public class HttpResponseHelper {
return res.body() instanceof Buffer ? (Buffer) res.body() : Buffer.buffer(res.bodyAsString());
}
private static void ensureBodyLimit(Buffer body) {
if (body != null && body.length() > MAX_RESPONSE_BODY_BYTES) {
throw new IllegalArgumentException("响应体过大: " + body.length() + " bytes");
}
}
private static void writeLimited(StringWriter writer, char[] buffer, int len) throws IOException {
if (writer.getBuffer().length() + len > MAX_DECOMPRESSED_CHARS) {
throw new IOException("解压后响应体过大");
}
writer.write(buffer, 0, len);
}
// -------------------- 通用解压分发 --------------------
private static String decompress(Buffer compressed, String encoding) throws IOException {
return switch (encoding.toLowerCase()) {
case "gzip" -> decompressGzip(compressed);
case "deflate" -> decompressDeflate(compressed);
case "br" -> decompressBrotli(compressed);
case "zstd" -> throw new UnsupportedOperationException("不支持的 Content-Encoding: zstd");
case "zstd" -> compressed.toString(StandardCharsets.UTF_8); // 暂时返回原始内容
default -> throw new UnsupportedOperationException("不支持的 Content-Encoding: " + encoding);
};
}
@@ -129,7 +74,7 @@ public class HttpResponseHelper {
char[] buffer = new char[4096];
int n;
while ((n = isr.read(buffer)) != -1) {
writeLimited(writer, buffer, n);
writer.write(buffer, 0, n);
}
return writer.toString();
}
@@ -154,7 +99,7 @@ public class HttpResponseHelper {
char[] buffer = new char[4096];
int n;
while ((n = isr.read(buffer)) != -1) {
writeLimited(writer, buffer, n);
writer.write(buffer, 0, n);
}
return writer.toString();
}
@@ -170,7 +115,7 @@ public class HttpResponseHelper {
char[] buffer = new char[4096];
int n;
while ((n = isr.read(buffer)) != -1) {
writeLimited(writer, buffer, n);
writer.write(buffer, 0, n);
}
return writer.toString();
}
@@ -1,12 +1,10 @@
package cn.qaiu.util;
import cn.qaiu.WebClientVertxInit;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.http.impl.headers.HeadersMultiMap;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
@@ -17,12 +15,6 @@ import java.util.ArrayList;
import java.util.List;
public class IpExtractor {
private static final Logger log = LoggerFactory.getLogger(IpExtractor.class);
// 使用共享的 Vertx 实例避免每次调用创建新实例导致资源泄漏
private static final WebClient SHARED_CLIENT = WebClient.create(WebClientVertxInit.get());
private static final WebClientSession SHARED_SESSION = WebClientSession.create(SHARED_CLIENT);
public static void main(String[] args) throws InterruptedException {
@@ -47,10 +39,12 @@ public class IpExtractor {
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36");
headers.add("Content-Type", "application/x-www-form-urlencoded");
SHARED_SESSION.getAbs("https://ip.ihuan.me").putHeaders(headers).send().onSuccess(res->{
log.debug("response: {}", res.toString());
SHARED_SESSION.getAbs("https://ip.ihuan.me").putHeaders(headers).send().onSuccess(res2->{
log.debug("response2: {}", res2.toString());
WebClient client = WebClient.create(Vertx.vertx());
WebClientSession webClientSession = WebClientSession.create(client);
webClientSession.getAbs("https://ip.ihuan.me").putHeaders(headers).send().onSuccess(res->{
System.out.println(res.toString());
webClientSession.getAbs("https://ip.ihuan.me").putHeaders(headers).send().onSuccess(res2->{
System.out.println(res2.toString());
});
});
@@ -21,11 +21,11 @@ import static cn.qaiu.util.AESUtils.encrypt;
*/
public class JsExecUtils {
private static final Invocable inv;
private static final ScriptEngineManager ENGINE_MANAGER = new ScriptEngineManager();
// 初始化脚本引擎
static {
ScriptEngine engine = ENGINE_MANAGER.getEngineByName("JavaScript"); // 得到脚本引擎
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("JavaScript"); // 得到脚本引擎
try {
engine.eval(JsContent.ye123);
@@ -45,63 +45,37 @@ public class JsExecUtils {
}
/**
* 调用执行蓝奏云js文件每次动态JS代码无法复用引擎
* 注意使用后清理引擎引用帮助 GC 回收 Nashorn 引擎内部资源
* 调用执行蓝奏云js文件
*/
public static ScriptObjectMirror executeDynamicJs(String jsText, String funName) throws ScriptException,
NoSuchMethodException {
ScriptEngine engine = ENGINE_MANAGER.getEngineByName("JavaScript"); // 得到脚本引擎
try {
engine.eval(JsContent.lz + "\n" + jsText);
Invocable inv = (Invocable) engine;
//调用js中的函数
if (StringUtils.isNotEmpty(funName)) {
inv.invokeFunction(funName);
}
return (ScriptObjectMirror) engine.get("signObj");
} finally {
// 清理引擎持有的引用帮助 GC 回收
clearEngineBindings(engine);
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("JavaScript"); // 得到脚本引擎
engine.eval(JsContent.lz + "\n" + jsText);
Invocable inv = (Invocable) engine;
//调用js中的函数
if (StringUtils.isNotEmpty(funName)) {
inv.invokeFunction(funName);
}
return (ScriptObjectMirror) engine.get("signObj");
}
/**
* 调用执行js文件使用缓存的 ScriptEngineManager 创建新引擎实例
* 注意使用后清理引擎引用帮助 GC 回收 Nashorn 引擎内部资源
* 调用执行蓝奏云js文件
*/
public static Object executeOtherJs(String jsText, String funName, Object ... args) throws ScriptException,
NoSuchMethodException {
ScriptEngine engine = ENGINE_MANAGER.getEngineByName("JavaScript"); // 得到脚本引擎
try {
engine.eval(jsText);
Invocable inv = (Invocable) engine;
//调用js中的函数
if (StringUtils.isNotEmpty(funName)) {
return inv.invokeFunction(funName, args);
}
throw new ScriptException("funName is null");
} finally {
// 清理引擎持有的引用帮助 GC 回收
clearEngineBindings(engine);
}
}
/**
* 清理 ScriptEngine bindings帮助 GC 回收 Nashorn 引擎资源
*/
private static void clearEngineBindings(ScriptEngine engine) {
try {
if (engine != null) {
// 清理全局 bindings
var bindings = engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
if (bindings != null) {
bindings.clear();
}
}
} catch (Exception ignored) {
// 清理失败不影响主流程
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("JavaScript"); // 得到脚本引擎
engine.eval(jsText);
Invocable inv = (Invocable) engine;
//调用js中的函数
if (StringUtils.isNotEmpty(funName)) {
return inv.invokeFunction(funName, args);
}
throw new ScriptException("funName is null");
}
public static String getKwSign(String s, String pwd) {
@@ -1,26 +1,22 @@
package cn.qaiu.util;
import cn.qaiu.WebClientVertxInit;
import io.vertx.core.AsyncResult;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.impl.headers.HeadersMultiMap;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReqIpUtil {
private static final Logger log = LoggerFactory.getLogger(ReqIpUtil.class);
public static final String BASE_URL = "https://ip.ihuan.me";
public static final String BASE_URL_TEMPLATE = BASE_URL + "/{path}";
public static String BASE_URL = "https://ip.ihuan.me";
public static String BASE_URL_TEMPLATE = BASE_URL + "/{path}";
// GET https://ip.ihuan.me/mouse.do -> $("input[name='key']").val("30b4975b5547fed806bd2b9caa18485a");
public static final String PATH1 = "mouse.do";
public static String PATH1 = "mouse.do";
public static final String PATH2 = "tqdl.html";
public static String PATH2 = "tqdl.html";
// 创建请求头Map
static MultiMap headers = new HeadersMultiMap();
@@ -47,28 +43,30 @@ public class ReqIpUtil {
}
// 使用共享的 Vertx 实例和 WebClient避免每次创建新实例导致资源泄漏
private static final WebClient WEB_CLIENT = WebClient.create(WebClientVertxInit.get());
private static final WebClientSession WEB_CLIENT_SESSION = WebClientSession.create(WEB_CLIENT);
Vertx vertx = Vertx.vertx();
WebClient webClient = WebClient.create(vertx);
// 发送GET请求
WebClientSession webClientSession = WebClientSession.create(webClient);
public void exec() {
WEB_CLIENT_SESSION.getAbs(BASE_URL)
webClientSession.getAbs(BASE_URL)
.putHeaders(headers) // 将请求头Map添加到请求中
.send(this::next);
}
void next(AsyncResult<HttpResponse<Buffer>> response) {
if (response.failed()) {
log.error("请求失败", response.cause());
response.cause().printStackTrace();
} else {
HttpResponse<Buffer> res = response.result();
log.debug("Received response with status code {}", res.statusCode());
log.debug("Body: {}", res.body());
WEB_CLIENT_SESSION.getAbs(BASE_URL_TEMPLATE).setTemplateParam("path", PATH1)
System.out.println("Received response with status code " + res.statusCode());
System.out.println("Body: " + res.body());
webClientSession.getAbs(BASE_URL_TEMPLATE).setTemplateParam("path", PATH1)
.putHeaders(headers) // 将请求头Map添加到请求中
.send(response2 -> {
log.debug("response2: {}", response2.result().bodyAsString());
System.out.println(response2.result().bodyAsString());
});
}
@@ -2,9 +2,6 @@ package cn.qaiu.util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
@@ -13,8 +10,6 @@ import java.util.Map;
public class URLUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(URLUtil.class);
private final Map<String, String> queryParams = new HashMap<>();
// 构造函数传入URL并解析参数
@@ -36,7 +31,7 @@ public class URLUtil {
}
}
} catch (Exception e) {
LOGGER.error("URL解析失败: {}", url, e);
e.printStackTrace();
}
}
@@ -1,84 +0,0 @@
package cn.qaiu.util;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* 123分享链接子域工具将分享 key 的前半段解码为数字 uid
*/
public final class YeShareHostUtil {
private static final String CODE62 = "Tvd3hHA9QEkom14xpfaBJIMwgFYGPXn2sWCNORDr80KuUSl7bZcetizL5q6yVj";
private static final long MAX_SAFE_INTEGER = 9007199254740991L;
private static final Map<Character, Integer> DECODE_MAP = new HashMap<>();
static {
for (int i = 0; i < CODE62.length(); i++) {
DECODE_MAP.put(CODE62.charAt(i), i);
}
}
private YeShareHostUtil() {
}
public static String getNumericSubdomainIdByShareKey(String shareKey) {
String normalized = normalizeShareKey(shareKey);
if (StringUtils.isBlank(normalized)) {
return "";
}
int split = normalized.indexOf('-');
if (split <= 0) {
return "";
}
String encodedUid = normalized.substring(0, split);
Long uid = decodeBase62LittleEndian(encodedUid);
return uid == null ? "" : String.valueOf(uid);
}
public static String normalizeShareKey(String shareKey) {
if (StringUtils.isBlank(shareKey)) {
return "";
}
String key = shareKey.trim();
int queryIndex = key.indexOf('?');
if (queryIndex >= 0) {
key = key.substring(0, queryIndex);
}
int slashIndex = key.lastIndexOf('/');
if (slashIndex >= 0 && slashIndex < key.length() - 1) {
key = key.substring(slashIndex + 1);
}
if (key.endsWith(".html")) {
key = key.substring(0, key.length() - 5);
}
return key;
}
private static Long decodeBase62LittleEndian(String value) {
if (StringUtils.isBlank(value)) {
return null;
}
long result = 0L;
for (int i = 0; i < value.length(); i++) {
Integer digit = DECODE_MAP.get(value.charAt(i));
if (digit == null) {
return null;
}
double weighted = digit * Math.pow(62, i);
if (!Double.isFinite(weighted)) {
return null;
}
long next = result + (long) weighted;
if (next <= 0 || next > MAX_SAFE_INTEGER) {
return null;
}
result = next;
}
if (result <= 0) {
return null;
}
return result;
}
}
@@ -134,8 +134,8 @@ HTTP客户端对象:
http.get(url) // GET请求
http.post(url, data) // POST请求
http.putHeader(name, value) // 设置请求头
http.sendForm(url, data) // 发送表单数据
http.sendJson(url, data) // 发送JSON数据
http.sendForm(data) // 发送表单数据
http.sendJson(data) // 发送JSON数据
```
### JsHttpResponse
@@ -89,9 +89,9 @@ var java;
* @property {function(): JsHttpClient} clearHeaders - 清空所有请求头保留默认头
* @property {function(): Object} getHeaders - 获取所有请求头
* @property {function(number): JsHttpClient} setTimeout - 设置请求超时时间
* @property {function(string, Object): JsHttpResponse} sendForm - 发送简单表单数据
* @property {function(Object): JsHttpResponse} sendForm - 发送简单表单数据
* @property {function(string, Object): JsHttpResponse} sendMultipartForm - 发送multipart表单数据仅支持文本字段
* @property {function(string, any): JsHttpResponse} sendJson - 发送JSON数据
* @property {function(any): JsHttpResponse} sendJson - 发送JSON数据
* @property {function(string): string} urlEncode - URL编码静态方法
* @property {function(string): string} urlDecode - URL解码静态方法
*/
+3 -3
View File
@@ -37,10 +37,10 @@
<!-- 将文件输出设置成异步输出 -->
<appender name="ASYNC-FILE" class="ch.qos.logback.classic.AsyncAppender">
<!-- 队列剩余 20% 时开始丢弃 TRACE/DEBUG/INFO 级别日志,避免阻塞调用线程 -->
<discardingThreshold>20</discardingThreshold>
<!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUGINFO级别日志 -->
<discardingThreshold>0</discardingThreshold>
<!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
<queueSize>512</queueSize>
<queueSize>256</queueSize>
<!-- 添加附加的appender,最多只能添加一个 -->
<appender-ref ref="FILE"/>
</appender>
@@ -8,8 +8,6 @@ import cn.qaiu.parser.customjs.JsParserExecutor;
import cn.qaiu.WebClientVertxInit;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
@@ -24,26 +22,15 @@ import java.util.Map;
*/
public class BaiduPhotoParserTest {
private Vertx vertx;
@Before
public void setUp() {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
}
@After
public void tearDown() {
if (vertx != null) {
vertx.close();
}
}
@Test
public void testBaiduPhotoParserRegistration() {
// 清理注册表
CustomParserRegistry.clear();
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
// 检查是否加载了百度相册解析器
CustomParserConfig config = CustomParserRegistry.get("baidu_photo");
assert config != null : "百度相册解析器未加载";
@@ -57,7 +44,11 @@ public class BaiduPhotoParserTest {
public void testBaiduPhotoFileShareExecution() {
// 清理注册表
CustomParserRegistry.clear();
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
try {
// 创建解析器 - 测试文件分享链接
IPanTool tool = ParserCreate.fromType("baidu_photo")
@@ -85,7 +76,11 @@ public class BaiduPhotoParserTest {
public void testBaiduPhotoFolderShareExecution() {
// 清理注册表
CustomParserRegistry.clear();
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
try {
// 创建解析器 - 测试文件夹分享链接
IPanTool tool = ParserCreate.fromType("baidu_photo")
@@ -113,7 +108,11 @@ public class BaiduPhotoParserTest {
public void testBaiduPhotoParserFileList() {
// 清理注册表
CustomParserRegistry.clear();
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
try {
IPanTool tool = ParserCreate.fromType("baidu_photo")
// 分享key PPgOEodBVE
@@ -167,7 +166,11 @@ public class BaiduPhotoParserTest {
public void testBaiduPhotoParserById() {
// 清理注册表
CustomParserRegistry.clear();
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
try {
// 创建ShareLinkInfo
Map<String, Object> otherParam = new HashMap<>();
@@ -7,8 +7,6 @@ import cn.qaiu.parser.custom.CustomParserRegistry;
import cn.qaiu.parser.customjs.JsParserExecutor;
import cn.qaiu.WebClientVertxInit;
import io.vertx.core.Vertx;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
@@ -23,26 +21,15 @@ import java.util.Map;
*/
public class JsParserTest {
private Vertx vertx;
@Before
public void setUp() {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
}
@After
public void tearDown() {
if (vertx != null) {
vertx.close();
}
}
@Test
public void testJsParserRegistration() {
// 清理注册表
CustomParserRegistry.clear();
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
// 检查是否加载了JavaScript解析器
CustomParserConfig config = CustomParserRegistry.get("demo_js");
assert config != null : "JavaScript解析器未加载";
@@ -56,7 +43,11 @@ public class JsParserTest {
public void testJsParserExecution() {
// 清理注册表
CustomParserRegistry.clear();
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
try {
// 创建解析器
IPanTool tool = ParserCreate.fromType("demo_js")
@@ -83,7 +74,11 @@ public class JsParserTest {
public void testJsParserFileList() {
// 清理注册表
CustomParserRegistry.clear();
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
try {
// 创建解析器
IPanTool tool = ParserCreate.fromType("demo_js")
@@ -119,7 +114,11 @@ public class JsParserTest {
public void testJsParserById() {
// 清理注册表
CustomParserRegistry.clear();
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
try {
// 创建ShareLinkInfo
Map<String, Object> otherParam = new HashMap<>();
@@ -1,7 +1,6 @@
package cn.qaiu.parser;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.util.YeShareHostUtil;
import org.junit.Test;
import java.util.Arrays;
@@ -158,26 +157,6 @@ public class PanDomainTemplateTest {
assertEquals("somekey", m5.group("KEY"));
}
@Test
public void testYeRedirectPatternAndUidDecode() {
Pattern yePattern = PanDomainTemplate.YE.getPattern();
Matcher oldUrl = yePattern.matcher("https://www.123pan.com/s/lN7UVv-pbYJ");
assertTrue("YE should match old 123pan share URL", oldUrl.find());
assertEquals("lN7UVv-pbYJ", oldUrl.group("KEY"));
Matcher redirectedUrl = yePattern.matcher("https://1813382308.mshare.123pan.cn/123pan/lN7UVv-pbYJ");
assertTrue("YE should match redirected mshare URL", redirectedUrl.find());
assertEquals("lN7UVv-pbYJ", redirectedUrl.group("KEY"));
Matcher htmlUrl = yePattern.matcher("https://www.123278.com/s/lN7UVv-pbYJ.html?pwd=abcd");
assertTrue("YE should match html URL with query", htmlUrl.find());
assertEquals("lN7UVv-pbYJ", htmlUrl.group("KEY"));
assertEquals("1813382308", YeShareHostUtil.getNumericSubdomainIdByShareKey("lN7UVv-pbYJ"));
assertEquals("lN7UVv-pbYJ", YeShareHostUtil.normalizeShareKey("https://1813382308.mshare.123pan.cn/123pan/lN7UVv-pbYJ?pwd=abcd"));
}
@Test
public void testLePatternFix() {
Pattern lePattern = PanDomainTemplate.LE.getPattern();
@@ -7,8 +7,6 @@ import cn.qaiu.parser.ParserCreate;
import cn.qaiu.parser.custom.CustomParserConfig;
import cn.qaiu.parser.custom.CustomParserRegistry;
import io.vertx.core.Vertx;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -18,29 +16,18 @@ import org.slf4j.LoggerFactory;
* 测试fetch API和Promise polyfill功能
*/
public class JsFetchBridgeTest {
private static final Logger log = LoggerFactory.getLogger(JsFetchBridgeTest.class);
private Vertx vertx;
@Before
public void setUp() {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
}
@After
public void tearDown() {
if (vertx != null) {
vertx.close();
}
}
@Test
public void testFetchPolyfillLoaded() {
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
// 清理注册表
CustomParserRegistry.clear();
// 创建一个简单的解析器配置
String jsCode = """
// 测试Promise是否可用
@@ -96,9 +83,13 @@ public class JsFetchBridgeTest {
@Test
public void testPromiseBasicUsage() {
// 初始化Vertx
Vertx vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
// 清理注册表
CustomParserRegistry.clear();
String jsCode = """
function parse(shareLinkInfo, http, logger) {
logger.info("测试Promise基本用法");
-329
View File
@@ -1,329 +0,0 @@
// ==FetchRuntime==
// @name Fetch API Polyfill for ES5
// @description Fetch API and Promise implementation for ES5 JavaScript engines
// @version 1.0.0
// @author QAIU
// ==============
/**
* Simple Promise implementation compatible with ES5
* Supports basic Promise functionality needed for fetch API
*/
function SimplePromise(executor) {
var state = 'pending';
var value;
var handlers = [];
var self = this;
function resolve(result) {
if (state !== 'pending') return;
state = 'fulfilled';
value = result;
handlers.forEach(handle);
handlers = [];
}
function reject(err) {
if (state !== 'pending') return;
state = 'rejected';
value = err;
handlers.forEach(handle);
handlers = [];
}
function handle(handler) {
if (state === 'pending') {
handlers.push(handler);
} else {
setTimeout(function() {
if (state === 'fulfilled' && typeof handler.onFulfilled === 'function') {
try {
var result = handler.onFulfilled(value);
if (result && typeof result.then === 'function') {
result.then(handler.resolve, handler.reject);
} else {
handler.resolve(result);
}
} catch (e) {
handler.reject(e);
}
}
if (state === 'rejected' && typeof handler.onRejected === 'function') {
try {
var result = handler.onRejected(value);
if (result && typeof result.then === 'function') {
result.then(handler.resolve, handler.reject);
} else {
handler.resolve(result);
}
} catch (e) {
handler.reject(e);
}
} else if (state === 'rejected' && !handler.onRejected) {
handler.reject(value);
}
}, 0);
}
}
this.then = function(onFulfilled, onRejected) {
return new SimplePromise(function(resolveNext, rejectNext) {
handle({
onFulfilled: onFulfilled,
onRejected: onRejected,
resolve: resolveNext,
reject: rejectNext
});
});
};
this['catch'] = function(onRejected) {
return this.then(null, onRejected);
};
this['finally'] = function(onFinally) {
return this.then(
function(value) {
return SimplePromise.resolve(onFinally()).then(function() {
return value;
});
},
function(reason) {
return SimplePromise.resolve(onFinally()).then(function() {
throw reason;
});
}
);
};
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
// Static methods
SimplePromise.resolve = function(value) {
if (value && typeof value.then === 'function') {
return value;
}
return new SimplePromise(function(resolve) {
resolve(value);
});
};
SimplePromise.reject = function(reason) {
return new SimplePromise(function(resolve, reject) {
reject(reason);
});
};
SimplePromise.all = function(promises) {
return new SimplePromise(function(resolve, reject) {
var results = [];
var remaining = promises.length;
if (remaining === 0) {
resolve(results);
return;
}
function handleResult(index, value) {
results[index] = value;
remaining--;
if (remaining === 0) {
resolve(results);
}
}
for (var i = 0; i < promises.length; i++) {
(function(index) {
var promise = promises[index];
if (promise && typeof promise.then === 'function') {
promise.then(
function(value) { handleResult(index, value); },
reject
);
} else {
handleResult(index, promise);
}
})(i);
}
});
};
SimplePromise.race = function(promises) {
return new SimplePromise(function(resolve, reject) {
if (promises.length === 0) {
// Per spec, Promise.race with empty array stays pending forever
return;
}
for (var i = 0; i < promises.length; i++) {
var promise = promises[i];
if (promise && typeof promise.then === 'function') {
promise.then(resolve, reject);
} else {
resolve(promise);
return;
}
}
});
};
// Make Promise global if not already defined
if (typeof Promise === 'undefined') {
var Promise = SimplePromise;
}
/**
* Response object that mimics the Fetch API Response
*/
function FetchResponse(jsHttpResponse) {
this._jsResponse = jsHttpResponse;
this.status = jsHttpResponse.statusCode();
this.ok = this.status >= 200 && this.status < 300;
// Map HTTP status codes to standard status text
var statusTexts = {
200: 'OK',
201: 'Created',
204: 'No Content',
301: 'Moved Permanently',
302: 'Found',
304: 'Not Modified',
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout'
};
this.statusText = statusTexts[this.status] || (this.ok ? 'OK' : 'Error');
this.headers = {
get: function(name) {
return jsHttpResponse.header(name);
},
has: function(name) {
return jsHttpResponse.header(name) !== null;
},
entries: function() {
var headerMap = jsHttpResponse.headers();
var entries = [];
for (var key in headerMap) {
if (headerMap.hasOwnProperty(key)) {
entries.push([key, headerMap[key]]);
}
}
return entries;
}
};
}
FetchResponse.prototype.text = function() {
var body = this._jsResponse.body();
return SimplePromise.resolve(body || '');
};
FetchResponse.prototype.json = function() {
var self = this;
return this.text().then(function(text) {
try {
return JSON.parse(text);
} catch (e) {
throw new Error('Invalid JSON: ' + e.message);
}
});
};
FetchResponse.prototype.arrayBuffer = function() {
var bytes = this._jsResponse.bodyBytes();
return SimplePromise.resolve(bytes);
};
FetchResponse.prototype.blob = function() {
// Blob not supported in ES5, return bytes
return this.arrayBuffer();
};
/**
* Fetch API implementation using JavaFetch bridge
* @param {string} url - Request URL
* @param {Object} options - Fetch options (method, headers, body, etc.)
* @returns {Promise<FetchResponse>}
*/
function fetch(url, options) {
return new SimplePromise(function(resolve, reject) {
try {
// Parse options
options = options || {};
var method = (options.method || 'GET').toUpperCase();
var headers = options.headers || {};
var body = options.body;
// Prepare request options for JavaFetch
var requestOptions = {
method: method,
headers: {}
};
// Convert headers to simple object
if (headers) {
if (typeof headers.forEach === 'function') {
// Headers object
headers.forEach(function(value, key) {
requestOptions.headers[key] = value;
});
} else if (typeof headers === 'object') {
// Plain object
for (var key in headers) {
if (headers.hasOwnProperty(key)) {
requestOptions.headers[key] = headers[key];
}
}
}
}
// Add body if present
if (body !== undefined && body !== null) {
if (typeof body === 'string') {
requestOptions.body = body;
} else if (typeof body === 'object') {
// Assume JSON
requestOptions.body = JSON.stringify(body);
if (!requestOptions.headers['Content-Type'] && !requestOptions.headers['content-type']) {
requestOptions.headers['Content-Type'] = 'application/json';
}
}
}
// Call JavaFetch bridge
var jsHttpResponse = JavaFetch.fetch(url, requestOptions);
// Create Response object
var response = new FetchResponse(jsHttpResponse);
resolve(response);
} catch (e) {
reject(e);
}
});
}
// Export for global use
if (typeof window !== 'undefined') {
window.fetch = fetch;
window.Promise = Promise;
} else if (typeof global !== 'undefined') {
global.fetch = fetch;
global.Promise = Promise;
}
+5 -6
View File
@@ -17,7 +17,7 @@
</modules>
<properties>
<revision>0.3.4</revision>
<revision>0.2.1</revision>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
@@ -25,17 +25,16 @@
<packageDirectory>${project.basedir}/web-service/target/package</packageDirectory>
<!-- Vert.x 4.5.27 包含安全修复,无需单独指定 Netty 版本 -->
<vertx.version>4.5.27</vertx.version>
<!-- Vert.x 4.5.24 已包含安全修复,无需单独指定 Netty 版本 -->
<vertx.version>4.5.24</vertx.version>
<org.reflections.version>0.10.2</org.reflections.version>
<lombok.version>1.18.38</lombok.version>
<slf4j.version>2.0.16</slf4j.version>
<commons-lang3.version>3.18.0</commons-lang3.version>
<commons-beanutils2.version>2.0.0</commons-beanutils2.version>
<parserVersion>10.2.5</parserVersion>
<jackson.version>2.18.6</jackson.version>
<!-- Logback 最新稳定版 -->
<logback.version>1.5.32</logback.version>
<logback.version>1.5.18</logback.version>
<junit.version>4.13.2</junit.version>
</properties>
@@ -75,7 +74,7 @@
<dependency>
<groupId>cn.qaiu</groupId>
<artifactId>parser</artifactId>
<version>${parserVersion}</version>
<version>10.2.5</version>
</dependency>
</dependencies>
</dependencyManagement>
+3 -3
View File
@@ -5,15 +5,15 @@
"scripts": {
"serve": "vue-cli-service serve",
"dev": "vue-cli-service serve",
"build": "node scripts/sync-version.js && vue-cli-service build && node scripts/compress-vs.js",
"build:no-compress": "node scripts/sync-version.js && vue-cli-service build",
"build": "vue-cli-service build && node scripts/compress-vs.js",
"build:no-compress": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.1",
"@monaco-editor/loader": "^1.4.0",
"@vueuse/core": "^11.2.0",
"axios": "1.16.1",
"axios": "1.13.5",
"clipboard": "^2.0.11",
"core-js": "^3.8.3",
"crypto-js": "^4.2.0",
+1 -1
View File
@@ -10,7 +10,7 @@
<meta name="description"
content="Netdisk fast download 网盘直链解析工具">
<!-- Font Awesome 图标库 - 使用国内CDN -->
<link rel="stylesheet" href="https://s4.zstatic.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- 迅雷 JS-SDK -->
<script src="//open.thunderurl.com/thunder-link.js"></script>
<style>
+11 -54
View File
@@ -511,7 +511,6 @@
files.forEach(file => {
const item = document.createElement('div');
const metaText = fileMetaText(file);
if (file.fileType === 'folder') {
// 文件夹
@@ -521,7 +520,9 @@
<i class="fas fa-folder"></i>
</div>
<div class="item-name">${file.fileName || '未命名文件夹'}</div>
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
<div class="item-meta">
${file.sizeStr || '0B'} · ${formatDate(file.createTime)}
</div>
`;
folderCount++;
@@ -540,7 +541,9 @@
<i class="fas ${fileTypeInfo.icon}"></i>
</div>
<div class="item-name">${file.fileName}</div>
${metaText ? `<div class="item-meta">${metaText}</div>` : ''}
<div class="item-meta">
${file.sizeStr || '0B'} · ${formatDate(file.createTime)}
</div>
`;
fileCount++;
@@ -672,65 +675,19 @@
renderBreadcrumb();
}
// 文件元信息
function fileMetaText(file) {
const parts = [];
if (file.fileType !== 'folder') {
parts.push(file.sizeStr || '0B');
}
const dateText = formatDate(file.createTime);
if (dateText) {
parts.push(dateText);
}
return parts.join(' · ');
}
function hasValidTime(value) {
if (value === null || value === undefined) return false;
if (typeof value !== 'string') return true;
const trimmedValue = value.trim();
return trimmedValue !== '' && trimmedValue !== 'null' && trimmedValue !== 'undefined';
}
function formatDateOnly(yearValue, monthValue, dayValue) {
const year = Number(yearValue);
const month = Number(monthValue);
const day = Number(dayValue);
const date = new Date(year, month - 1, day);
if (
date.getFullYear() !== year ||
date.getMonth() !== month - 1 ||
date.getDate() !== day
) {
return '';
}
return `${yearValue}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}
// 格式化日期
function formatDate(dateString) {
if (!hasValidTime(dateString)) return '';
if (!dateString) return '未知日期';
try {
const value = typeof dateString === 'string' ? dateString.trim() : dateString;
if (typeof value === 'string') {
const dateOnly = value.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/);
if (dateOnly) {
return formatDateOnly(dateOnly[1], dateOnly[2], dateOnly[3]);
}
const cnDateOnly = value.match(/^(\d{4})年\s*(\d{1,2})月\s*(\d{1,2})日$/);
if (cnDateOnly) {
return formatDateOnly(cnDateOnly[1], cnDateOnly[2], cnDateOnly[3]);
}
}
const date = new Date(value);
const date = new Date(dateString);
return isNaN(date.getTime())
? ''
? '未知日期'
: `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
} catch {
return '';
return '未知日期';
}
}
</script>
</body>
</html>
</html>
-23
View File
@@ -1,23 +0,0 @@
const fs = require('fs');
const path = require('path');
const pomPath = path.resolve(__dirname, '../../pom.xml');
const pkgPath = path.resolve(__dirname, '../package.json');
const pomContent = fs.readFileSync(pomPath, 'utf-8');
const match = pomContent.match(/<revision>([^<]+)<\/revision>/);
if (!match) {
console.error('sync-version: <revision> not found in root pom.xml');
process.exit(1);
}
const version = match[1];
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
if (pkg.version === version) {
console.log(`sync-version: package.json already at ${version}`);
process.exit(0);
}
pkg.version = version;
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
console.log(`sync-version: package.json ${pkg.version} -> ${version}`);
+1
View File
@@ -36,6 +36,7 @@ if (item) {
const darkMode = ref(item)
watch(darkMode, (newValue) => {
console.log(`darkMode: ${newValue}`)
window.localStorage.setItem("darkMode", newValue);
//
+19 -133
View File
@@ -32,8 +32,8 @@
<i :class="getFileIcon(file)"></i>
</div>
<div class="file-name">{{ file.fileName }}</div>
<div v-if="fileMetaText(file)" class="file-meta">
{{ fileMetaText(file) }}
<div class="file-meta">
<template v-if="file.fileType !== 'folder'">{{ file.sizeStr || '0B' }} · </template>{{ formatDate(file.createTime) }}
</div>
</div>
<div v-if="!loading && (!currentFileList || currentFileList.length === 0)" class="empty-state">
@@ -168,8 +168,7 @@
<div v-if="selectedNode.fileType !== 'folder'" class="file-detail-meta">
<p>类型: {{ getFileTypeClass(selectedNode) }}</p>
<p>大小: {{ selectedNode.sizeStr || '0B' }}</p>
<p v-if="formatDate(selectedNode.createTime)">创建时间: {{ formatDate(selectedNode.createTime) }}</p>
<p v-if="formatDate(selectedNode.updateTime)">更新时间: {{ formatDate(selectedNode.updateTime) }}</p>
<p v-if="selectedNode.createTime">创建时间: {{ formatDate(selectedNode.createTime) }}</p>
</div>
<div class="file-detail-actions">
<el-button v-if="selectedNode.parserUrl" size="small" @click="previewFile(selectedNode)">
@@ -191,14 +190,6 @@
>
<i class="fas fa-paper-plane"></i> 发送到下载器
</el-button>
<el-button
v-if="selectedNode.parserUrl"
size="small"
@click="copyDirectLink(selectedNode)"
:loading="copyLinkLoading"
>
<i class="fas fa-link"></i> 复制直链
</el-button>
</div>
</div>
<div v-else class="file-detail-empty">
@@ -245,8 +236,7 @@
<div v-if="selectedNode.fileType !== 'folder'" class="file-detail-meta">
<p>类型: {{ getFileTypeClass(selectedNode) }}</p>
<p>大小: {{ selectedNode.sizeStr || '0B' }}</p>
<p v-if="formatDate(selectedNode.createTime)">创建时间: {{ formatDate(selectedNode.createTime) }}</p>
<p v-if="formatDate(selectedNode.updateTime)">更新时间: {{ formatDate(selectedNode.updateTime) }}</p>
<p v-if="selectedNode.createTime">创建时间: {{ formatDate(selectedNode.createTime) }}</p>
</div>
<div class="file-detail-actions">
<el-button v-if="selectedNode.parserUrl" size="small" @click="previewFile(selectedNode)">
@@ -268,14 +258,6 @@
>
<i class="fas fa-paper-plane"></i> 发送到下载器
</el-button>
<el-button
v-if="selectedNode.parserUrl"
size="small"
@click="copyDirectLink(selectedNode)"
:loading="copyLinkLoading"
>
<i class="fas fa-link"></i> 复制直链
</el-button>
</div>
</div>
<div v-else class="file-detail-empty">
@@ -316,9 +298,8 @@
<div class="file-dialog-content">
<p><strong>{{ selectedFile?.fileName || '未命名文件' }}</strong></p>
<p class="file-info">
<template v-for="(line, index) in selectedFileInfoLines" :key="index">
{{ line }}<br v-if="index < selectedFileInfoLines.length - 1">
</template>
大小: {{ selectedFile?.sizeStr || '0B' }}<br>
创建时间: {{ formatDate(selectedFile?.createTime) }}
</p>
</div>
@@ -343,14 +324,6 @@
>
发送到下载器
</el-button>
<el-button
v-if="selectedFile && selectedFile.parserUrl"
@click="copyDirectLink(selectedFile)"
style="margin-left: 8px;"
:loading="copyLinkLoading"
>
复制直链
</el-button>
</span>
</el-dialog>
<div v-if="isPreviewing" class="preview-mask">
@@ -418,7 +391,6 @@ export default {
downloadInfo: null,
downloadLoading: false,
singleSendLoading: false,
copyLinkLoading: false,
treeProps: {
label: 'fileName',
children: 'children',
@@ -447,19 +419,6 @@ export default {
if (this.batchProgress.failed > 0) return 'exception'
if (this.batchProgress.current >= this.batchProgress.total && this.batchProgress.total > 0) return 'success'
return ''
},
selectedFileInfoLines() {
if (!this.selectedFile) return []
const lines = [`大小: ${this.selectedFile.sizeStr || '0B'}`]
const createTime = this.formatDate(this.selectedFile.createTime)
const updateTime = this.formatDate(this.selectedFile.updateTime)
if (createTime) {
lines.push(`创建时间: ${createTime}`)
}
if (updateTime) {
lines.push(`更新时间: ${updateTime}`)
}
return lines
}
},
watch: {
@@ -503,6 +462,10 @@ export default {
}
return `${baseUrl}?${params.toString()}`
},
//
buildTree(list) {
return list || []
},
//
loadNode(node, resolve) {
if (node.level === 0) {
@@ -516,14 +479,9 @@ export default {
}))
resolve(children)
} else {
this.$message.error(res.data.msg || '获取子节点失败')
resolve([])
}
}).catch(err => {
const msg = err.response?.data?.msg || err.message
if (msg) this.$message.error(msg)
resolve([])
})
}).catch(() => resolve([]))
} else {
resolve([])
}
@@ -533,6 +491,7 @@ export default {
},
//
handleFileClick(file) {
console.log('点击文件', file, this.viewMode)
if (file.fileType === 'folder') {
this.enterFolder(file)
} else if (this.viewMode === 'pane') {
@@ -561,8 +520,7 @@ export default {
}
} catch (error) {
console.error('进入文件夹失败:', error)
const msg = error.response?.data?.msg || error.message || '进入文件夹失败'
this.$message.error(msg)
this.$message.error('进入文件夹失败')
} finally {
this.loading = false
}
@@ -593,8 +551,7 @@ export default {
}
} catch (error) {
console.error('加载目录失败:', error)
const msg = error.response?.data?.msg || error.message || '加载目录失败'
this.$message.error(msg)
this.$message.error('加载目录失败')
} finally {
this.loading = false
}
@@ -692,8 +649,7 @@ export default {
}
} catch (error) {
console.error('获取下载信息失败:', error)
const msg = error.response?.data?.msg || '获取下载信息失败,尝试直接下载'
this.$message.error(msg)
this.$message.error('获取下载信息失败,尝试直接下载')
this.downloadFile(file)
} finally {
this.downloadLoading = false
@@ -779,8 +735,7 @@ export default {
}
} catch (error) {
console.error('发送到下载器失败:', error)
const msg = error.response?.data?.msg || error.message || '发送到下载器失败'
this.$message.error(msg)
this.$message.error('发送到下载器失败: ' + error.message)
} finally {
this.singleSendLoading = false
}
@@ -789,32 +744,6 @@ export default {
this.fileDialogVisible = false
this.selectedFile = null
},
async copyDirectLink(file) {
if (!file?.parserUrl) {
this.$message.warning('该文件暂无直链')
return
}
const rawUrl = file.parserUrl.startsWith('http') ? file.parserUrl : (window.location.origin + file.parserUrl)
const url = this.appendToken(rawUrl)
this.copyLinkLoading = true
try {
await navigator.clipboard.writeText(url)
this.$message.success('直链已复制到剪贴板')
} catch {
// fallback
const ta = document.createElement('textarea')
ta.value = url
ta.style.position = 'fixed'
ta.style.opacity = '0'
document.body.appendChild(ta)
ta.select()
document.execCommand('copy')
document.body.removeChild(ta)
this.$message.success('直链已复制到剪贴板')
} finally {
this.copyLinkLoading = false
}
},
closePreview() {
this.isPreviewing = false
this.previewUrl = ''
@@ -831,54 +760,11 @@ export default {
document.body.removeChild(a)
}
},
hasValidTime(value) {
if (value === null || value === undefined) return false
if (typeof value !== 'string') return true
const trimmedValue = value.trim()
return trimmedValue !== '' && trimmedValue !== 'null' && trimmedValue !== 'undefined'
},
formatDateOnly(yearValue, monthValue, dayValue) {
const year = Number(yearValue)
const month = Number(monthValue)
const day = Number(dayValue)
const date = new Date(year, month - 1, day)
if (
date.getFullYear() !== year ||
date.getMonth() !== month - 1 ||
date.getDate() !== day
) {
return ''
}
return `${yearValue}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
},
formatDate(timestamp) {
if (!this.hasValidTime(timestamp)) return ''
const value = typeof timestamp === 'string' ? timestamp.trim() : timestamp
if (typeof value === 'string') {
const dateOnly = value.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/)
if (dateOnly) {
return this.formatDateOnly(dateOnly[1], dateOnly[2], dateOnly[3])
}
const cnDateOnly = value.match(/^(\d{4})年\s*(\d{1,2})月\s*(\d{1,2})日$/)
if (cnDateOnly) {
return this.formatDateOnly(cnDateOnly[1], cnDateOnly[2], cnDateOnly[3])
}
}
const date = new Date(value)
if (Number.isNaN(date.getTime())) return ''
if (!timestamp) return '未知时间'
const date = new Date(timestamp)
return date.toLocaleString('zh-CN')
},
fileMetaText(file) {
const parts = []
if (file.fileType !== 'folder') {
parts.push(file.sizeStr || '0B')
}
const timeText = this.formatDate(file.createTime)
if (timeText) {
parts.push(timeText)
}
return parts.join(' · ')
},
checkTheme() {
this.isDarkTheme = document.documentElement.classList.contains('dark')
},
@@ -916,7 +802,7 @@ export default {
this.toggleFileSelect(file)
},
selectAll() {
this.selectedFiles = this.currentFileList.filter(f => f.fileType !== 'folder' && f.parserUrl)
this.selectedFiles = this.currentFileList.filter(f => f.fileType !== 'folder')
},
deselectAll() {
this.selectedFiles = []
+2 -2
View File
@@ -238,8 +238,8 @@
storage: 'hash'
},
'ctfile': {
reg: /((?:https?:\/\/)?(?:[a-zA-Z\d-.]+)?(?:ctfile|545c|u062|ghpym|474b)\.com\/(?:f(?:ile)?|d)\/[a-zA-Z\d_-]+\/?(?:\?[^#\s]*)?)/,
host: /(?:[a-zA-Z\d-.]+)?(?:ctfile|545c|u062|ghpym|474b)\.com/,
reg: /((?:https?:\/\/)?(?:[a-zA-Z\d-.]+)?(?:ctfile|545c|u062|ghpym|474b)\.com\/\w+\/[a-zA-Z\d-]+)/,
host: /(?:[a-zA-Z\d-.]+)?(?:ctfile|545c|u062|474b)\.com/,
input: ['#passcode'],
button: ['.card-body button'],
name: '城通网盘',
+125
View File
@@ -0,0 +1,125 @@
import axios from 'axios'
// 创建 axios 实例
const api = axios.create({
baseURL: process.env.VUE_APP_API_BASE_URL || 'http://localhost:6400',
timeout: 30000,
headers: {
'Content-Type': 'application/json'
}
})
// 请求拦截器
api.interceptors.request.use(
config => {
// 可以在这里添加认证token等
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截器
api.interceptors.response.use(
response => {
return response.data
},
error => {
console.error('API请求错误:', error)
if (error.response) {
// 服务器返回错误状态码
const message = error.response.data?.message || error.response.data?.error || '服务器错误'
return Promise.reject(new Error(message))
} else if (error.request) {
// 网络错误
return Promise.reject(new Error('网络连接失败,请检查网络设置'))
} else {
// 其他错误
return Promise.reject(new Error(error.message || '请求失败'))
}
}
)
// 客户端链接 API
export const clientLinksApi = {
/**
* 获取所有客户端下载链接
* @param {string} shareUrl - 分享链接
* @param {string} password - 提取码可选
* @returns {Promise} 客户端链接响应
*/
async getClientLinks(shareUrl, password = '') {
const params = new URLSearchParams()
params.append('url', shareUrl)
if (password) {
params.append('pwd', password)
}
return await api.get(`/v2/clientLinks?${params.toString()}`)
},
/**
* 获取指定类型的客户端下载链接
* @param {string} shareUrl - 分享链接
* @param {string} password - 提取码可选
* @param {string} clientType - 客户端类型
* @returns {Promise} 指定类型的客户端链接
*/
async getClientLink(shareUrl, password = '', clientType) {
const params = new URLSearchParams()
params.append('url', shareUrl)
if (password) {
params.append('pwd', password)
}
params.append('clientType', clientType)
return await api.get(`/v2/clientLink?${params.toString()}`)
}
}
// 其他 API(如果需要的话)
export const parserApi = {
/**
* 解析分享链接
* @param {string} shareUrl - 分享链接
* @param {string} password - 提取码可选
* @returns {Promise} 解析结果
*/
async parseLink(shareUrl, password = '') {
const params = new URLSearchParams()
params.append('url', shareUrl)
if (password) {
params.append('pwd', password)
}
return await api.get(`/v2/linkInfo?${params.toString()}`)
},
/**
* 获取文件列表
* @param {string} shareUrl - 分享链接
* @param {string} password - 提取码可选
* @param {string} dirId - 目录ID可选
* @param {string} uuid - UUID可选
* @returns {Promise} 文件列表
*/
async getFileList(shareUrl, password = '', dirId = '', uuid = '') {
const params = new URLSearchParams()
params.append('url', shareUrl)
if (password) {
params.append('pwd', password)
}
if (dirId) {
params.append('dirId', dirId)
}
if (uuid) {
params.append('uuid', uuid)
}
return await api.get(`/v2/getFileList?${params.toString()}`)
}
}
export default api
-6
View File
@@ -1,6 +0,0 @@
/**
* 前端全局常量
*/
/** 预览服务基础 URL */
export const PREVIEW_BASE_URL = 'https://nfd-parser.github.io/nfd-preview/preview.html?src='
+1
View File
@@ -410,6 +410,7 @@ function addThunderDownload(tasks, config) {
if (userAgent) taskParam.userAgent = userAgent
taskParam.threadCount = '1'
console.log('[Thunder SDK] newTask params:', JSON.stringify(taskParam))
window.thunderLink.newTask(taskParam)
return Promise.resolve('thunder-ok')
}
+9 -6
View File
@@ -83,9 +83,9 @@ function registerTypeDefinitions(monaco) {
clearHeaders(): JsHttpClient;
getHeaders(): Record<string, string>;
setTimeout(seconds: number): JsHttpClient;
sendForm(url: string, data: Record<string, any>): JsHttpResponse;
sendForm(data: Record<string, any>): JsHttpResponse;
sendMultipartForm(url: string, data: Record<string, any>): JsHttpResponse;
sendJson(url: string, data: any): JsHttpResponse;
sendJson(data: any): JsHttpResponse;
urlEncode(str: string): string;
urlDecode(str: string): string;
}
@@ -244,17 +244,17 @@ function registerCompletionProvider(monaco) {
range
},
{
label: 'http.sendForm(url, data)',
label: 'http.sendForm(data)',
kind: monaco.languages.CompletionItemKind.Method,
insertText: 'http.sendForm(${1:url}, ${2:data})',
insertText: 'http.sendForm(${1:data})',
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: '发送表单数据',
range
},
{
label: 'http.sendJson(url, data)',
label: 'http.sendJson(data)',
kind: monaco.languages.CompletionItemKind.Method,
insertText: 'http.sendJson(${1:url}, ${2:data})',
insertText: 'http.sendJson(${1:data})',
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
documentation: '发送JSON数据',
range
@@ -313,6 +313,7 @@ export async function loadTypesFromApi(monaco) {
cachedContent,
'file:///types.js'
);
console.log('从缓存加载types.js成功');
// 异步更新缓存
updateTypesJsCache();
return;
@@ -333,6 +334,7 @@ export async function loadTypesFromApi(monaco) {
typesJsContent,
'file:///types.js'
);
console.log('加载types.js成功并已缓存');
}
} catch (error) {
console.warn('加载types.js失败,使用内置类型定义:', error);
@@ -348,6 +350,7 @@ async function updateTypesJsCache() {
if (response.ok) {
const typesJsContent = await response.text();
localStorage.setItem('playground_types_js', typesJsContent);
console.log('types.js缓存已更新');
}
} catch (error) {
console.warn('更新types.js缓存失败:', error);

Some files were not shown because too many files have changed in this diff Show More