diff --git a/parser/src/main/java/cn/qaiu/parser/impl/LzFolderCursor.java b/parser/src/main/java/cn/qaiu/parser/impl/LzFolderCursor.java
new file mode 100644
index 0000000..8918c6d
--- /dev/null
+++ b/parser/src/main/java/cn/qaiu/parser/impl/LzFolderCursor.java
@@ -0,0 +1,116 @@
+package cn.qaiu.parser.impl;
+
+import cn.qaiu.util.CommonUtils;
+import io.vertx.core.json.JsonObject;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+/**
+ * 蓝奏目录「下一页」游标。
+ *
+ * filemoreajax 的 t/k 由分享页下发,上游按这组令牌记录已翻到第几页:同一组令牌可以取
+ * 「已取过的最大页 + 1」以内的任意页;换一组新令牌直接跳到第 N 页会返回 zt=4「请刷新,重试」。
+ * 所以加载更多时把上一页用过的表单(不含密码和页码)交还给客户端,下次直接续翻。
+ *
+ * 游标来自客户端,不可信:只用于表单字段,POST 主机仍由服务端按分享链接决定;
+ * 分享 key、页码、路径对不上一律当作没有游标,回退到从第 1 页顺序翻。
+ */
+final class LzFolderCursor {
+
+ private static final int VERSION = 1;
+ private static final Pattern PATH = Pattern.compile("/filemoreajax\\.php\\?file=(\\d+)");
+ private static final Pattern KEY = Pattern.compile("\\w{1,32}");
+ private static final int MAX_VALUE_LENGTH = 256;
+ private static final int MAX_FIELDS = 32;
+
+ final String path;
+ final Map form;
+ final String webpage;
+
+ private LzFolderCursor(String path, Map form, String webpage) {
+ this.path = path;
+ this.form = form;
+ this.webpage = webpage;
+ }
+
+ static String encode(String shareKey, String path, Map form, int nextPage, String webpage) {
+ JsonObject f = new JsonObject();
+ form.forEach((k, v) -> {
+ if (!"pwd".equals(k) && !"pg".equals(k)) {
+ f.put(k, v);
+ }
+ });
+ JsonObject json = new JsonObject()
+ .put("v", VERSION)
+ .put("s", shareKey)
+ .put("p", path)
+ .put("n", nextPage)
+ .put("f", f);
+ if (webpage != null && !webpage.isBlank()) {
+ json.put("w", webpage);
+ }
+ return CommonUtils.urlBase64Encode(json.encode());
+ }
+
+ /**
+ * @return 校验通过的游标;任何不匹配或格式问题都返回 null
+ */
+ static LzFolderCursor decode(String raw, String shareKey, int page) {
+ if (raw == null || raw.isBlank() || raw.length() > 4096) {
+ return null;
+ }
+ try {
+ JsonObject json = new JsonObject(CommonUtils.urlBase64Decode(raw));
+ if (json.getInteger("v", 0) != VERSION) {
+ return null;
+ }
+ if (shareKey == null || !shareKey.equals(json.getString("s"))) {
+ return null;
+ }
+ if (json.getInteger("n", -1) != page) {
+ return null;
+ }
+ String path = json.getString("p");
+ var m = path == null ? null : PATH.matcher(path);
+ if (m == null || !m.matches()) {
+ return null;
+ }
+ JsonObject f = json.getJsonObject("f");
+ if (f == null || f.size() > MAX_FIELDS) {
+ return null;
+ }
+ Map form = new LinkedHashMap<>();
+ for (String key : f.fieldNames()) {
+ Object v = f.getValue(key);
+ if (!KEY.matcher(key).matches() || v == null) {
+ return null;
+ }
+ String s = String.valueOf(v);
+ if (s.length() > MAX_VALUE_LENGTH || s.chars().anyMatch(c -> c < 0x20)) {
+ return null;
+ }
+ form.put(key, s);
+ }
+ if (!m.group(1).equals(form.get("fid")) || !form.containsKey("t") || !form.containsKey("k")) {
+ return null;
+ }
+ String webpage = json.getString("w");
+ if (webpage != null && (webpage.length() > MAX_VALUE_LENGTH || !webpage.matches("[\\w\\-=.%]+"))) {
+ webpage = null;
+ }
+ return new LzFolderCursor(path, form, webpage);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ /** 本次请求用的表单:游标字段 + 当前密码 + 目标页。 */
+ Map formFor(String pwd, int page) {
+ Map out = new LinkedHashMap<>(form);
+ out.put("pg", String.valueOf(page));
+ out.put("pwd", pwd == null ? "" : pwd);
+ return out;
+ }
+}
diff --git a/parser/src/main/java/cn/qaiu/parser/impl/LzTool.java b/parser/src/main/java/cn/qaiu/parser/impl/LzTool.java
index bf8d0bc..49e7f78 100644
--- a/parser/src/main/java/cn/qaiu/parser/impl/LzTool.java
+++ b/parser/src/main/java/cn/qaiu/parser/impl/LzTool.java
@@ -3,6 +3,7 @@ package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
+import cn.qaiu.parser.FolderPaging;
import cn.qaiu.parser.PanBase;
import cn.qaiu.util.*;
import io.netty.handler.codec.http.cookie.DefaultCookie;
@@ -11,6 +12,7 @@ import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
+import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.ProxyOptions;
import io.vertx.core.net.ProxyType;
@@ -25,9 +27,11 @@ import java.io.ByteArrayInputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
+import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -73,6 +77,17 @@ public class LzTool extends PanBase {
"https://www.lanzoux.com",
"https://wwww.lanzoux.com"
);
+ /** filemoreajax.php 每页条数(含 id=-1 占位项),不足即最后一页。 */
+ static final int LZ_FOLDER_PAGE_SIZE = 50;
+ /** 目录页不渲染的占位项 id。 */
+ static final String LZ_PLACEHOLDER_ID = "-1";
+ /** 同一组 t/k 两次 filemoreajax 间隔不足约 1.5 秒时返回 zt=4「请刷新,重试」。 */
+ static final int LZ_ZT_REFRESH = 4;
+ static final long LZ_PAGE_INTERVAL_MS = 1500;
+ static final long LZ_REFRESH_RETRY_DELAY_MS = 2000;
+ static final int LZ_REFRESH_RETRIES = 2;
+ /** 无游标时从第 1 页顺序翻的最大页数,保证一次请求能在路由超时(默认 15 秒)内完成。 */
+ static final int LZ_MAX_WALK_PAGES = 6;
/** 分享页 / ajax 请求超时 */
private static final long REQUEST_TIMEOUT = 8000;
/** 下载域跳转与二次验证超时,链路更长 */
@@ -1085,7 +1100,7 @@ public class LzTool extends PanBase {
private static String originOf(String url, String fallback) {
try {
URL u = new URL(url);
- return u.getProtocol() + "://" + u.getHost();
+ return u.getProtocol() + "://" + u.getHost() + (u.getPort() == -1 ? "" : ":" + u.getPort());
} catch (Exception e) {
return fallback;
}
@@ -1164,16 +1179,69 @@ public class LzTool extends PanBase {
final String sUrl = resolveShareUrl();
final String pwd = shareLinkInfo.getSharePassword();
+ final int page;
+ try {
+ page = FolderPaging.pageOrFirst(shareLinkInfo);
+ } catch (IllegalArgumentException e) {
+ listPromise.fail(baseMsg() + e.getMessage());
+ return listPromise.future();
+ }
- // 目录页用移动端 UA。桌面 Chrome 访问旧目录(如 /b66477)常返回空白风控页,
- // 页面里没有 filemoreajax,随后会被误报成「获取失败1,可能分享已失效」。
- getWithArg1Retry(sUrl, folderPageHeaders(sUrl))
- .onSuccess(html -> handleFileListParse(html, pwd, sUrl, listPromise))
- .onFailure(listPromise::fail);
+ LzFolderCursor cursor = page > 1
+ ? LzFolderCursor.decode(FolderPaging.cursor(shareLinkInfo), shareLinkInfo.getShareKey(), page)
+ : null;
+ if (cursor == null) {
+ if (page > LZ_MAX_WALK_PAGES) {
+ listPromise.fail(baseMsg() + walkLimitMessage(page));
+ return listPromise.future();
+ }
+ loadFolderPage(sUrl, pwd, page, listPromise);
+ return listPromise.future();
+ }
+ if (cursor.webpage != null) {
+ shareLinkInfo.getOtherParam().put("webpage", cursor.webpage);
+ }
+ AjaxCall call = new AjaxCall(cursor.path, cursor.formFor(pwd, page));
+ postFolderPage(sUrl, call, page, 0, reply -> {
+ if (reply.zt() == 1) {
+ finishFolderPage(call, page, reply, listPromise);
+ } else if (reply.zt() == 2) {
+ finishEmptyFolderPage(page, listPromise);
+ } else if (reply.zt() == LZ_ZT_REFRESH) {
+ fallbackFromCursor(sUrl, pwd, page, reply.info(), listPromise);
+ } else {
+ listPromise.tryFail(baseMsg() + "蓝奏云目录第 " + page + " 页获取失败: " + reply.info());
+ }
+ }, err -> fallbackFromCursor(sUrl, pwd, page, err.getMessage(), listPromise));
return listPromise.future();
}
- private void handleFileListParse(String html, String pwd, String sUrl, Promise> listPromise) {
+ /** 游标过期(令牌约 10 分钟)或被拒:页码不大时整段重翻,否则让调用方从第 1 页重新加载。 */
+ private void fallbackFromCursor(String sUrl, String pwd, int page, String reason,
+ Promise> listPromise) {
+ log.debug("蓝奏目录游标不可用 page={} reason={}", page, reason);
+ if (page > LZ_MAX_WALK_PAGES) {
+ listPromise.tryFail(baseMsg() + "蓝奏云目录分页游标已失效(" + reason + "),请从第 1 页重新加载");
+ return;
+ }
+ loadFolderPage(sUrl, pwd, page, listPromise);
+ }
+
+ private static String walkLimitMessage(int page) {
+ return "蓝奏云目录需按顺序翻页:第 " + page + " 页请带上一页返回的 nextCursor 请求"
+ + "(无游标最多直接取到第 " + LZ_MAX_WALK_PAGES + " 页)";
+ }
+
+ private void loadFolderPage(String sUrl, String pwd, int page, Promise> listPromise) {
+ // 目录页用移动端 UA。桌面 Chrome 访问旧目录(如 /b66477)常返回空白风控页,
+ // 页面里没有 filemoreajax,随后会被误报成「获取失败1,可能分享已失效」。
+ getWithArg1Retry(sUrl, folderPageHeaders(sUrl))
+ .onSuccess(html -> handleFileListParse(html, pwd, sUrl, page, listPromise))
+ .onFailure(listPromise::fail);
+ }
+
+ private void handleFileListParse(String html, String pwd, String sUrl, int page,
+ Promise> listPromise) {
if (!isLzFolderShare(sUrl, html)) {
listPromise.fail(baseMsg() + "该链接为蓝奏云文件分享,请使用文件解析接口");
return;
@@ -1193,14 +1261,105 @@ public class LzTool extends PanBase {
}
log.debug("解析参数: {}", call.form());
- postAjaxWithFallback(sUrl, call, folderListHeaders(sUrl),
- body -> handleFileListResponse(body, listPromise),
- listPromise::fail);
+ walkFolderPages(sUrl, call, 1, page, listPromise);
} catch (ScriptException | NoSuchMethodException | RuntimeException e) {
listPromise.fail(e);
}
}
+ /**
+ * 同一组 t/k 从第 {@code pg} 页顺序翻到 {@code target} 页。新令牌不能跳页,
+ * 两次请求间隔不足约 1.5 秒会返回 zt=4,所以逐页间隔 {@link #LZ_PAGE_INTERVAL_MS};
+ * 次数受 {@link #LZ_MAX_WALK_PAGES} 限制。
+ */
+ private void walkFolderPages(String sUrl, AjaxCall call, int pg, int target,
+ Promise> listPromise) {
+ postFolderPage(sUrl, call, pg, 0, reply -> {
+ if (reply.zt() == 1) {
+ if (pg == target) {
+ finishFolderPage(call, target, reply, listPromise);
+ } else if (reply.rawCount() < LZ_FOLDER_PAGE_SIZE) {
+ finishEmptyFolderPage(target, listPromise);
+ } else {
+ WebClientVertxInit.get().setTimer(LZ_PAGE_INTERVAL_MS,
+ id -> walkFolderPages(sUrl, call, pg + 1, target, listPromise));
+ }
+ return;
+ }
+ if (target == 1) {
+ listPromise.tryFail(baseMsg() + reply.info());
+ } else if (reply.zt() == 2) {
+ finishEmptyFolderPage(target, listPromise);
+ } else {
+ listPromise.tryFail(baseMsg() + "蓝奏云目录第 " + pg + " 页获取失败: " + reply.info()
+ + ";未取到第 " + target + " 页,目录列表不完整,请稍后重试");
+ }
+ }, listPromise::tryFail);
+ }
+
+ /** 取一页;zt=4(请求过快)时同一令牌等一会儿重试,最多 {@link #LZ_REFRESH_RETRIES} 次。 */
+ private void postFolderPage(String sUrl, AjaxCall call, int pg, int attempt,
+ Handler onReply, Handler onFailure) {
+ call.form().put("pg", String.valueOf(pg));
+ postAjaxWithFallback(sUrl, call, folderListHeaders(sUrl), body -> {
+ FolderReply reply = FolderReply.parse(body);
+ if (reply == null) {
+ onFailure.handle(new RuntimeException(baseMsg() + "目录列表返回非JSON"));
+ return;
+ }
+ if (reply.zt() == LZ_ZT_REFRESH && attempt < LZ_REFRESH_RETRIES) {
+ log.debug("蓝奏目录第 {} 页返回 {},{}ms 后重试", pg, reply.info(), LZ_REFRESH_RETRY_DELAY_MS);
+ WebClientVertxInit.get().setTimer(LZ_REFRESH_RETRY_DELAY_MS,
+ id -> postFolderPage(sUrl, call, pg, attempt + 1, onReply, onFailure));
+ return;
+ }
+ onReply.handle(reply);
+ }, onFailure);
+ }
+
+ private void finishEmptyFolderPage(int page, Promise> listPromise) {
+ FolderPaging.pageInfo(shareLinkInfo, page, LZ_FOLDER_PAGE_SIZE, false, null, null, null);
+ listPromise.tryComplete(new ArrayList<>());
+ }
+
+ private void finishFolderPage(AjaxCall call, int page, FolderReply reply, Promise> listPromise) {
+ try {
+ List list = toFolderFileInfos(reply.items());
+ boolean hasMore = reply.rawCount() >= LZ_FOLDER_PAGE_SIZE;
+ String next = hasMore
+ ? LzFolderCursor.encode(shareLinkInfo.getShareKey(), call.path(), call.form(), page + 1,
+ currentWebpage())
+ : null;
+ FolderPaging.pageInfo(shareLinkInfo, page, LZ_FOLDER_PAGE_SIZE, hasMore, null, null, next);
+ listPromise.tryComplete(list);
+ } catch (Exception e) {
+ listPromise.tryFail(e);
+ }
+ }
+
+ /** filemoreajax.php 单页响应;text 不是数组时 items 为空。 */
+ record FolderReply(int zt, String info, List items, int rawCount) {
+ static FolderReply parse(String body) {
+ JsonObject json = parseLzJson(body);
+ if (json == null) {
+ return null;
+ }
+ Integer zt = jsonInt(json, "zt");
+ Object info = json.getValue("info");
+ List items = new ArrayList<>();
+ Object text = json.getValue("text");
+ if (text instanceof JsonArray arr) {
+ for (Object o : arr) {
+ if (o instanceof JsonObject item) {
+ items.add(item);
+ }
+ }
+ }
+ return new FolderReply(zt == null ? -1 : zt, info == null ? null : String.valueOf(info),
+ items, items.size());
+ }
+ }
+
/** 正则匹配不到 filemoreajax 块时,回退到执行页面 JS 取参数。 */
private AjaxCall folderAjaxFromJs(String html, String pwd) throws ScriptException, NoSuchMethodException {
String jsText = getJsByPwd(pwd, html, "var urls =window.location.href");
@@ -1293,66 +1452,59 @@ public class LzTool extends PanBase {
return u;
}
- private void handleFileListResponse(String responseBody, Promise> listPromise) {
- try {
- JsonObject fileListJson = parseLzJson(responseBody);
- if (fileListJson == null) {
- listPromise.fail(baseMsg() + "目录列表返回非JSON");
- return;
+ /**
+ * 目录页 JS 不渲染 id 为 -1 的占位项(如「***.apk」),这里同样跳过;它仍计入每页 50 条。
+ * 同一页里重复的 id 只保留第一条。
+ */
+ private List toFolderFileInfos(List items) {
+ List list = new ArrayList<>();
+ Set seen = new HashSet<>();
+ for (JsonObject fileJson : items) {
+ /*
+ {
+ "icon": "apk",
+ "t": 0,
+ "id": "iULV2n4361c",
+ "name_all": "xx.apk",
+ "size": "49.8 M",
+ "time": "2021-03-19",
+ "duan": "in4361",
+ "p_ico": 0
}
- Integer zt = fileListJson.getInteger("zt");
- if (zt == null || zt != 1) {
- listPromise.fail(baseMsg() + fileListJson.getString("info"));
- return;
+ */
+ String id = fileJson.getString("id");
+ if (id == null || id.isBlank() || LZ_PLACEHOLDER_ID.equals(id) || !seen.add(id)) {
+ continue;
}
- List list = new ArrayList<>();
- fileListJson.getJsonArray("text").forEach(item -> {
- /*
- {
- "icon": "apk",
- "t": 0,
- "id": "iULV2n4361c",
- "name_all": "xx.apk",
- "size": "49.8 M",
- "time": "2021-03-19",
- "duan": "in4361",
- "p_ico": 0
- }
- */
- JsonObject fileJson = (JsonObject) item;
- FileInfo fileInfo = new FileInfo();
- String size = fileJson.getString("size");
- Long sizeNum = FileSizeConverter.convertToBytes(size);
- String panType = shareLinkInfo.getType();
- String id = fileJson.getString("id");
- String fileName = fileJson.getString("name_all");
- // 构建 base64 参数,用于 /v2/redirectUrl 接口
- JsonObject paramJson = new JsonObject()
- .put("id", id)
- .put("fileName", fileName)
- .put("shareKey", shareLinkInfo.getShareKey());
- String webpage = currentWebpage();
- if (webpage != null) {
- paramJson.put("webpage", webpage);
- }
- String param = CommonUtils.urlBase64Encode(paramJson.encode());
- fileInfo.setFileName(fileName)
- .setFileId(id)
- .setCreateTime(fileJson.getString("time"))
- .setFileType(fileJson.getString("icon"))
- .setSizeStr(fileJson.getString("size"))
- .setSize(sizeNum)
- .setPanType(panType)
- .setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(), panType, param))
- .setPreviewUrl(String.format("%s/v2/view/%s/%s", getDomainName(),
- shareLinkInfo.getType(), id));
- log.debug("文件信息: {}", fileInfo);
- list.add(fileInfo);
- });
- listPromise.complete(list);
- } catch (Exception e) {
- listPromise.fail(e);
+ FileInfo fileInfo = new FileInfo();
+ String size = fileJson.getString("size");
+ Long sizeNum = FileSizeConverter.convertToBytes(size);
+ String panType = shareLinkInfo.getType();
+ String fileName = fileJson.getString("name_all");
+ // 构建 base64 参数,用于 /v2/redirectUrl 接口
+ JsonObject paramJson = new JsonObject()
+ .put("id", id)
+ .put("fileName", fileName)
+ .put("shareKey", shareLinkInfo.getShareKey());
+ String webpage = currentWebpage();
+ if (webpage != null) {
+ paramJson.put("webpage", webpage);
+ }
+ String param = CommonUtils.urlBase64Encode(paramJson.encode());
+ fileInfo.setFileName(fileName)
+ .setFileId(id)
+ .setCreateTime(fileJson.getString("time"))
+ .setFileType(fileJson.getString("icon"))
+ .setSizeStr(fileJson.getString("size"))
+ .setSize(sizeNum)
+ .setPanType(panType)
+ .setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", getDomainName(), panType, param))
+ .setPreviewUrl(String.format("%s/v2/view/%s/%s", getDomainName(),
+ shareLinkInfo.getType(), id));
+ log.debug("文件信息: {}", fileInfo);
+ list.add(fileInfo);
}
+ return list;
}
@Override
diff --git a/parser/src/test/java/cn/qaiu/parser/impl/LzFolderCursorTest.java b/parser/src/test/java/cn/qaiu/parser/impl/LzFolderCursorTest.java
new file mode 100644
index 0000000..508545a
--- /dev/null
+++ b/parser/src/test/java/cn/qaiu/parser/impl/LzFolderCursorTest.java
@@ -0,0 +1,76 @@
+package cn.qaiu.parser.impl;
+
+import cn.qaiu.util.CommonUtils;
+import io.vertx.core.json.JsonObject;
+import org.junit.Test;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+public class LzFolderCursorTest {
+
+ private static final String PATH = "/filemoreajax.php?file=66477";
+
+ private static Map form() {
+ Map form = new LinkedHashMap<>();
+ form.put("lx", "2");
+ form.put("fid", "66477");
+ form.put("uid", "234978");
+ form.put("pg", "1");
+ form.put("t", "1795564485");
+ form.put("k", "abc");
+ form.put("pwd", "secret");
+ return form;
+ }
+
+ @Test
+ public void roundTripDropsPasswordAndUsesRequestedPage() {
+ String raw = LzFolderCursor.encode("b66477", PATH, form(), 2, "wp1");
+ assertFalse(CommonUtils.urlBase64Decode(raw).contains("secret"));
+ LzFolderCursor cursor = LzFolderCursor.decode(raw, "b66477", 2);
+ assertNotNull(cursor);
+ assertEquals(PATH, cursor.path);
+ assertEquals("wp1", cursor.webpage);
+ Map next = cursor.formFor("newpwd", 2);
+ assertEquals("2", next.get("pg"));
+ assertEquals("newpwd", next.get("pwd"));
+ assertEquals("1795564485", next.get("t"));
+ }
+
+ @Test
+ public void mismatchedShareOrPageIsIgnored() {
+ String raw = LzFolderCursor.encode("b66477", PATH, form(), 2, null);
+ assertNull(LzFolderCursor.decode(raw, "b00000", 2));
+ assertNull(LzFolderCursor.decode(raw, "b66477", 3));
+ assertNull(LzFolderCursor.decode("not-base64!", "b66477", 2));
+ assertNull(LzFolderCursor.decode(null, "b66477", 2));
+ }
+
+ @Test
+ public void tamperedPathOrFieldsAreIgnored() {
+ assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", "http://evil/x", form(), 2, null), "b1", 2));
+ assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", "/filemoreajax.php?file=1", form(), 2, null), "b1", 2));
+ Map bad = form();
+ bad.put("x\ny", "1");
+ assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", PATH, bad, 2, null), "b1", 2));
+ Map noToken = form();
+ noToken.remove("t");
+ assertNull(LzFolderCursor.decode(LzFolderCursor.encode("b1", PATH, noToken, 2, null), "b1", 2));
+ JsonObject json = new JsonObject(CommonUtils.urlBase64Decode(LzFolderCursor.encode("b1", PATH, form(), 2, null)));
+ json.put("v", 99);
+ assertNull(LzFolderCursor.decode(CommonUtils.urlBase64Encode(json.encode()), "b1", 2));
+ }
+
+ @Test
+ public void unsafeWebpageIsDropped() {
+ String raw = LzFolderCursor.encode("b1", PATH, form(), 2, "a/../../x?y");
+ LzFolderCursor cursor = LzFolderCursor.decode(raw, "b1", 2);
+ assertNotNull(cursor);
+ assertNull(cursor.webpage);
+ }
+}
diff --git a/parser/src/test/java/cn/qaiu/parser/impl/LzFolderPagingLiveTest.java b/parser/src/test/java/cn/qaiu/parser/impl/LzFolderPagingLiveTest.java
new file mode 100644
index 0000000..5d28715
--- /dev/null
+++ b/parser/src/test/java/cn/qaiu/parser/impl/LzFolderPagingLiveTest.java
@@ -0,0 +1,175 @@
+package cn.qaiu.parser.impl;
+
+import cn.qaiu.WebClientVertxInit;
+import cn.qaiu.entity.FileInfo;
+import cn.qaiu.parser.FolderPaging;
+import cn.qaiu.parser.ParserCreate;
+import io.vertx.core.Vertx;
+import io.vertx.core.json.JsonObject;
+import org.junit.AfterClass;
+import org.junit.Assume;
+import org.junit.Test;
+
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.time.Duration;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * 蓝奏目录分页真实联调(b66477 约 93 页,每页 50 条)。默认不跑:
+ * mvn -pl parser -DskipTests=false -Dlz.live=true -Dtest=LzFolderPagingLiveTest test
+ * 加 -Dlz.live.full=true 会顺序翻完整个目录(约 2 分钟)。
+ */
+public class LzFolderPagingLiveTest {
+
+ private static final String OUI = "https://pan.lanzoui.com/b66477";
+ private static final String OUG = "https://pan.lanzoug.com/b66477";
+
+ private static Vertx vertx;
+
+ @AfterClass
+ public static void close() {
+ if (vertx != null) {
+ vertx.close();
+ }
+ }
+
+ record Page(List list, JsonObject info) {
+ String cursor() {
+ return info.getString("nextCursor");
+ }
+ }
+
+ @Test
+ public void pacedPagesOneToThreeAreFullAndDistinct() throws Exception {
+ liveOnly();
+ Set ids = new HashSet<>();
+ Page page = page(OUI, null, 1, null);
+ for (int n = 1; n <= 3; n++) {
+ if (n > 1) {
+ Thread.sleep(5000);
+ page = page(OUI, null, n, page.cursor());
+ }
+ // 上游每页 50 条原始项,其中 id=-1 的占位项(如 ***.apk)已被过滤
+ assertTrue("第 " + n + " 页 " + page.list().size(), page.list().size() >= 45 && page.list().size() <= 50);
+ assertEquals(Integer.valueOf(50), page.info().getInteger("pageSize"));
+ assertTrue(page.info().getBoolean("hasMore"));
+ assertNotNull(page.cursor());
+ page.list().forEach(f -> assertTrue("重复 " + f.getFileId(), ids.add(f.getFileId())));
+ }
+ }
+
+ /** 上游对紧跟的下一页常回 zt=4「请刷新,重试0」:必须重试成功或明确报错,不能当末页。 */
+ @Test
+ public void immediateNextPageIsNeverReportedAsEnd() throws Exception {
+ liveOnly();
+ Page first = page(OUG, null, 1, null);
+ try {
+ Page second = page(OUG, null, 2, first.cursor());
+ assertFalse(second.list().isEmpty());
+ assertTrue(second.info().getBoolean("hasMore"));
+ } catch (ExecutionException e) {
+ String msg = e.getCause().getMessage();
+ assertTrue(msg, msg.contains("稍后重试") || msg.contains("重新加载"));
+ }
+ Page again = page(OUG, null, 2, null);
+ assertEquals(50, again.list().size());
+ assertTrue(again.info().getBoolean("hasMore"));
+ }
+
+ @Test
+ public void passwordFolderIsSinglePageAndPageTwoIsEmpty() throws Exception {
+ liveOnly();
+ Page first = page("https://moteam.lanzoum.com/b00yaejvte", "1234", 1, null);
+ assertFalse(first.list().isEmpty());
+ assertFalse(first.info().getBoolean("hasMore"));
+ assertNull(first.cursor());
+ Thread.sleep(2000);
+ Page second = page("https://moteam.lanzoum.com/b00yaejvte", "1234", 2, null);
+ assertTrue(second.list().isEmpty());
+ assertFalse(second.info().getBoolean("hasMore"));
+ }
+
+ @Test
+ public void fileFromSecondPageDownloads() throws Exception {
+ liveOnly();
+ Page first = page(OUI, null, 1, null);
+ Thread.sleep(2000);
+ Page second = page(OUI, null, 2, first.cursor());
+ FileInfo small = second.list().get(0);
+ for (FileInfo f : second.list()) {
+ if (f.getSize() != null && small.getSize() != null && f.getSize() < small.getSize()) {
+ small = f;
+ }
+ }
+ String url = ParserCreate.fromShareUrl("https://pan.lanzoui.com/" + small.getFileId())
+ .createTool().parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
+ HttpResponse response = HttpClient.newBuilder()
+ .followRedirects(HttpClient.Redirect.NORMAL)
+ .connectTimeout(Duration.ofSeconds(20))
+ .build()
+ .send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(120)).GET().build(),
+ HttpResponse.BodyHandlers.ofByteArray());
+ assertEquals(200, response.statusCode());
+ assertTrue(response.body().length > 0);
+ }
+
+ @Test
+ public void wholeFolderWithCursorHasNoDuplicatesAndEnds() throws Exception {
+ liveOnly();
+ Assume.assumeTrue(Boolean.getBoolean("lz.live.full"));
+ Set ids = new HashSet<>();
+ String cursor = null;
+ int pages = 0;
+ int lastSize = -1;
+ for (int n = 1; n <= FolderPaging.MAX_PAGE; n++) {
+ Page page = page(OUI, null, n, cursor);
+ pages = n;
+ lastSize = page.list().size();
+ page.list().forEach(f -> assertTrue("重复 " + f.getFileId(), ids.add(f.getFileId())));
+ if (!page.info().getBoolean("hasMore")) {
+ break;
+ }
+ cursor = page.cursor();
+ assertNotNull(cursor);
+ Thread.sleep(800);
+ }
+ assertTrue("应有多页", pages > 2);
+ assertTrue("末页应不足 50 条", lastSize < 50);
+ assertTrue(ids.size() > (pages - 1) * 49);
+ }
+
+ private static Page page(String url, String pwd, int page, String cursor) throws Exception {
+ ParserCreate create = ParserCreate.fromShareUrl(url);
+ if (pwd != null) {
+ create.setShareLinkInfoPwd(pwd);
+ }
+ create.getShareLinkInfo().getOtherParam().put(FolderPaging.PAGE, page);
+ if (cursor != null) {
+ create.getShareLinkInfo().getOtherParam().put(FolderPaging.CURSOR, cursor);
+ }
+ List list = create.createTool().parseFileList()
+ .toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
+ return new Page(list, FolderPaging.pageInfo(create.getShareLinkInfo()));
+ }
+
+ private static void liveOnly() {
+ Assume.assumeTrue(Boolean.getBoolean("lz.live"));
+ if (vertx == null) {
+ vertx = Vertx.vertx();
+ WebClientVertxInit.init(vertx);
+ }
+ }
+}
diff --git a/parser/src/test/java/cn/qaiu/parser/impl/LzToolFolderPagingTest.java b/parser/src/test/java/cn/qaiu/parser/impl/LzToolFolderPagingTest.java
new file mode 100644
index 0000000..c83d7b7
--- /dev/null
+++ b/parser/src/test/java/cn/qaiu/parser/impl/LzToolFolderPagingTest.java
@@ -0,0 +1,293 @@
+package cn.qaiu.parser.impl;
+
+import cn.qaiu.WebClientVertxInit;
+import cn.qaiu.entity.FileInfo;
+import cn.qaiu.entity.ShareLinkInfo;
+import cn.qaiu.parser.FolderPaging;
+import io.vertx.core.MultiMap;
+import io.vertx.core.Vertx;
+import io.vertx.core.http.HttpServer;
+import io.vertx.core.json.JsonArray;
+import io.vertx.core.json.JsonObject;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiFunction;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/**
+ * 蓝奏目录分页离线回归:本地模拟分享页与 filemoreajax.php。
+ * 上游真实行为(b66477 实测):每页 50 条,不足 50 即末页;zt=2「没有了」;
+ * 同一组 t/k 请求过快返回 {@code {"zt":4,"info":"请刷新,重试0","text":0}},隔约 2 秒同页可正常取到。
+ */
+public class LzToolFolderPagingTest {
+
+ private static final String SHARE_KEY = "b66477";
+ private static final String TOKEN_T = "1700000000";
+ private static final String TOKEN_K = "test-k-token";
+ private static final String RATE_LIMITED = "{\"zt\":4,\"info\":\"请刷新,重试0\",\"text\":0}";
+
+ private Vertx vertx;
+ private HttpServer server;
+ private final AtomicInteger pageGets = new AtomicInteger();
+ private final List ajaxForms = new CopyOnWriteArrayList<>();
+ private final Map ajaxCountByPg = new ConcurrentHashMap<>();
+ /** (pg, 该页第几次请求 从 1 开始) -> 响应体;返回 null 用默认三页数据 */
+ private volatile BiFunction ajax = (pg, n) -> null;
+
+ @Before
+ public void setup() throws Exception {
+ vertx = Vertx.vertx();
+ WebClientVertxInit.init(vertx);
+ server = vertx.createHttpServer().requestHandler(req -> {
+ if ("GET".equals(req.method().name()) && req.path().equals("/" + SHARE_KEY)) {
+ pageGets.incrementAndGet();
+ req.response().putHeader("Content-Type", "text/html; charset=utf-8").end(folderHtml());
+ } else if (req.path().equals("/filemoreajax.php")) {
+ req.setExpectMultipart(true);
+ req.endHandler(v -> {
+ MultiMap form = MultiMap.caseInsensitiveMultiMap().addAll(req.formAttributes());
+ ajaxForms.add(form);
+ int pg = Integer.parseInt(form.get("pg"));
+ int n = ajaxCountByPg.computeIfAbsent(String.valueOf(pg), k -> new AtomicInteger()).incrementAndGet();
+ String body = ajax.apply(pg, n);
+ req.response().putHeader("Content-Type", "text/json; charset=utf-8")
+ .end(body != null ? body : defaultPage(pg));
+ });
+ } else {
+ req.response().setStatusCode(404).end();
+ }
+ }).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
+ }
+
+ @After
+ public void cleanup() throws Exception {
+ server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
+ vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
+ }
+
+ @Test
+ public void defaultRequestStillReturnsFirstPageWithoutPlaceholder() throws Exception {
+ ShareLinkInfo info = info(null, null);
+ List list = list(info);
+ assertEquals(49, list.size());
+ assertTrue(list.stream().noneMatch(f -> "-1".equals(f.getFileId())));
+ assertEquals("p1-0", list.get(0).getFileId());
+ assertTrue(list.get(0).getParserUrl().startsWith("http://nfd.test/v2/redirectUrl/lz/"));
+ JsonObject pageInfo = FolderPaging.pageInfo(info);
+ assertTrue(pageInfo.getBoolean("hasMore"));
+ assertEquals(2, (int) pageInfo.getInteger("nextPage"));
+ assertNotNull(pageInfo.getString("nextCursor"));
+ assertEquals(1, pageGets.get());
+ assertEquals("1", ajaxForms.get(0).get("pg"));
+ assertEquals("secret", ajaxForms.get(0).get("pwd"));
+ }
+
+ @Test
+ public void rateLimitedNextPageIsRetriedNotTreatedAsLastPage() throws Exception {
+ ajax = (pg, n) -> pg == 2 && n == 1 ? RATE_LIMITED : null;
+ ShareLinkInfo info = info(2, null);
+ List list = list(info);
+ assertEquals(50, list.size());
+ assertEquals("p2-0", list.get(0).getFileId());
+ JsonObject pageInfo = FolderPaging.pageInfo(info);
+ assertTrue("zt=4 不能被当作末页", pageInfo.getBoolean("hasMore"));
+ assertEquals(2, ajaxCountByPg.get("2").get());
+ }
+
+ @Test
+ public void persistentRateLimitFailsWithRetryableErrorInsteadOfEmptyEnd() throws Exception {
+ ajax = (pg, n) -> pg == 2 ? RATE_LIMITED : null;
+ ShareLinkInfo info = info(2, null);
+ try {
+ list(info);
+ fail("zt=4 一直不恢复时必须报错,不能返回空列表或 hasMore=false");
+ } catch (ExecutionException e) {
+ String msg = e.getCause().getMessage();
+ assertTrue(msg, msg.contains("请刷新,重试0"));
+ assertTrue(msg, msg.contains("不完整"));
+ assertTrue(msg, msg.contains("稍后重试"));
+ }
+ assertNull(FolderPaging.pageInfo(info));
+ assertEquals(1 + LzTool.LZ_REFRESH_RETRIES, ajaxCountByPg.get("2").get());
+ }
+
+ @Test
+ public void cursorContinuesWithSameTokenWithoutReloadingPage() throws Exception {
+ ShareLinkInfo first = info(1, null);
+ list(first);
+ String cursor = FolderPaging.pageInfo(first).getString("nextCursor");
+
+ ShareLinkInfo second = info(2, cursor);
+ List page2 = list(second);
+ assertEquals(50, page2.size());
+ assertEquals(1, pageGets.get());
+ MultiMap last = ajaxForms.get(ajaxForms.size() - 1);
+ assertEquals("2", last.get("pg"));
+ assertEquals(TOKEN_T, last.get("t"));
+ assertEquals(TOKEN_K, last.get("k"));
+ assertEquals("secret", last.get("pwd"));
+
+ ShareLinkInfo third = info(3, FolderPaging.pageInfo(second).getString("nextCursor"));
+ List page3 = list(third);
+ assertEquals(9, page3.size());
+ JsonObject end = FolderPaging.pageInfo(third);
+ assertFalse(end.getBoolean("hasMore"));
+ assertNull(end.getString("nextCursor"));
+ assertNull(end.getValue("nextPage"));
+
+ Set ids = new HashSet<>();
+ for (List page : List.of(list(info(1, null)), page2, page3)) {
+ page.forEach(f -> assertTrue("跨页重复 " + f.getFileId(), ids.add(f.getFileId())));
+ }
+ assertEquals(49 + 50 + 9, ids.size());
+ }
+
+ @Test
+ public void rateLimitedCursorRequestRetriesSamePage() throws Exception {
+ ShareLinkInfo first = info(1, null);
+ list(first);
+ ajax = (pg, n) -> pg == 2 && n == 1 ? RATE_LIMITED : null;
+ ShareLinkInfo second = info(2, FolderPaging.pageInfo(first).getString("nextCursor"));
+ assertEquals(50, list(second).size());
+ assertTrue(FolderPaging.pageInfo(second).getBoolean("hasMore"));
+ assertEquals(1, pageGets.get());
+ }
+
+ @Test
+ public void pastLastPageIsEmptyAndEnds() throws Exception {
+ ajax = (pg, n) -> pg == 3 ? page(pg, 50) : pg == 4 ? "{\"zt\":2,\"info\":\"没有了\",\"text\":\"no file\"}" : null;
+ ShareLinkInfo third = info(3, null);
+ list(third);
+ ShareLinkInfo fourth = info(4, FolderPaging.pageInfo(third).getString("nextCursor"));
+ List list = list(fourth);
+ assertTrue(list.isEmpty());
+ assertFalse(FolderPaging.pageInfo(fourth).getBoolean("hasMore"));
+ }
+
+ @Test
+ public void walkStopsAtShortPageWhenTargetIsBeyondEnd() throws Exception {
+ ShareLinkInfo info = info(5, null);
+ assertTrue(list(info).isEmpty());
+ assertFalse(FolderPaging.pageInfo(info).getBoolean("hasMore"));
+ assertEquals(null, ajaxCountByPg.get("4"));
+ }
+
+ @Test
+ public void deepPageWithoutCursorFailsFastWithHint() throws Exception {
+ ShareLinkInfo info = info(LzTool.LZ_MAX_WALK_PAGES + 1, null);
+ try {
+ list(info);
+ fail();
+ } catch (ExecutionException e) {
+ assertTrue(e.getCause().getMessage().contains("nextCursor"));
+ }
+ assertEquals(0, pageGets.get());
+ assertTrue(ajaxForms.isEmpty());
+ }
+
+ @Test
+ public void foreignCursorIsIgnored() throws Exception {
+ String foreign = LzFolderCursor.encode("bOTHER", "/filemoreajax.php?file=66477",
+ Map.of("fid", "66477", "t", "x", "k", "y"), 2, null);
+ ShareLinkInfo info = info(2, foreign);
+ assertEquals(50, list(info).size());
+ assertEquals(1, pageGets.get());
+ assertTrue(ajaxForms.stream().noneMatch(f -> "x".equals(f.get("t"))));
+ }
+
+ @Test
+ public void emptyFolderKeepsLegacyFailure() throws Exception {
+ ajax = (pg, n) -> "{\"zt\":2,\"info\":\"没有文件\",\"text\":\"no file\"}";
+ try {
+ list(info(null, null));
+ fail();
+ } catch (ExecutionException e) {
+ assertTrue(e.getCause().getMessage().contains("没有文件"));
+ }
+ }
+
+ private List list(ShareLinkInfo info) throws Exception {
+ return new LzTool(info).parseFileList().toCompletionStage().toCompletableFuture().get(30, TimeUnit.SECONDS);
+ }
+
+ private ShareLinkInfo info(Integer page, String cursor) {
+ String url = "http://127.0.0.1:" + server.actualPort() + "/" + SHARE_KEY;
+ ShareLinkInfo info = ShareLinkInfo.newBuilder().type("lz").panName("蓝奏云").shareKey(SHARE_KEY)
+ .shareUrl(url).standardUrl(url).sharePassword("secret").build();
+ info.getOtherParam().put("domainName", "http://nfd.test");
+ if (page != null) {
+ info.getOtherParam().put(FolderPaging.PAGE, page);
+ }
+ if (cursor != null) {
+ info.getOtherParam().put(FolderPaging.CURSOR, cursor);
+ }
+ return info;
+ }
+
+ private static String folderHtml() {
+ return """
+
+
+ """.formatted(TOKEN_T, TOKEN_K);
+ }
+
+ /** 默认三页:50(含一个 -1 占位)、50、9。 */
+ private static String defaultPage(int pg) {
+ return switch (pg) {
+ case 1, 2 -> page(pg, 50);
+ case 3 -> page(pg, 9);
+ default -> "{\"zt\":2,\"info\":\"没有了\",\"text\":\"no file\"}";
+ };
+ }
+
+ private static String page(int pg, int count) {
+ JsonArray text = new JsonArray();
+ for (int i = 0; i < count; i++) {
+ String id = pg == 1 && i == 10 ? "-1" : "p" + pg + "-" + i;
+ text.add(new JsonObject().put("icon", "apk").put("t", 0).put("id", id)
+ .put("name_all", id + ".apk").put("size", "1.0 M").put("time", "2023-03-08"));
+ }
+ return new JsonObject().put("zt", 1).put("info", "sucess").put("text", text).encode();
+ }
+}